babylon.max.js 3.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467
  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 Color3 = (function () {
  67. /**
  68. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  69. */
  70. function Color3(r, g, b) {
  71. if (r === void 0) { r = 0; }
  72. if (g === void 0) { g = 0; }
  73. if (b === void 0) { b = 0; }
  74. this.r = r;
  75. this.g = g;
  76. this.b = b;
  77. }
  78. /**
  79. * Returns a string with the Color3 current values.
  80. */
  81. Color3.prototype.toString = function () {
  82. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  83. };
  84. /**
  85. * Returns the string "Color3".
  86. */
  87. Color3.prototype.getClassName = function () {
  88. return "Color3";
  89. };
  90. /**
  91. * Returns the Color3 hash code.
  92. */
  93. Color3.prototype.getHashCode = function () {
  94. var hash = this.r || 0;
  95. hash = (hash * 397) ^ (this.g || 0);
  96. hash = (hash * 397) ^ (this.b || 0);
  97. return hash;
  98. };
  99. // Operators
  100. /**
  101. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  102. * Returns the Color3.
  103. */
  104. Color3.prototype.toArray = function (array, index) {
  105. if (index === undefined) {
  106. index = 0;
  107. }
  108. array[index] = this.r;
  109. array[index + 1] = this.g;
  110. array[index + 2] = this.b;
  111. return this;
  112. };
  113. /**
  114. * Returns a new Color4 object from the current Color3 and the passed alpha.
  115. */
  116. Color3.prototype.toColor4 = function (alpha) {
  117. if (alpha === void 0) { alpha = 1; }
  118. return new Color4(this.r, this.g, this.b, alpha);
  119. };
  120. /**
  121. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  122. */
  123. Color3.prototype.asArray = function () {
  124. var result = [];
  125. this.toArray(result, 0);
  126. return result;
  127. };
  128. /**
  129. * Returns the luminance value (float).
  130. */
  131. Color3.prototype.toLuminance = function () {
  132. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  133. };
  134. /**
  135. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  136. * Returns this new object.
  137. */
  138. Color3.prototype.multiply = function (otherColor) {
  139. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  140. };
  141. /**
  142. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  143. * Returns the current Color3.
  144. */
  145. Color3.prototype.multiplyToRef = function (otherColor, result) {
  146. result.r = this.r * otherColor.r;
  147. result.g = this.g * otherColor.g;
  148. result.b = this.b * otherColor.b;
  149. return this;
  150. };
  151. /**
  152. * Boolean : True if the rgb values are equal to the passed ones.
  153. */
  154. Color3.prototype.equals = function (otherColor) {
  155. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  156. };
  157. /**
  158. * Boolean : True if the rgb values are equal to the passed ones.
  159. */
  160. Color3.prototype.equalsFloats = function (r, g, b) {
  161. return this.r === r && this.g === g && this.b === b;
  162. };
  163. /**
  164. * Multiplies in place each rgb value by scale.
  165. * Returns the updated Color3.
  166. */
  167. Color3.prototype.scale = function (scale) {
  168. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  169. };
  170. /**
  171. * Multiplies the rgb values by scale and stores the result into "result".
  172. * Returns the unmodified current Color3.
  173. */
  174. Color3.prototype.scaleToRef = function (scale, result) {
  175. result.r = this.r * scale;
  176. result.g = this.g * scale;
  177. result.b = this.b * scale;
  178. return this;
  179. };
  180. /**
  181. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  182. */
  183. Color3.prototype.add = function (otherColor) {
  184. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  185. };
  186. /**
  187. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  188. * Returns the unmodified current Color3.
  189. */
  190. Color3.prototype.addToRef = function (otherColor, result) {
  191. result.r = this.r + otherColor.r;
  192. result.g = this.g + otherColor.g;
  193. result.b = this.b + otherColor.b;
  194. return this;
  195. };
  196. /**
  197. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  198. */
  199. Color3.prototype.subtract = function (otherColor) {
  200. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  201. };
  202. /**
  203. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  204. * Returns the unmodified current Color3.
  205. */
  206. Color3.prototype.subtractToRef = function (otherColor, result) {
  207. result.r = this.r - otherColor.r;
  208. result.g = this.g - otherColor.g;
  209. result.b = this.b - otherColor.b;
  210. return this;
  211. };
  212. /**
  213. * Returns a new Color3 copied the current one.
  214. */
  215. Color3.prototype.clone = function () {
  216. return new Color3(this.r, this.g, this.b);
  217. };
  218. /**
  219. * Copies the rgb values from the source in the current Color3.
  220. * Returns the updated Color3.
  221. */
  222. Color3.prototype.copyFrom = function (source) {
  223. this.r = source.r;
  224. this.g = source.g;
  225. this.b = source.b;
  226. return this;
  227. };
  228. /**
  229. * Updates the Color3 rgb values from the passed floats.
  230. * Returns the Color3.
  231. */
  232. Color3.prototype.copyFromFloats = function (r, g, b) {
  233. this.r = r;
  234. this.g = g;
  235. this.b = b;
  236. return this;
  237. };
  238. /**
  239. * Updates the Color3 rgb values from the passed floats.
  240. * Returns the Color3.
  241. */
  242. Color3.prototype.set = function (r, g, b) {
  243. return this.copyFromFloats(r, g, b);
  244. };
  245. /**
  246. * Returns the Color3 hexadecimal code as a string.
  247. */
  248. Color3.prototype.toHexString = function () {
  249. var intR = (this.r * 255) | 0;
  250. var intG = (this.g * 255) | 0;
  251. var intB = (this.b * 255) | 0;
  252. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  253. };
  254. /**
  255. * Returns a new Color3 converted to linear space.
  256. */
  257. Color3.prototype.toLinearSpace = function () {
  258. var convertedColor = new Color3();
  259. this.toLinearSpaceToRef(convertedColor);
  260. return convertedColor;
  261. };
  262. /**
  263. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  264. * Returns the unmodified Color3.
  265. */
  266. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  267. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  268. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  269. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  270. return this;
  271. };
  272. /**
  273. * Returns a new Color3 converted to gamma space.
  274. */
  275. Color3.prototype.toGammaSpace = function () {
  276. var convertedColor = new Color3();
  277. this.toGammaSpaceToRef(convertedColor);
  278. return convertedColor;
  279. };
  280. /**
  281. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  282. * Returns the unmodified Color3.
  283. */
  284. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  285. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  286. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  287. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  288. return this;
  289. };
  290. // Statics
  291. /**
  292. * Creates a new Color3 from the string containing valid hexadecimal values.
  293. */
  294. Color3.FromHexString = function (hex) {
  295. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  296. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  297. return new Color3(0, 0, 0);
  298. }
  299. var r = parseInt(hex.substring(1, 3), 16);
  300. var g = parseInt(hex.substring(3, 5), 16);
  301. var b = parseInt(hex.substring(5, 7), 16);
  302. return Color3.FromInts(r, g, b);
  303. };
  304. /**
  305. * Creates a new Vector3 from the startind index of the passed array.
  306. */
  307. Color3.FromArray = function (array, offset) {
  308. if (offset === void 0) { offset = 0; }
  309. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  310. };
  311. /**
  312. * Creates a new Color3 from integer values ( < 256).
  313. */
  314. Color3.FromInts = function (r, g, b) {
  315. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  316. };
  317. /**
  318. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  319. */
  320. Color3.Lerp = function (start, end, amount) {
  321. var r = start.r + ((end.r - start.r) * amount);
  322. var g = start.g + ((end.g - start.g) * amount);
  323. var b = start.b + ((end.b - start.b) * amount);
  324. return new Color3(r, g, b);
  325. };
  326. Color3.Red = function () { return new Color3(1, 0, 0); };
  327. Color3.Green = function () { return new Color3(0, 1, 0); };
  328. Color3.Blue = function () { return new Color3(0, 0, 1); };
  329. Color3.Black = function () { return new Color3(0, 0, 0); };
  330. Color3.White = function () { return new Color3(1, 1, 1); };
  331. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  332. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  333. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  334. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  335. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  336. return Color3;
  337. }());
  338. BABYLON.Color3 = Color3;
  339. var Color4 = (function () {
  340. /**
  341. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  342. */
  343. function Color4(r, g, b, a) {
  344. this.r = r;
  345. this.g = g;
  346. this.b = b;
  347. this.a = a;
  348. }
  349. // Operators
  350. /**
  351. * Adds in place the passed Color4 values to the current Color4.
  352. * Returns the updated Color4.
  353. */
  354. Color4.prototype.addInPlace = function (right) {
  355. this.r += right.r;
  356. this.g += right.g;
  357. this.b += right.b;
  358. this.a += right.a;
  359. return this;
  360. };
  361. /**
  362. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  363. */
  364. Color4.prototype.asArray = function () {
  365. var result = [];
  366. this.toArray(result, 0);
  367. return result;
  368. };
  369. /**
  370. * Stores from the starting index in the passed array the Color4 successive values.
  371. * Returns the Color4.
  372. */
  373. Color4.prototype.toArray = function (array, index) {
  374. if (index === undefined) {
  375. index = 0;
  376. }
  377. array[index] = this.r;
  378. array[index + 1] = this.g;
  379. array[index + 2] = this.b;
  380. array[index + 3] = this.a;
  381. return this;
  382. };
  383. /**
  384. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  385. */
  386. Color4.prototype.add = function (right) {
  387. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  388. };
  389. /**
  390. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  391. */
  392. Color4.prototype.subtract = function (right) {
  393. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  394. };
  395. /**
  396. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  397. * Returns the Color4.
  398. */
  399. Color4.prototype.subtractToRef = function (right, result) {
  400. result.r = this.r - right.r;
  401. result.g = this.g - right.g;
  402. result.b = this.b - right.b;
  403. result.a = this.a - right.a;
  404. return this;
  405. };
  406. /**
  407. * Creates a new Color4 with the current Color4 values multiplied by scale.
  408. */
  409. Color4.prototype.scale = function (scale) {
  410. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  411. };
  412. /**
  413. * Multiplies the current Color4 values by scale and stores the result in "result".
  414. * Returns the Color4.
  415. */
  416. Color4.prototype.scaleToRef = function (scale, result) {
  417. result.r = this.r * scale;
  418. result.g = this.g * scale;
  419. result.b = this.b * scale;
  420. result.a = this.a * scale;
  421. return this;
  422. };
  423. /**
  424. * Multipy an RGBA Color4 value by another and return a new Color4 object
  425. * @param color The Color4 (RGBA) value to multiply by
  426. * @returns A new Color4.
  427. */
  428. Color4.prototype.multiply = function (color) {
  429. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  430. };
  431. /**
  432. * Multipy an RGBA Color4 value by another and push the result in a reference value
  433. * @param color The Color4 (RGBA) value to multiply by
  434. * @param result The Color4 (RGBA) to fill the result in
  435. * @returns the result Color4.
  436. */
  437. Color4.prototype.multiplyToRef = function (color, result) {
  438. result.r = this.r * color.r;
  439. result.g = this.g * color.g;
  440. result.b = this.b * color.b;
  441. result.a = this.a * color.a;
  442. return result;
  443. };
  444. /**
  445. * Returns a string with the Color4 values.
  446. */
  447. Color4.prototype.toString = function () {
  448. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  449. };
  450. /**
  451. * Returns the string "Color4"
  452. */
  453. Color4.prototype.getClassName = function () {
  454. return "Color4";
  455. };
  456. /**
  457. * Return the Color4 hash code as a number.
  458. */
  459. Color4.prototype.getHashCode = function () {
  460. var hash = this.r || 0;
  461. hash = (hash * 397) ^ (this.g || 0);
  462. hash = (hash * 397) ^ (this.b || 0);
  463. hash = (hash * 397) ^ (this.a || 0);
  464. return hash;
  465. };
  466. /**
  467. * Creates a new Color4 copied from the current one.
  468. */
  469. Color4.prototype.clone = function () {
  470. return new Color4(this.r, this.g, this.b, this.a);
  471. };
  472. /**
  473. * Copies the passed Color4 values into the current one.
  474. * Returns the updated Color4.
  475. */
  476. Color4.prototype.copyFrom = function (source) {
  477. this.r = source.r;
  478. this.g = source.g;
  479. this.b = source.b;
  480. this.a = source.a;
  481. return this;
  482. };
  483. /**
  484. * Copies the passed float values into the current one.
  485. * Returns the updated Color4.
  486. */
  487. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  488. this.r = r;
  489. this.g = g;
  490. this.b = b;
  491. this.a = a;
  492. return this;
  493. };
  494. /**
  495. * Copies the passed float values into the current one.
  496. * Returns the updated Color4.
  497. */
  498. Color4.prototype.set = function (r, g, b, a) {
  499. return this.copyFromFloats(r, g, b, a);
  500. };
  501. /**
  502. * Returns a string containing the hexadecimal Color4 code.
  503. */
  504. Color4.prototype.toHexString = function () {
  505. var intR = (this.r * 255) | 0;
  506. var intG = (this.g * 255) | 0;
  507. var intB = (this.b * 255) | 0;
  508. var intA = (this.a * 255) | 0;
  509. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  510. };
  511. // Statics
  512. /**
  513. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  514. */
  515. Color4.FromHexString = function (hex) {
  516. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  517. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  518. return new Color4(0.0, 0.0, 0.0, 0.0);
  519. }
  520. var r = parseInt(hex.substring(1, 3), 16);
  521. var g = parseInt(hex.substring(3, 5), 16);
  522. var b = parseInt(hex.substring(5, 7), 16);
  523. var a = parseInt(hex.substring(7, 9), 16);
  524. return Color4.FromInts(r, g, b, a);
  525. };
  526. /**
  527. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  528. */
  529. Color4.Lerp = function (left, right, amount) {
  530. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  531. Color4.LerpToRef(left, right, amount, result);
  532. return result;
  533. };
  534. /**
  535. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  536. */
  537. Color4.LerpToRef = function (left, right, amount, result) {
  538. result.r = left.r + (right.r - left.r) * amount;
  539. result.g = left.g + (right.g - left.g) * amount;
  540. result.b = left.b + (right.b - left.b) * amount;
  541. result.a = left.a + (right.a - left.a) * amount;
  542. };
  543. /**
  544. * Creates a new Color4 from the starting index element of the passed array.
  545. */
  546. Color4.FromArray = function (array, offset) {
  547. if (offset === void 0) { offset = 0; }
  548. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  549. };
  550. /**
  551. * Creates a new Color4 from the passed integers ( < 256 ).
  552. */
  553. Color4.FromInts = function (r, g, b, a) {
  554. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  555. };
  556. Color4.CheckColors4 = function (colors, count) {
  557. // Check if color3 was used
  558. if (colors.length === count * 3) {
  559. var colors4 = [];
  560. for (var index = 0; index < colors.length; index += 3) {
  561. var newIndex = (index / 3) * 4;
  562. colors4[newIndex] = colors[index];
  563. colors4[newIndex + 1] = colors[index + 1];
  564. colors4[newIndex + 2] = colors[index + 2];
  565. colors4[newIndex + 3] = 1.0;
  566. }
  567. return colors4;
  568. }
  569. return colors;
  570. };
  571. return Color4;
  572. }());
  573. BABYLON.Color4 = Color4;
  574. var Vector2 = (function () {
  575. /**
  576. * Creates a new Vector2 from the passed x and y coordinates.
  577. */
  578. function Vector2(x, y) {
  579. this.x = x;
  580. this.y = y;
  581. }
  582. /**
  583. * Returns a string with the Vector2 coordinates.
  584. */
  585. Vector2.prototype.toString = function () {
  586. return "{X: " + this.x + " Y:" + this.y + "}";
  587. };
  588. /**
  589. * Returns the string "Vector2"
  590. */
  591. Vector2.prototype.getClassName = function () {
  592. return "Vector2";
  593. };
  594. /**
  595. * Returns the Vector2 hash code as a number.
  596. */
  597. Vector2.prototype.getHashCode = function () {
  598. var hash = this.x || 0;
  599. hash = (hash * 397) ^ (this.y || 0);
  600. return hash;
  601. };
  602. // Operators
  603. /**
  604. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  605. * Returns the Vector2.
  606. */
  607. Vector2.prototype.toArray = function (array, index) {
  608. if (index === void 0) { index = 0; }
  609. array[index] = this.x;
  610. array[index + 1] = this.y;
  611. return this;
  612. };
  613. /**
  614. * Returns a new array with 2 elements : the Vector2 coordinates.
  615. */
  616. Vector2.prototype.asArray = function () {
  617. var result = [];
  618. this.toArray(result, 0);
  619. return result;
  620. };
  621. /**
  622. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  623. * Returns the updated Vector2.
  624. */
  625. Vector2.prototype.copyFrom = function (source) {
  626. this.x = source.x;
  627. this.y = source.y;
  628. return this;
  629. };
  630. /**
  631. * Sets the Vector2 coordinates with the passed floats.
  632. * Returns the updated Vector2.
  633. */
  634. Vector2.prototype.copyFromFloats = function (x, y) {
  635. this.x = x;
  636. this.y = y;
  637. return this;
  638. };
  639. /**
  640. * Sets the Vector2 coordinates with the passed floats.
  641. * Returns the updated Vector2.
  642. */
  643. Vector2.prototype.set = function (x, y) {
  644. return this.copyFromFloats(x, y);
  645. };
  646. /**
  647. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  648. */
  649. Vector2.prototype.add = function (otherVector) {
  650. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  651. };
  652. /**
  653. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  654. * Returns the Vector2.
  655. */
  656. Vector2.prototype.addToRef = function (otherVector, result) {
  657. result.x = this.x + otherVector.x;
  658. result.y = this.y + otherVector.y;
  659. return this;
  660. };
  661. /**
  662. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  663. * Returns the updated Vector2.
  664. */
  665. Vector2.prototype.addInPlace = function (otherVector) {
  666. this.x += otherVector.x;
  667. this.y += otherVector.y;
  668. return this;
  669. };
  670. /**
  671. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  672. */
  673. Vector2.prototype.addVector3 = function (otherVector) {
  674. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  675. };
  676. /**
  677. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  678. */
  679. Vector2.prototype.subtract = function (otherVector) {
  680. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  681. };
  682. /**
  683. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  684. * Returns the Vector2.
  685. */
  686. Vector2.prototype.subtractToRef = function (otherVector, result) {
  687. result.x = this.x - otherVector.x;
  688. result.y = this.y - otherVector.y;
  689. return this;
  690. };
  691. /**
  692. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  693. * Returns the updated Vector2.
  694. */
  695. Vector2.prototype.subtractInPlace = function (otherVector) {
  696. this.x -= otherVector.x;
  697. this.y -= otherVector.y;
  698. return this;
  699. };
  700. /**
  701. * Multiplies in place the current Vector2 coordinates by the passed ones.
  702. * Returns the updated Vector2.
  703. */
  704. Vector2.prototype.multiplyInPlace = function (otherVector) {
  705. this.x *= otherVector.x;
  706. this.y *= otherVector.y;
  707. return this;
  708. };
  709. /**
  710. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  711. */
  712. Vector2.prototype.multiply = function (otherVector) {
  713. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  714. };
  715. /**
  716. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  717. * Returns the Vector2.
  718. */
  719. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  720. result.x = this.x * otherVector.x;
  721. result.y = this.y * otherVector.y;
  722. return this;
  723. };
  724. /**
  725. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  726. */
  727. Vector2.prototype.multiplyByFloats = function (x, y) {
  728. return new Vector2(this.x * x, this.y * y);
  729. };
  730. /**
  731. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  732. */
  733. Vector2.prototype.divide = function (otherVector) {
  734. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  735. };
  736. /**
  737. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  738. * Returns the Vector2.
  739. */
  740. Vector2.prototype.divideToRef = function (otherVector, result) {
  741. result.x = this.x / otherVector.x;
  742. result.y = this.y / otherVector.y;
  743. return this;
  744. };
  745. /**
  746. * Returns a new Vector2 with current Vector2 negated coordinates.
  747. */
  748. Vector2.prototype.negate = function () {
  749. return new Vector2(-this.x, -this.y);
  750. };
  751. /**
  752. * Multiply the Vector2 coordinates by scale.
  753. * Returns the updated Vector2.
  754. */
  755. Vector2.prototype.scaleInPlace = function (scale) {
  756. this.x *= scale;
  757. this.y *= scale;
  758. return this;
  759. };
  760. /**
  761. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  762. */
  763. Vector2.prototype.scale = function (scale) {
  764. return new Vector2(this.x * scale, this.y * scale);
  765. };
  766. /**
  767. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  768. */
  769. Vector2.prototype.equals = function (otherVector) {
  770. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  771. };
  772. /**
  773. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  774. */
  775. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  776. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  777. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  778. };
  779. // Properties
  780. /**
  781. * Returns the vector length (float).
  782. */
  783. Vector2.prototype.length = function () {
  784. return Math.sqrt(this.x * this.x + this.y * this.y);
  785. };
  786. /**
  787. * Returns the vector squared length (float);
  788. */
  789. Vector2.prototype.lengthSquared = function () {
  790. return (this.x * this.x + this.y * this.y);
  791. };
  792. // Methods
  793. /**
  794. * Normalize the vector.
  795. * Returns the updated Vector2.
  796. */
  797. Vector2.prototype.normalize = function () {
  798. var len = this.length();
  799. if (len === 0)
  800. return this;
  801. var num = 1.0 / len;
  802. this.x *= num;
  803. this.y *= num;
  804. return this;
  805. };
  806. /**
  807. * Returns a new Vector2 copied from the Vector2.
  808. */
  809. Vector2.prototype.clone = function () {
  810. return new Vector2(this.x, this.y);
  811. };
  812. // Statics
  813. /**
  814. * Returns a new Vector2(0, 0)
  815. */
  816. Vector2.Zero = function () {
  817. return new Vector2(0, 0);
  818. };
  819. /**
  820. * Returns a new Vector2 set from the passed index element of the passed array.
  821. */
  822. Vector2.FromArray = function (array, offset) {
  823. if (offset === void 0) { offset = 0; }
  824. return new Vector2(array[offset], array[offset + 1]);
  825. };
  826. /**
  827. * Sets "result" from the passed index element of the passed array.
  828. */
  829. Vector2.FromArrayToRef = function (array, offset, result) {
  830. result.x = array[offset];
  831. result.y = array[offset + 1];
  832. };
  833. /**
  834. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  835. */
  836. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  837. var squared = amount * amount;
  838. var cubed = amount * squared;
  839. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  840. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  841. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  842. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  843. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  844. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  845. return new Vector2(x, y);
  846. };
  847. /**
  848. * 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".
  849. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  850. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  851. */
  852. Vector2.Clamp = function (value, min, max) {
  853. var x = value.x;
  854. x = (x > max.x) ? max.x : x;
  855. x = (x < min.x) ? min.x : x;
  856. var y = value.y;
  857. y = (y > max.y) ? max.y : y;
  858. y = (y < min.y) ? min.y : y;
  859. return new Vector2(x, y);
  860. };
  861. /**
  862. * Returns a new Vecto2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  863. */
  864. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  865. var squared = amount * amount;
  866. var cubed = amount * squared;
  867. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  868. var part2 = (-2.0 * cubed) + (3.0 * squared);
  869. var part3 = (cubed - (2.0 * squared)) + amount;
  870. var part4 = cubed - squared;
  871. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  872. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  873. return new Vector2(x, y);
  874. };
  875. /**
  876. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  877. */
  878. Vector2.Lerp = function (start, end, amount) {
  879. var x = start.x + ((end.x - start.x) * amount);
  880. var y = start.y + ((end.y - start.y) * amount);
  881. return new Vector2(x, y);
  882. };
  883. /**
  884. * Returns the dot product (float) of the vector "left" and the vector "right".
  885. */
  886. Vector2.Dot = function (left, right) {
  887. return left.x * right.x + left.y * right.y;
  888. };
  889. /**
  890. * Returns a new Vector2 equal to the normalized passed vector.
  891. */
  892. Vector2.Normalize = function (vector) {
  893. var newVector = vector.clone();
  894. newVector.normalize();
  895. return newVector;
  896. };
  897. /**
  898. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  899. */
  900. Vector2.Minimize = function (left, right) {
  901. var x = (left.x < right.x) ? left.x : right.x;
  902. var y = (left.y < right.y) ? left.y : right.y;
  903. return new Vector2(x, y);
  904. };
  905. /**
  906. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  907. */
  908. Vector2.Maximize = function (left, right) {
  909. var x = (left.x > right.x) ? left.x : right.x;
  910. var y = (left.y > right.y) ? left.y : right.y;
  911. return new Vector2(x, y);
  912. };
  913. /**
  914. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  915. */
  916. Vector2.Transform = function (vector, transformation) {
  917. var r = Vector2.Zero();
  918. Vector2.TransformToRef(vector, transformation, r);
  919. return r;
  920. };
  921. /**
  922. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  923. */
  924. Vector2.TransformToRef = function (vector, transformation, result) {
  925. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  926. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  927. result.x = x;
  928. result.y = y;
  929. };
  930. /**
  931. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  932. */
  933. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  934. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  935. var sign = a < 0 ? -1 : 1;
  936. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  937. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  938. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  939. };
  940. /**
  941. * Returns the distance (float) between the vectors "value1" and "value2".
  942. */
  943. Vector2.Distance = function (value1, value2) {
  944. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  945. };
  946. /**
  947. * Returns the squared distance (float) between the vectors "value1" and "value2".
  948. */
  949. Vector2.DistanceSquared = function (value1, value2) {
  950. var x = value1.x - value2.x;
  951. var y = value1.y - value2.y;
  952. return (x * x) + (y * y);
  953. };
  954. /**
  955. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  956. */
  957. Vector2.Center = function (value1, value2) {
  958. var center = value1.add(value2);
  959. center.scaleInPlace(0.5);
  960. return center;
  961. };
  962. /**
  963. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  964. */
  965. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  966. var l2 = Vector2.DistanceSquared(segA, segB);
  967. if (l2 === 0.0) {
  968. return Vector2.Distance(p, segA);
  969. }
  970. var v = segB.subtract(segA);
  971. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  972. var proj = segA.add(v.multiplyByFloats(t, t));
  973. return Vector2.Distance(p, proj);
  974. };
  975. return Vector2;
  976. }());
  977. BABYLON.Vector2 = Vector2;
  978. var Vector3 = (function () {
  979. /**
  980. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  981. * A Vector3 is the main object used in 3D geometry.
  982. * It can represent etiher the coordinates of a point the space, either a direction.
  983. */
  984. function Vector3(x, y, z) {
  985. this.x = x;
  986. this.y = y;
  987. this.z = z;
  988. }
  989. /**
  990. * Returns a string with the Vector3 coordinates.
  991. */
  992. Vector3.prototype.toString = function () {
  993. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  994. };
  995. /**
  996. * Returns the string "Vector3"
  997. */
  998. Vector3.prototype.getClassName = function () {
  999. return "Vector3";
  1000. };
  1001. /**
  1002. * Returns the Vector hash code.
  1003. */
  1004. Vector3.prototype.getHashCode = function () {
  1005. var hash = this.x || 0;
  1006. hash = (hash * 397) ^ (this.y || 0);
  1007. hash = (hash * 397) ^ (this.z || 0);
  1008. return hash;
  1009. };
  1010. // Operators
  1011. /**
  1012. * Returns a new array with three elements : the coordinates the Vector3.
  1013. */
  1014. Vector3.prototype.asArray = function () {
  1015. var result = [];
  1016. this.toArray(result, 0);
  1017. return result;
  1018. };
  1019. /**
  1020. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1021. * Returns the Vector3.
  1022. */
  1023. Vector3.prototype.toArray = function (array, index) {
  1024. if (index === void 0) { index = 0; }
  1025. array[index] = this.x;
  1026. array[index + 1] = this.y;
  1027. array[index + 2] = this.z;
  1028. return this;
  1029. };
  1030. /**
  1031. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1032. */
  1033. Vector3.prototype.toQuaternion = function () {
  1034. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1035. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1036. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1037. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1038. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1039. var cosy = Math.cos(this.y * 0.5);
  1040. var siny = Math.sin(this.y * 0.5);
  1041. result.x = coszMinusx * siny;
  1042. result.y = -sinzMinusx * siny;
  1043. result.z = sinxPlusz * cosy;
  1044. result.w = cosxPlusz * cosy;
  1045. return result;
  1046. };
  1047. /**
  1048. * Adds the passed vector to the current Vector3.
  1049. * Returns the updated Vector3.
  1050. */
  1051. Vector3.prototype.addInPlace = function (otherVector) {
  1052. this.x += otherVector.x;
  1053. this.y += otherVector.y;
  1054. this.z += otherVector.z;
  1055. return this;
  1056. };
  1057. /**
  1058. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1059. */
  1060. Vector3.prototype.add = function (otherVector) {
  1061. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1062. };
  1063. /**
  1064. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1065. * Returns the current Vector3.
  1066. */
  1067. Vector3.prototype.addToRef = function (otherVector, result) {
  1068. result.x = this.x + otherVector.x;
  1069. result.y = this.y + otherVector.y;
  1070. result.z = this.z + otherVector.z;
  1071. return this;
  1072. };
  1073. /**
  1074. * Subtract the passed vector from the current Vector3.
  1075. * Returns the updated Vector3.
  1076. */
  1077. Vector3.prototype.subtractInPlace = function (otherVector) {
  1078. this.x -= otherVector.x;
  1079. this.y -= otherVector.y;
  1080. this.z -= otherVector.z;
  1081. return this;
  1082. };
  1083. /**
  1084. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1085. */
  1086. Vector3.prototype.subtract = function (otherVector) {
  1087. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1088. };
  1089. /**
  1090. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1091. * Returns the current Vector3.
  1092. */
  1093. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1094. result.x = this.x - otherVector.x;
  1095. result.y = this.y - otherVector.y;
  1096. result.z = this.z - otherVector.z;
  1097. return this;
  1098. };
  1099. /**
  1100. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1101. */
  1102. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1103. return new Vector3(this.x - x, this.y - y, this.z - z);
  1104. };
  1105. /**
  1106. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1107. * Returns the current Vector3.
  1108. */
  1109. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1110. result.x = this.x - x;
  1111. result.y = this.y - y;
  1112. result.z = this.z - z;
  1113. return this;
  1114. };
  1115. /**
  1116. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1117. */
  1118. Vector3.prototype.negate = function () {
  1119. return new Vector3(-this.x, -this.y, -this.z);
  1120. };
  1121. /**
  1122. * Multiplies the Vector3 coordinates by the float "scale".
  1123. * Returns the updated Vector3.
  1124. */
  1125. Vector3.prototype.scaleInPlace = function (scale) {
  1126. this.x *= scale;
  1127. this.y *= scale;
  1128. this.z *= scale;
  1129. return this;
  1130. };
  1131. /**
  1132. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1133. */
  1134. Vector3.prototype.scale = function (scale) {
  1135. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1136. };
  1137. /**
  1138. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1139. * Returns the current Vector3.
  1140. */
  1141. Vector3.prototype.scaleToRef = function (scale, result) {
  1142. result.x = this.x * scale;
  1143. result.y = this.y * scale;
  1144. result.z = this.z * scale;
  1145. return this;
  1146. };
  1147. /**
  1148. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1149. */
  1150. Vector3.prototype.equals = function (otherVector) {
  1151. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1152. };
  1153. /**
  1154. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1155. */
  1156. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1157. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1158. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  1159. };
  1160. /**
  1161. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1162. */
  1163. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1164. return this.x === x && this.y === y && this.z === z;
  1165. };
  1166. /**
  1167. * Muliplies the current Vector3 coordinates by the passed ones.
  1168. * Returns the updated Vector3.
  1169. */
  1170. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1171. this.x *= otherVector.x;
  1172. this.y *= otherVector.y;
  1173. this.z *= otherVector.z;
  1174. return this;
  1175. };
  1176. /**
  1177. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1178. */
  1179. Vector3.prototype.multiply = function (otherVector) {
  1180. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1181. };
  1182. /**
  1183. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1184. * Returns the current Vector3.
  1185. */
  1186. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1187. result.x = this.x * otherVector.x;
  1188. result.y = this.y * otherVector.y;
  1189. result.z = this.z * otherVector.z;
  1190. return this;
  1191. };
  1192. /**
  1193. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1194. */
  1195. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1196. return new Vector3(this.x * x, this.y * y, this.z * z);
  1197. };
  1198. /**
  1199. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1200. */
  1201. Vector3.prototype.divide = function (otherVector) {
  1202. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1203. };
  1204. /**
  1205. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1206. * Returns the current Vector3.
  1207. */
  1208. Vector3.prototype.divideToRef = function (otherVector, result) {
  1209. result.x = this.x / otherVector.x;
  1210. result.y = this.y / otherVector.y;
  1211. result.z = this.z / otherVector.z;
  1212. return this;
  1213. };
  1214. /**
  1215. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1216. * Returns the updated Vector3.
  1217. */
  1218. Vector3.prototype.MinimizeInPlace = function (other) {
  1219. if (other.x < this.x)
  1220. this.x = other.x;
  1221. if (other.y < this.y)
  1222. this.y = other.y;
  1223. if (other.z < this.z)
  1224. this.z = other.z;
  1225. return this;
  1226. };
  1227. /**
  1228. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1229. * Returns the updated Vector3.
  1230. */
  1231. Vector3.prototype.MaximizeInPlace = function (other) {
  1232. if (other.x > this.x)
  1233. this.x = other.x;
  1234. if (other.y > this.y)
  1235. this.y = other.y;
  1236. if (other.z > this.z)
  1237. this.z = other.z;
  1238. return this;
  1239. };
  1240. // Properties
  1241. /**
  1242. * Returns the length of the Vector3 (float).
  1243. */
  1244. Vector3.prototype.length = function () {
  1245. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1246. };
  1247. /**
  1248. * Returns the squared length of the Vector3 (float).
  1249. */
  1250. Vector3.prototype.lengthSquared = function () {
  1251. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1252. };
  1253. // Methods
  1254. /**
  1255. * Normalize the current Vector3.
  1256. * Returns the updated Vector3.
  1257. */
  1258. Vector3.prototype.normalize = function () {
  1259. var len = this.length();
  1260. if (len === 0 || len === 1.0)
  1261. return this;
  1262. var num = 1.0 / len;
  1263. this.x *= num;
  1264. this.y *= num;
  1265. this.z *= num;
  1266. return this;
  1267. };
  1268. /**
  1269. * Returns a new Vector3 copied from the current Vector3.
  1270. */
  1271. Vector3.prototype.clone = function () {
  1272. return new Vector3(this.x, this.y, this.z);
  1273. };
  1274. /**
  1275. * Copies the passed vector coordinates to the current Vector3 ones.
  1276. * Returns the updated Vector3.
  1277. */
  1278. Vector3.prototype.copyFrom = function (source) {
  1279. this.x = source.x;
  1280. this.y = source.y;
  1281. this.z = source.z;
  1282. return this;
  1283. };
  1284. /**
  1285. * Copies the passed floats to the current Vector3 coordinates.
  1286. * Returns the updated Vector3.
  1287. */
  1288. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1289. this.x = x;
  1290. this.y = y;
  1291. this.z = z;
  1292. return this;
  1293. };
  1294. /**
  1295. * Copies the passed floats to the current Vector3 coordinates.
  1296. * Returns the updated Vector3.
  1297. */
  1298. Vector3.prototype.set = function (x, y, z) {
  1299. return this.copyFromFloats(x, y, z);
  1300. };
  1301. // Statics
  1302. /**
  1303. *
  1304. */
  1305. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1306. var d0 = Vector3.Dot(vector0, axis) - size;
  1307. var d1 = Vector3.Dot(vector1, axis) - size;
  1308. var s = d0 / (d0 - d1);
  1309. return s;
  1310. };
  1311. /**
  1312. * Returns a new Vector3 set from the index "offset" of the passed array.
  1313. */
  1314. Vector3.FromArray = function (array, offset) {
  1315. if (!offset) {
  1316. offset = 0;
  1317. }
  1318. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1319. };
  1320. /**
  1321. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1322. * This function is deprecated. Use FromArray instead.
  1323. */
  1324. Vector3.FromFloatArray = function (array, offset) {
  1325. return Vector3.FromArray(array, offset);
  1326. };
  1327. /**
  1328. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1329. */
  1330. Vector3.FromArrayToRef = function (array, offset, result) {
  1331. result.x = array[offset];
  1332. result.y = array[offset + 1];
  1333. result.z = array[offset + 2];
  1334. };
  1335. /**
  1336. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1337. * This function is deprecated. Use FromArrayToRef instead.
  1338. */
  1339. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1340. return Vector3.FromArrayToRef(array, offset, result);
  1341. };
  1342. /**
  1343. * Sets the passed vector "result" with the passed floats.
  1344. */
  1345. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1346. result.x = x;
  1347. result.y = y;
  1348. result.z = z;
  1349. };
  1350. /**
  1351. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1352. */
  1353. Vector3.Zero = function () {
  1354. return new Vector3(0.0, 0.0, 0.0);
  1355. };
  1356. /**
  1357. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1358. */
  1359. Vector3.Up = function () {
  1360. return new Vector3(0.0, 1.0, 0.0);
  1361. };
  1362. /**
  1363. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1364. */
  1365. Vector3.Forward = function () {
  1366. return new Vector3(0.0, 0.0, 1.0);
  1367. };
  1368. /**
  1369. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1370. */
  1371. Vector3.Right = function () {
  1372. return new Vector3(1.0, 0.0, 0.0);
  1373. };
  1374. /**
  1375. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1376. */
  1377. Vector3.Left = function () {
  1378. return new Vector3(-1.0, 0.0, 0.0);
  1379. };
  1380. /**
  1381. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1382. * This method computes tranformed coordinates only, not transformed direction vectors.
  1383. */
  1384. Vector3.TransformCoordinates = function (vector, transformation) {
  1385. var result = Vector3.Zero();
  1386. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1387. return result;
  1388. };
  1389. /**
  1390. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1391. * This method computes tranformed coordinates only, not transformed direction vectors.
  1392. */
  1393. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1394. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1395. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1396. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1397. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1398. result.x = x / w;
  1399. result.y = y / w;
  1400. result.z = z / w;
  1401. };
  1402. /**
  1403. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1404. * This method computes tranformed coordinates only, not transformed direction vectors.
  1405. */
  1406. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1407. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1408. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1409. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1410. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1411. result.x = rx / rw;
  1412. result.y = ry / rw;
  1413. result.z = rz / rw;
  1414. };
  1415. /**
  1416. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1417. * This methods computes transformed normalized direction vectors only.
  1418. */
  1419. Vector3.TransformNormal = function (vector, transformation) {
  1420. var result = Vector3.Zero();
  1421. Vector3.TransformNormalToRef(vector, transformation, result);
  1422. return result;
  1423. };
  1424. /**
  1425. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1426. * This methods computes transformed normalized direction vectors only.
  1427. */
  1428. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1429. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1430. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1431. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1432. result.x = x;
  1433. result.y = y;
  1434. result.z = z;
  1435. };
  1436. /**
  1437. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1438. * This methods computes transformed normalized direction vectors only.
  1439. */
  1440. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1441. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1442. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1443. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1444. };
  1445. /**
  1446. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1447. */
  1448. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1449. var squared = amount * amount;
  1450. var cubed = amount * squared;
  1451. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1452. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1453. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1454. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1455. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1456. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1457. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1458. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1459. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1460. return new Vector3(x, y, z);
  1461. };
  1462. /**
  1463. * 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".
  1464. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1465. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1466. */
  1467. Vector3.Clamp = function (value, min, max) {
  1468. var x = value.x;
  1469. x = (x > max.x) ? max.x : x;
  1470. x = (x < min.x) ? min.x : x;
  1471. var y = value.y;
  1472. y = (y > max.y) ? max.y : y;
  1473. y = (y < min.y) ? min.y : y;
  1474. var z = value.z;
  1475. z = (z > max.z) ? max.z : z;
  1476. z = (z < min.z) ? min.z : z;
  1477. return new Vector3(x, y, z);
  1478. };
  1479. /**
  1480. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1481. */
  1482. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1483. var squared = amount * amount;
  1484. var cubed = amount * squared;
  1485. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1486. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1487. var part3 = (cubed - (2.0 * squared)) + amount;
  1488. var part4 = cubed - squared;
  1489. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1490. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1491. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1492. return new Vector3(x, y, z);
  1493. };
  1494. /**
  1495. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1496. */
  1497. Vector3.Lerp = function (start, end, amount) {
  1498. var result = new Vector3(0, 0, 0);
  1499. Vector3.LerpToRef(start, end, amount, result);
  1500. return result;
  1501. };
  1502. /**
  1503. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1504. */
  1505. Vector3.LerpToRef = function (start, end, amount, result) {
  1506. result.x = start.x + ((end.x - start.x) * amount);
  1507. result.y = start.y + ((end.y - start.y) * amount);
  1508. result.z = start.z + ((end.z - start.z) * amount);
  1509. };
  1510. /**
  1511. * Returns the dot product (float) between the vectors "left" and "right".
  1512. */
  1513. Vector3.Dot = function (left, right) {
  1514. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1515. };
  1516. /**
  1517. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1518. * The cross product is then orthogonal to both "left" and "right".
  1519. */
  1520. Vector3.Cross = function (left, right) {
  1521. var result = Vector3.Zero();
  1522. Vector3.CrossToRef(left, right, result);
  1523. return result;
  1524. };
  1525. /**
  1526. * Sets the passed vector "result" with the cross product of "left" and "right".
  1527. * The cross product is then orthogonal to both "left" and "right".
  1528. */
  1529. Vector3.CrossToRef = function (left, right, result) {
  1530. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1531. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1532. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1533. result.copyFrom(MathTmp.Vector3[0]);
  1534. };
  1535. /**
  1536. * Returns a new Vector3 as the normalization of the passed vector.
  1537. */
  1538. Vector3.Normalize = function (vector) {
  1539. var result = Vector3.Zero();
  1540. Vector3.NormalizeToRef(vector, result);
  1541. return result;
  1542. };
  1543. /**
  1544. * Sets the passed vector "result" with the normalization of the passed first vector.
  1545. */
  1546. Vector3.NormalizeToRef = function (vector, result) {
  1547. result.copyFrom(vector);
  1548. result.normalize();
  1549. };
  1550. Vector3.Project = function (vector, world, transform, viewport) {
  1551. var cw = viewport.width;
  1552. var ch = viewport.height;
  1553. var cx = viewport.x;
  1554. var cy = viewport.y;
  1555. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1556. 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);
  1557. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1558. world.multiplyToRef(transform, matrix);
  1559. matrix.multiplyToRef(viewportMatrix, matrix);
  1560. return Vector3.TransformCoordinates(vector, matrix);
  1561. };
  1562. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1563. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1564. world.multiplyToRef(transform, matrix);
  1565. matrix.invert();
  1566. source.x = source.x / viewportWidth * 2 - 1;
  1567. source.y = -(source.y / viewportHeight * 2 - 1);
  1568. var vector = Vector3.TransformCoordinates(source, matrix);
  1569. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1570. if (MathTools.WithinEpsilon(num, 1.0)) {
  1571. vector = vector.scale(1.0 / num);
  1572. }
  1573. return vector;
  1574. };
  1575. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1576. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  1577. world.multiplyToRef(view, matrix);
  1578. matrix.multiplyToRef(projection, matrix);
  1579. matrix.invert();
  1580. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1581. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1582. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1583. if (MathTools.WithinEpsilon(num, 1.0)) {
  1584. vector = vector.scale(1.0 / num);
  1585. }
  1586. return vector;
  1587. };
  1588. Vector3.Minimize = function (left, right) {
  1589. var min = left.clone();
  1590. min.MinimizeInPlace(right);
  1591. return min;
  1592. };
  1593. Vector3.Maximize = function (left, right) {
  1594. var max = left.clone();
  1595. max.MaximizeInPlace(right);
  1596. return max;
  1597. };
  1598. /**
  1599. * Returns the distance (float) between the vectors "value1" and "value2".
  1600. */
  1601. Vector3.Distance = function (value1, value2) {
  1602. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1603. };
  1604. /**
  1605. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1606. */
  1607. Vector3.DistanceSquared = function (value1, value2) {
  1608. var x = value1.x - value2.x;
  1609. var y = value1.y - value2.y;
  1610. var z = value1.z - value2.z;
  1611. return (x * x) + (y * y) + (z * z);
  1612. };
  1613. /**
  1614. * Returns a new Vector3 located at the center between "value1" and "value2".
  1615. */
  1616. Vector3.Center = function (value1, value2) {
  1617. var center = value1.add(value2);
  1618. center.scaleInPlace(0.5);
  1619. return center;
  1620. };
  1621. /**
  1622. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1623. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1624. * to something in order to rotate it from its local system to the given target system.
  1625. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1626. * Returns a new Vector3.
  1627. */
  1628. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1629. var rotation = Vector3.Zero();
  1630. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1631. return rotation;
  1632. };
  1633. /**
  1634. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1635. */
  1636. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1637. var quat = MathTmp.Quaternion[0];
  1638. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1639. quat.toEulerAnglesToRef(ref);
  1640. };
  1641. return Vector3;
  1642. }());
  1643. BABYLON.Vector3 = Vector3;
  1644. //Vector4 class created for EulerAngle class conversion to Quaternion
  1645. var Vector4 = (function () {
  1646. /**
  1647. * Creates a Vector4 object from the passed floats.
  1648. */
  1649. function Vector4(x, y, z, w) {
  1650. this.x = x;
  1651. this.y = y;
  1652. this.z = z;
  1653. this.w = w;
  1654. }
  1655. /**
  1656. * Returns the string with the Vector4 coordinates.
  1657. */
  1658. Vector4.prototype.toString = function () {
  1659. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1660. };
  1661. /**
  1662. * Returns the string "Vector4".
  1663. */
  1664. Vector4.prototype.getClassName = function () {
  1665. return "Vector4";
  1666. };
  1667. /**
  1668. * Returns the Vector4 hash code.
  1669. */
  1670. Vector4.prototype.getHashCode = function () {
  1671. var hash = this.x || 0;
  1672. hash = (hash * 397) ^ (this.y || 0);
  1673. hash = (hash * 397) ^ (this.z || 0);
  1674. hash = (hash * 397) ^ (this.w || 0);
  1675. return hash;
  1676. };
  1677. // Operators
  1678. /**
  1679. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1680. */
  1681. Vector4.prototype.asArray = function () {
  1682. var result = [];
  1683. this.toArray(result, 0);
  1684. return result;
  1685. };
  1686. /**
  1687. * Populates the passed array from the passed index with the Vector4 coordinates.
  1688. * Returns the Vector4.
  1689. */
  1690. Vector4.prototype.toArray = function (array, index) {
  1691. if (index === undefined) {
  1692. index = 0;
  1693. }
  1694. array[index] = this.x;
  1695. array[index + 1] = this.y;
  1696. array[index + 2] = this.z;
  1697. array[index + 3] = this.w;
  1698. return this;
  1699. };
  1700. /**
  1701. * Adds the passed vector to the current Vector4.
  1702. * Returns the updated Vector4.
  1703. */
  1704. Vector4.prototype.addInPlace = function (otherVector) {
  1705. this.x += otherVector.x;
  1706. this.y += otherVector.y;
  1707. this.z += otherVector.z;
  1708. this.w += otherVector.w;
  1709. return this;
  1710. };
  1711. /**
  1712. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1713. */
  1714. Vector4.prototype.add = function (otherVector) {
  1715. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1716. };
  1717. /**
  1718. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1719. * Returns the current Vector4.
  1720. */
  1721. Vector4.prototype.addToRef = function (otherVector, result) {
  1722. result.x = this.x + otherVector.x;
  1723. result.y = this.y + otherVector.y;
  1724. result.z = this.z + otherVector.z;
  1725. result.w = this.w + otherVector.w;
  1726. return this;
  1727. };
  1728. /**
  1729. * Subtract in place the passed vector from the current Vector4.
  1730. * Returns the updated Vector4.
  1731. */
  1732. Vector4.prototype.subtractInPlace = function (otherVector) {
  1733. this.x -= otherVector.x;
  1734. this.y -= otherVector.y;
  1735. this.z -= otherVector.z;
  1736. this.w -= otherVector.w;
  1737. return this;
  1738. };
  1739. /**
  1740. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1741. */
  1742. Vector4.prototype.subtract = function (otherVector) {
  1743. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1744. };
  1745. /**
  1746. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1747. * Returns the current Vector4.
  1748. */
  1749. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1750. result.x = this.x - otherVector.x;
  1751. result.y = this.y - otherVector.y;
  1752. result.z = this.z - otherVector.z;
  1753. result.w = this.w - otherVector.w;
  1754. return this;
  1755. };
  1756. /**
  1757. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1758. */
  1759. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1760. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1761. };
  1762. /**
  1763. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1764. * Returns the current Vector4.
  1765. */
  1766. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1767. result.x = this.x - x;
  1768. result.y = this.y - y;
  1769. result.z = this.z - z;
  1770. result.w = this.w - w;
  1771. return this;
  1772. };
  1773. /**
  1774. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1775. */
  1776. Vector4.prototype.negate = function () {
  1777. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1778. };
  1779. /**
  1780. * Multiplies the current Vector4 coordinates by scale (float).
  1781. * Returns the updated Vector4.
  1782. */
  1783. Vector4.prototype.scaleInPlace = function (scale) {
  1784. this.x *= scale;
  1785. this.y *= scale;
  1786. this.z *= scale;
  1787. this.w *= scale;
  1788. return this;
  1789. };
  1790. /**
  1791. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1792. */
  1793. Vector4.prototype.scale = function (scale) {
  1794. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1795. };
  1796. /**
  1797. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1798. * Returns the current Vector4.
  1799. */
  1800. Vector4.prototype.scaleToRef = function (scale, result) {
  1801. result.x = this.x * scale;
  1802. result.y = this.y * scale;
  1803. result.z = this.z * scale;
  1804. result.w = this.w * scale;
  1805. return this;
  1806. };
  1807. /**
  1808. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1809. */
  1810. Vector4.prototype.equals = function (otherVector) {
  1811. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1812. };
  1813. /**
  1814. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1815. */
  1816. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1817. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1818. return otherVector
  1819. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1820. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1821. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1822. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1823. };
  1824. /**
  1825. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1826. */
  1827. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1828. return this.x === x && this.y === y && this.z === z && this.w === w;
  1829. };
  1830. /**
  1831. * Multiplies in place the current Vector4 by the passed one.
  1832. * Returns the updated Vector4.
  1833. */
  1834. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1835. this.x *= otherVector.x;
  1836. this.y *= otherVector.y;
  1837. this.z *= otherVector.z;
  1838. this.w *= otherVector.w;
  1839. return this;
  1840. };
  1841. /**
  1842. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1843. */
  1844. Vector4.prototype.multiply = function (otherVector) {
  1845. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1846. };
  1847. /**
  1848. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1849. * Returns the current Vector4.
  1850. */
  1851. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1852. result.x = this.x * otherVector.x;
  1853. result.y = this.y * otherVector.y;
  1854. result.z = this.z * otherVector.z;
  1855. result.w = this.w * otherVector.w;
  1856. return this;
  1857. };
  1858. /**
  1859. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1860. */
  1861. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1862. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1863. };
  1864. /**
  1865. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1866. */
  1867. Vector4.prototype.divide = function (otherVector) {
  1868. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1869. };
  1870. /**
  1871. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1872. * Returns the current Vector4.
  1873. */
  1874. Vector4.prototype.divideToRef = function (otherVector, result) {
  1875. result.x = this.x / otherVector.x;
  1876. result.y = this.y / otherVector.y;
  1877. result.z = this.z / otherVector.z;
  1878. result.w = this.w / otherVector.w;
  1879. return this;
  1880. };
  1881. /**
  1882. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1883. */
  1884. Vector4.prototype.MinimizeInPlace = function (other) {
  1885. if (other.x < this.x)
  1886. this.x = other.x;
  1887. if (other.y < this.y)
  1888. this.y = other.y;
  1889. if (other.z < this.z)
  1890. this.z = other.z;
  1891. if (other.w < this.w)
  1892. this.w = other.w;
  1893. return this;
  1894. };
  1895. /**
  1896. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1897. */
  1898. Vector4.prototype.MaximizeInPlace = function (other) {
  1899. if (other.x > this.x)
  1900. this.x = other.x;
  1901. if (other.y > this.y)
  1902. this.y = other.y;
  1903. if (other.z > this.z)
  1904. this.z = other.z;
  1905. if (other.w > this.w)
  1906. this.w = other.w;
  1907. return this;
  1908. };
  1909. // Properties
  1910. /**
  1911. * Returns the Vector4 length (float).
  1912. */
  1913. Vector4.prototype.length = function () {
  1914. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1915. };
  1916. /**
  1917. * Returns the Vector4 squared length (float).
  1918. */
  1919. Vector4.prototype.lengthSquared = function () {
  1920. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1921. };
  1922. // Methods
  1923. /**
  1924. * Normalizes in place the Vector4.
  1925. * Returns the updated Vector4.
  1926. */
  1927. Vector4.prototype.normalize = function () {
  1928. var len = this.length();
  1929. if (len === 0)
  1930. return this;
  1931. var num = 1.0 / len;
  1932. this.x *= num;
  1933. this.y *= num;
  1934. this.z *= num;
  1935. this.w *= num;
  1936. return this;
  1937. };
  1938. /**
  1939. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1940. */
  1941. Vector4.prototype.toVector3 = function () {
  1942. return new Vector3(this.x, this.y, this.z);
  1943. };
  1944. /**
  1945. * Returns a new Vector4 copied from the current one.
  1946. */
  1947. Vector4.prototype.clone = function () {
  1948. return new Vector4(this.x, this.y, this.z, this.w);
  1949. };
  1950. /**
  1951. * Updates the current Vector4 with the passed one coordinates.
  1952. * Returns the updated Vector4.
  1953. */
  1954. Vector4.prototype.copyFrom = function (source) {
  1955. this.x = source.x;
  1956. this.y = source.y;
  1957. this.z = source.z;
  1958. this.w = source.w;
  1959. return this;
  1960. };
  1961. /**
  1962. * Updates the current Vector4 coordinates with the passed floats.
  1963. * Returns the updated Vector4.
  1964. */
  1965. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1966. this.x = x;
  1967. this.y = y;
  1968. this.z = z;
  1969. this.w = w;
  1970. return this;
  1971. };
  1972. /**
  1973. * Updates the current Vector4 coordinates with the passed floats.
  1974. * Returns the updated Vector4.
  1975. */
  1976. Vector4.prototype.set = function (x, y, z, w) {
  1977. return this.copyFromFloats(x, y, z, w);
  1978. };
  1979. // Statics
  1980. /**
  1981. * Returns a new Vector4 set from the starting index of the passed array.
  1982. */
  1983. Vector4.FromArray = function (array, offset) {
  1984. if (!offset) {
  1985. offset = 0;
  1986. }
  1987. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1988. };
  1989. /**
  1990. * Updates the passed vector "result" from the starting index of the passed array.
  1991. */
  1992. Vector4.FromArrayToRef = function (array, offset, result) {
  1993. result.x = array[offset];
  1994. result.y = array[offset + 1];
  1995. result.z = array[offset + 2];
  1996. result.w = array[offset + 3];
  1997. };
  1998. /**
  1999. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2000. */
  2001. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2002. Vector4.FromArrayToRef(array, offset, result);
  2003. };
  2004. /**
  2005. * Updates the passed vector "result" coordinates from the passed floats.
  2006. */
  2007. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2008. result.x = x;
  2009. result.y = y;
  2010. result.z = z;
  2011. result.w = w;
  2012. };
  2013. /**
  2014. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2015. */
  2016. Vector4.Zero = function () {
  2017. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2018. };
  2019. /**
  2020. * Returns a new normalized Vector4 from the passed one.
  2021. */
  2022. Vector4.Normalize = function (vector) {
  2023. var result = Vector4.Zero();
  2024. Vector4.NormalizeToRef(vector, result);
  2025. return result;
  2026. };
  2027. /**
  2028. * Updates the passed vector "result" from the normalization of the passed one.
  2029. */
  2030. Vector4.NormalizeToRef = function (vector, result) {
  2031. result.copyFrom(vector);
  2032. result.normalize();
  2033. };
  2034. Vector4.Minimize = function (left, right) {
  2035. var min = left.clone();
  2036. min.MinimizeInPlace(right);
  2037. return min;
  2038. };
  2039. Vector4.Maximize = function (left, right) {
  2040. var max = left.clone();
  2041. max.MaximizeInPlace(right);
  2042. return max;
  2043. };
  2044. /**
  2045. * Returns the distance (float) between the vectors "value1" and "value2".
  2046. */
  2047. Vector4.Distance = function (value1, value2) {
  2048. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2049. };
  2050. /**
  2051. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2052. */
  2053. Vector4.DistanceSquared = function (value1, value2) {
  2054. var x = value1.x - value2.x;
  2055. var y = value1.y - value2.y;
  2056. var z = value1.z - value2.z;
  2057. var w = value1.w - value2.w;
  2058. return (x * x) + (y * y) + (z * z) + (w * w);
  2059. };
  2060. /**
  2061. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2062. */
  2063. Vector4.Center = function (value1, value2) {
  2064. var center = value1.add(value2);
  2065. center.scaleInPlace(0.5);
  2066. return center;
  2067. };
  2068. /**
  2069. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2070. * This methods computes transformed normalized direction vectors only.
  2071. */
  2072. Vector4.TransformNormal = function (vector, transformation) {
  2073. var result = Vector4.Zero();
  2074. Vector4.TransformNormalToRef(vector, transformation, result);
  2075. return result;
  2076. };
  2077. /**
  2078. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2079. * This methods computes transformed normalized direction vectors only.
  2080. */
  2081. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2082. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2083. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2084. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2085. result.x = x;
  2086. result.y = y;
  2087. result.z = z;
  2088. result.w = vector.w;
  2089. };
  2090. /**
  2091. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2092. * This methods computes transformed normalized direction vectors only.
  2093. */
  2094. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2095. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2096. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2097. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2098. result.w = w;
  2099. };
  2100. return Vector4;
  2101. }());
  2102. BABYLON.Vector4 = Vector4;
  2103. var Size = (function () {
  2104. /**
  2105. * Creates a Size object from the passed width and height (floats).
  2106. */
  2107. function Size(width, height) {
  2108. this.width = width;
  2109. this.height = height;
  2110. }
  2111. // Returns a string with the Size width and height.
  2112. Size.prototype.toString = function () {
  2113. return "{W: " + this.width + ", H: " + this.height + "}";
  2114. };
  2115. /**
  2116. * Returns the string "Size"
  2117. */
  2118. Size.prototype.getClassName = function () {
  2119. return "Size";
  2120. };
  2121. /**
  2122. * Returns the Size hash code.
  2123. */
  2124. Size.prototype.getHashCode = function () {
  2125. var hash = this.width || 0;
  2126. hash = (hash * 397) ^ (this.height || 0);
  2127. return hash;
  2128. };
  2129. /**
  2130. * Updates the current size from the passed one.
  2131. * Returns the updated Size.
  2132. */
  2133. Size.prototype.copyFrom = function (src) {
  2134. this.width = src.width;
  2135. this.height = src.height;
  2136. };
  2137. /**
  2138. * Updates in place the current Size from the passed floats.
  2139. * Returns the updated Size.
  2140. */
  2141. Size.prototype.copyFromFloats = function (width, height) {
  2142. this.width = width;
  2143. this.height = height;
  2144. return this;
  2145. };
  2146. /**
  2147. * Updates in place the current Size from the passed floats.
  2148. * Returns the updated Size.
  2149. */
  2150. Size.prototype.set = function (width, height) {
  2151. return this.copyFromFloats(width, height);
  2152. };
  2153. /**
  2154. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2155. */
  2156. Size.prototype.multiplyByFloats = function (w, h) {
  2157. return new Size(this.width * w, this.height * h);
  2158. };
  2159. /**
  2160. * Returns a new Size copied from the passed one.
  2161. */
  2162. Size.prototype.clone = function () {
  2163. return new Size(this.width, this.height);
  2164. };
  2165. /**
  2166. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2167. */
  2168. Size.prototype.equals = function (other) {
  2169. if (!other) {
  2170. return false;
  2171. }
  2172. return (this.width === other.width) && (this.height === other.height);
  2173. };
  2174. Object.defineProperty(Size.prototype, "surface", {
  2175. /**
  2176. * Returns the surface of the Size : width * height (float).
  2177. */
  2178. get: function () {
  2179. return this.width * this.height;
  2180. },
  2181. enumerable: true,
  2182. configurable: true
  2183. });
  2184. /**
  2185. * Returns a new Size set to (0.0, 0.0)
  2186. */
  2187. Size.Zero = function () {
  2188. return new Size(0.0, 0.0);
  2189. };
  2190. /**
  2191. * Returns a new Size set as the addition result of the current Size and the passed one.
  2192. */
  2193. Size.prototype.add = function (otherSize) {
  2194. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2195. return r;
  2196. };
  2197. /**
  2198. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2199. */
  2200. Size.prototype.subtract = function (otherSize) {
  2201. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2202. return r;
  2203. };
  2204. /**
  2205. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2206. */
  2207. Size.Lerp = function (start, end, amount) {
  2208. var w = start.width + ((end.width - start.width) * amount);
  2209. var h = start.height + ((end.height - start.height) * amount);
  2210. return new Size(w, h);
  2211. };
  2212. return Size;
  2213. }());
  2214. BABYLON.Size = Size;
  2215. var Quaternion = (function () {
  2216. /**
  2217. * Creates a new Quaternion from the passed floats.
  2218. */
  2219. function Quaternion(x, y, z, w) {
  2220. if (x === void 0) { x = 0.0; }
  2221. if (y === void 0) { y = 0.0; }
  2222. if (z === void 0) { z = 0.0; }
  2223. if (w === void 0) { w = 1.0; }
  2224. this.x = x;
  2225. this.y = y;
  2226. this.z = z;
  2227. this.w = w;
  2228. }
  2229. /**
  2230. * Returns a string with the Quaternion coordinates.
  2231. */
  2232. Quaternion.prototype.toString = function () {
  2233. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2234. };
  2235. /**
  2236. * Returns the string "Quaternion".
  2237. */
  2238. Quaternion.prototype.getClassName = function () {
  2239. return "Quaternion";
  2240. };
  2241. /**
  2242. * Returns the Quaternion hash code.
  2243. */
  2244. Quaternion.prototype.getHashCode = function () {
  2245. var hash = this.x || 0;
  2246. hash = (hash * 397) ^ (this.y || 0);
  2247. hash = (hash * 397) ^ (this.z || 0);
  2248. hash = (hash * 397) ^ (this.w || 0);
  2249. return hash;
  2250. };
  2251. /**
  2252. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2253. */
  2254. Quaternion.prototype.asArray = function () {
  2255. return [this.x, this.y, this.z, this.w];
  2256. };
  2257. /**
  2258. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2259. */
  2260. Quaternion.prototype.equals = function (otherQuaternion) {
  2261. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2262. };
  2263. /**
  2264. * Returns a new Quaternion copied from the current one.
  2265. */
  2266. Quaternion.prototype.clone = function () {
  2267. return new Quaternion(this.x, this.y, this.z, this.w);
  2268. };
  2269. /**
  2270. * Updates the current Quaternion from the passed one coordinates.
  2271. * Returns the updated Quaterion.
  2272. */
  2273. Quaternion.prototype.copyFrom = function (other) {
  2274. this.x = other.x;
  2275. this.y = other.y;
  2276. this.z = other.z;
  2277. this.w = other.w;
  2278. return this;
  2279. };
  2280. /**
  2281. * Updates the current Quaternion from the passed float coordinates.
  2282. * Returns the updated Quaterion.
  2283. */
  2284. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2285. this.x = x;
  2286. this.y = y;
  2287. this.z = z;
  2288. this.w = w;
  2289. return this;
  2290. };
  2291. /**
  2292. * Updates the current Quaternion from the passed float coordinates.
  2293. * Returns the updated Quaterion.
  2294. */
  2295. Quaternion.prototype.set = function (x, y, z, w) {
  2296. return this.copyFromFloats(x, y, z, w);
  2297. };
  2298. /**
  2299. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2300. */
  2301. Quaternion.prototype.add = function (other) {
  2302. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2303. };
  2304. /**
  2305. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2306. */
  2307. Quaternion.prototype.subtract = function (other) {
  2308. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2309. };
  2310. /**
  2311. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2312. */
  2313. Quaternion.prototype.scale = function (value) {
  2314. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2315. };
  2316. /**
  2317. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2318. */
  2319. Quaternion.prototype.multiply = function (q1) {
  2320. var result = new Quaternion(0, 0, 0, 1.0);
  2321. this.multiplyToRef(q1, result);
  2322. return result;
  2323. };
  2324. /**
  2325. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2326. * Returns the current Quaternion.
  2327. */
  2328. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2329. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2330. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2331. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2332. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2333. result.copyFromFloats(x, y, z, w);
  2334. return this;
  2335. };
  2336. /**
  2337. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2338. * Returns the updated Quaternion.
  2339. */
  2340. Quaternion.prototype.multiplyInPlace = function (q1) {
  2341. this.multiplyToRef(q1, this);
  2342. return this;
  2343. };
  2344. /**
  2345. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2346. * Returns the current Quaternion.
  2347. */
  2348. Quaternion.prototype.conjugateToRef = function (ref) {
  2349. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2350. return this;
  2351. };
  2352. /**
  2353. * Conjugates in place the current Quaternion.
  2354. * Returns the updated Quaternion.
  2355. */
  2356. Quaternion.prototype.conjugateInPlace = function () {
  2357. this.x *= -1;
  2358. this.y *= -1;
  2359. this.z *= -1;
  2360. return this;
  2361. };
  2362. /**
  2363. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2364. */
  2365. Quaternion.prototype.conjugate = function () {
  2366. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2367. return result;
  2368. };
  2369. /**
  2370. * Returns the Quaternion length (float).
  2371. */
  2372. Quaternion.prototype.length = function () {
  2373. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2374. };
  2375. /**
  2376. * Normalize in place the current Quaternion.
  2377. * Returns the updated Quaternion.
  2378. */
  2379. Quaternion.prototype.normalize = function () {
  2380. var length = 1.0 / this.length();
  2381. this.x *= length;
  2382. this.y *= length;
  2383. this.z *= length;
  2384. this.w *= length;
  2385. return this;
  2386. };
  2387. /**
  2388. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2389. */
  2390. Quaternion.prototype.toEulerAngles = function (order) {
  2391. if (order === void 0) { order = "YZX"; }
  2392. var result = Vector3.Zero();
  2393. this.toEulerAnglesToRef(result, order);
  2394. return result;
  2395. };
  2396. /**
  2397. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2398. * Returns the current Quaternion.
  2399. */
  2400. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2401. if (order === void 0) { order = "YZX"; }
  2402. var qz = this.z;
  2403. var qx = this.x;
  2404. var qy = this.y;
  2405. var qw = this.w;
  2406. var sqw = qw * qw;
  2407. var sqz = qz * qz;
  2408. var sqx = qx * qx;
  2409. var sqy = qy * qy;
  2410. var zAxisY = qy * qz - qx * qw;
  2411. var limit = .4999999;
  2412. if (zAxisY < -limit) {
  2413. result.y = 2 * Math.atan2(qy, qw);
  2414. result.x = Math.PI / 2;
  2415. result.z = 0;
  2416. }
  2417. else if (zAxisY > limit) {
  2418. result.y = 2 * Math.atan2(qy, qw);
  2419. result.x = -Math.PI / 2;
  2420. result.z = 0;
  2421. }
  2422. else {
  2423. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2424. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2425. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2426. }
  2427. return this;
  2428. };
  2429. /**
  2430. * Updates the passed rotation matrix with the current Quaternion values.
  2431. * Returns the current Quaternion.
  2432. */
  2433. Quaternion.prototype.toRotationMatrix = function (result) {
  2434. var xx = this.x * this.x;
  2435. var yy = this.y * this.y;
  2436. var zz = this.z * this.z;
  2437. var xy = this.x * this.y;
  2438. var zw = this.z * this.w;
  2439. var zx = this.z * this.x;
  2440. var yw = this.y * this.w;
  2441. var yz = this.y * this.z;
  2442. var xw = this.x * this.w;
  2443. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2444. result.m[1] = 2.0 * (xy + zw);
  2445. result.m[2] = 2.0 * (zx - yw);
  2446. result.m[3] = 0;
  2447. result.m[4] = 2.0 * (xy - zw);
  2448. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2449. result.m[6] = 2.0 * (yz + xw);
  2450. result.m[7] = 0;
  2451. result.m[8] = 2.0 * (zx + yw);
  2452. result.m[9] = 2.0 * (yz - xw);
  2453. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2454. result.m[11] = 0;
  2455. result.m[12] = 0;
  2456. result.m[13] = 0;
  2457. result.m[14] = 0;
  2458. result.m[15] = 1.0;
  2459. result._markAsUpdated();
  2460. return this;
  2461. };
  2462. /**
  2463. * Updates the current Quaternion from the passed rotation matrix values.
  2464. * Returns the updated Quaternion.
  2465. */
  2466. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2467. Quaternion.FromRotationMatrixToRef(matrix, this);
  2468. return this;
  2469. };
  2470. // Statics
  2471. /**
  2472. * Returns a new Quaternion set from the passed rotation matrix values.
  2473. */
  2474. Quaternion.FromRotationMatrix = function (matrix) {
  2475. var result = new Quaternion();
  2476. Quaternion.FromRotationMatrixToRef(matrix, result);
  2477. return result;
  2478. };
  2479. /**
  2480. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2481. */
  2482. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2483. var data = matrix.m;
  2484. var m11 = data[0], m12 = data[4], m13 = data[8];
  2485. var m21 = data[1], m22 = data[5], m23 = data[9];
  2486. var m31 = data[2], m32 = data[6], m33 = data[10];
  2487. var trace = m11 + m22 + m33;
  2488. var s;
  2489. if (trace > 0) {
  2490. s = 0.5 / Math.sqrt(trace + 1.0);
  2491. result.w = 0.25 / s;
  2492. result.x = (m32 - m23) * s;
  2493. result.y = (m13 - m31) * s;
  2494. result.z = (m21 - m12) * s;
  2495. }
  2496. else if (m11 > m22 && m11 > m33) {
  2497. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2498. result.w = (m32 - m23) / s;
  2499. result.x = 0.25 * s;
  2500. result.y = (m12 + m21) / s;
  2501. result.z = (m13 + m31) / s;
  2502. }
  2503. else if (m22 > m33) {
  2504. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2505. result.w = (m13 - m31) / s;
  2506. result.x = (m12 + m21) / s;
  2507. result.y = 0.25 * s;
  2508. result.z = (m23 + m32) / s;
  2509. }
  2510. else {
  2511. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2512. result.w = (m21 - m12) / s;
  2513. result.x = (m13 + m31) / s;
  2514. result.y = (m23 + m32) / s;
  2515. result.z = 0.25 * s;
  2516. }
  2517. };
  2518. /**
  2519. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2520. */
  2521. Quaternion.Zero = function () {
  2522. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2523. };
  2524. /**
  2525. * Returns a new Quaternion as the inverted current Quaternion.
  2526. */
  2527. Quaternion.Inverse = function (q) {
  2528. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2529. };
  2530. /**
  2531. * Returns the identity Quaternion.
  2532. */
  2533. Quaternion.Identity = function () {
  2534. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2535. };
  2536. Quaternion.IsIdentity = function (quaternion) {
  2537. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2538. };
  2539. /**
  2540. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2541. */
  2542. Quaternion.RotationAxis = function (axis, angle) {
  2543. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2544. };
  2545. /**
  2546. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2547. */
  2548. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2549. var sin = Math.sin(angle / 2);
  2550. axis.normalize();
  2551. result.w = Math.cos(angle / 2);
  2552. result.x = axis.x * sin;
  2553. result.y = axis.y * sin;
  2554. result.z = axis.z * sin;
  2555. return result;
  2556. };
  2557. /**
  2558. * Retuns a new Quaternion set from the starting index of the passed array.
  2559. */
  2560. Quaternion.FromArray = function (array, offset) {
  2561. if (!offset) {
  2562. offset = 0;
  2563. }
  2564. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2565. };
  2566. /**
  2567. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2568. */
  2569. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2570. var q = new Quaternion();
  2571. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2572. return q;
  2573. };
  2574. /**
  2575. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2576. */
  2577. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2578. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2579. var halfRoll = roll * 0.5;
  2580. var halfPitch = pitch * 0.5;
  2581. var halfYaw = yaw * 0.5;
  2582. var sinRoll = Math.sin(halfRoll);
  2583. var cosRoll = Math.cos(halfRoll);
  2584. var sinPitch = Math.sin(halfPitch);
  2585. var cosPitch = Math.cos(halfPitch);
  2586. var sinYaw = Math.sin(halfYaw);
  2587. var cosYaw = Math.cos(halfYaw);
  2588. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2589. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2590. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2591. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2592. };
  2593. /**
  2594. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2595. */
  2596. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2597. var result = new Quaternion();
  2598. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2599. return result;
  2600. };
  2601. /**
  2602. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2603. */
  2604. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2605. // Produces a quaternion from Euler angles in the z-x-z orientation
  2606. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2607. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2608. var halfBeta = beta * 0.5;
  2609. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2610. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2611. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2612. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2613. };
  2614. /**
  2615. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2616. * cf to Vector3.RotationFromAxis() documentation.
  2617. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2618. */
  2619. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2620. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2621. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2622. return quat;
  2623. };
  2624. /**
  2625. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2626. * cf to Vector3.RotationFromAxis() documentation.
  2627. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2628. */
  2629. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2630. var rotMat = MathTmp.Matrix[0];
  2631. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2632. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2633. };
  2634. Quaternion.Slerp = function (left, right, amount) {
  2635. var result = Quaternion.Identity();
  2636. Quaternion.SlerpToRef(left, right, amount, result);
  2637. return result;
  2638. };
  2639. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2640. var num2;
  2641. var num3;
  2642. var num = amount;
  2643. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2644. var flag = false;
  2645. if (num4 < 0) {
  2646. flag = true;
  2647. num4 = -num4;
  2648. }
  2649. if (num4 > 0.999999) {
  2650. num3 = 1 - num;
  2651. num2 = flag ? -num : num;
  2652. }
  2653. else {
  2654. var num5 = Math.acos(num4);
  2655. var num6 = (1.0 / Math.sin(num5));
  2656. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2657. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2658. }
  2659. result.x = (num3 * left.x) + (num2 * right.x);
  2660. result.y = (num3 * left.y) + (num2 * right.y);
  2661. result.z = (num3 * left.z) + (num2 * right.z);
  2662. result.w = (num3 * left.w) + (num2 * right.w);
  2663. };
  2664. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2665. var squared = amount * amount;
  2666. var cubed = amount * squared;
  2667. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2668. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2669. var part3 = (cubed - (2.0 * squared)) + amount;
  2670. var part4 = cubed - squared;
  2671. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2672. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2673. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2674. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2675. return new Quaternion(x, y, z, w);
  2676. };
  2677. return Quaternion;
  2678. }());
  2679. BABYLON.Quaternion = Quaternion;
  2680. var Matrix = (function () {
  2681. function Matrix() {
  2682. this.m = new Float32Array(16);
  2683. this._markAsUpdated();
  2684. }
  2685. Matrix.prototype._markAsUpdated = function () {
  2686. this.updateFlag = Matrix._updateFlagSeed++;
  2687. };
  2688. // Properties
  2689. /**
  2690. * Boolean : True is the matrix is the identity matrix
  2691. */
  2692. Matrix.prototype.isIdentity = function () {
  2693. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2694. return false;
  2695. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2696. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2697. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2698. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2699. return false;
  2700. return true;
  2701. };
  2702. /**
  2703. * Returns the matrix determinant (float).
  2704. */
  2705. Matrix.prototype.determinant = function () {
  2706. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2707. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2708. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2709. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2710. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2711. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2712. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2713. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2714. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2715. };
  2716. // Methods
  2717. /**
  2718. * Returns the matrix underlying array.
  2719. */
  2720. Matrix.prototype.toArray = function () {
  2721. return this.m;
  2722. };
  2723. /**
  2724. * Returns the matrix underlying array.
  2725. */
  2726. Matrix.prototype.asArray = function () {
  2727. return this.toArray();
  2728. };
  2729. /**
  2730. * Inverts in place the Matrix.
  2731. * Returns the Matrix inverted.
  2732. */
  2733. Matrix.prototype.invert = function () {
  2734. this.invertToRef(this);
  2735. return this;
  2736. };
  2737. /**
  2738. * Sets all the matrix elements to zero.
  2739. * Returns the Matrix.
  2740. */
  2741. Matrix.prototype.reset = function () {
  2742. for (var index = 0; index < 16; index++) {
  2743. this.m[index] = 0.0;
  2744. }
  2745. this._markAsUpdated();
  2746. return this;
  2747. };
  2748. /**
  2749. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2750. */
  2751. Matrix.prototype.add = function (other) {
  2752. var result = new Matrix();
  2753. this.addToRef(other, result);
  2754. return result;
  2755. };
  2756. /**
  2757. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2758. * Returns the Matrix.
  2759. */
  2760. Matrix.prototype.addToRef = function (other, result) {
  2761. for (var index = 0; index < 16; index++) {
  2762. result.m[index] = this.m[index] + other.m[index];
  2763. }
  2764. result._markAsUpdated();
  2765. return this;
  2766. };
  2767. /**
  2768. * Adds in place the passed matrix to the current Matrix.
  2769. * Returns the updated Matrix.
  2770. */
  2771. Matrix.prototype.addToSelf = function (other) {
  2772. for (var index = 0; index < 16; index++) {
  2773. this.m[index] += other.m[index];
  2774. }
  2775. this._markAsUpdated();
  2776. return this;
  2777. };
  2778. /**
  2779. * Sets the passed matrix with the current inverted Matrix.
  2780. * Returns the unmodified current Matrix.
  2781. */
  2782. Matrix.prototype.invertToRef = function (other) {
  2783. var l1 = this.m[0];
  2784. var l2 = this.m[1];
  2785. var l3 = this.m[2];
  2786. var l4 = this.m[3];
  2787. var l5 = this.m[4];
  2788. var l6 = this.m[5];
  2789. var l7 = this.m[6];
  2790. var l8 = this.m[7];
  2791. var l9 = this.m[8];
  2792. var l10 = this.m[9];
  2793. var l11 = this.m[10];
  2794. var l12 = this.m[11];
  2795. var l13 = this.m[12];
  2796. var l14 = this.m[13];
  2797. var l15 = this.m[14];
  2798. var l16 = this.m[15];
  2799. var l17 = (l11 * l16) - (l12 * l15);
  2800. var l18 = (l10 * l16) - (l12 * l14);
  2801. var l19 = (l10 * l15) - (l11 * l14);
  2802. var l20 = (l9 * l16) - (l12 * l13);
  2803. var l21 = (l9 * l15) - (l11 * l13);
  2804. var l22 = (l9 * l14) - (l10 * l13);
  2805. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2806. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2807. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2808. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2809. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2810. var l28 = (l7 * l16) - (l8 * l15);
  2811. var l29 = (l6 * l16) - (l8 * l14);
  2812. var l30 = (l6 * l15) - (l7 * l14);
  2813. var l31 = (l5 * l16) - (l8 * l13);
  2814. var l32 = (l5 * l15) - (l7 * l13);
  2815. var l33 = (l5 * l14) - (l6 * l13);
  2816. var l34 = (l7 * l12) - (l8 * l11);
  2817. var l35 = (l6 * l12) - (l8 * l10);
  2818. var l36 = (l6 * l11) - (l7 * l10);
  2819. var l37 = (l5 * l12) - (l8 * l9);
  2820. var l38 = (l5 * l11) - (l7 * l9);
  2821. var l39 = (l5 * l10) - (l6 * l9);
  2822. other.m[0] = l23 * l27;
  2823. other.m[4] = l24 * l27;
  2824. other.m[8] = l25 * l27;
  2825. other.m[12] = l26 * l27;
  2826. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2827. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2828. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2829. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2830. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2831. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2832. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2833. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2834. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2835. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2836. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2837. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2838. other._markAsUpdated();
  2839. return this;
  2840. };
  2841. /**
  2842. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2843. * Returns the updated Matrix.
  2844. */
  2845. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2846. this.m[12] = x;
  2847. this.m[13] = y;
  2848. this.m[14] = z;
  2849. this._markAsUpdated();
  2850. return this;
  2851. };
  2852. /**
  2853. * Inserts the translation vector in the current Matrix.
  2854. * Returns the updated Matrix.
  2855. */
  2856. Matrix.prototype.setTranslation = function (vector3) {
  2857. this.m[12] = vector3.x;
  2858. this.m[13] = vector3.y;
  2859. this.m[14] = vector3.z;
  2860. this._markAsUpdated();
  2861. return this;
  2862. };
  2863. /**
  2864. * Returns a new Vector3 as the extracted translation from the Matrix.
  2865. */
  2866. Matrix.prototype.getTranslation = function () {
  2867. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2868. };
  2869. /**
  2870. * Fill a Vector3 with the extracted translation from the Matrix.
  2871. */
  2872. Matrix.prototype.getTranslationToRef = function (result) {
  2873. result.x = this.m[12];
  2874. result.y = this.m[13];
  2875. result.z = this.m[14];
  2876. return this;
  2877. };
  2878. /**
  2879. * Remove rotation and scaling part from the Matrix.
  2880. * Returns the updated Matrix.
  2881. */
  2882. Matrix.prototype.removeRotationAndScaling = function () {
  2883. this.setRowFromFloats(0, 1, 0, 0, 0);
  2884. this.setRowFromFloats(1, 0, 1, 0, 0);
  2885. this.setRowFromFloats(2, 0, 0, 1, 0);
  2886. return this;
  2887. };
  2888. /**
  2889. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2890. */
  2891. Matrix.prototype.multiply = function (other) {
  2892. var result = new Matrix();
  2893. this.multiplyToRef(other, result);
  2894. return result;
  2895. };
  2896. /**
  2897. * Updates the current Matrix from the passed one values.
  2898. * Returns the updated Matrix.
  2899. */
  2900. Matrix.prototype.copyFrom = function (other) {
  2901. for (var index = 0; index < 16; index++) {
  2902. this.m[index] = other.m[index];
  2903. }
  2904. this._markAsUpdated();
  2905. return this;
  2906. };
  2907. /**
  2908. * Populates the passed array from the starting index with the Matrix values.
  2909. * Returns the Matrix.
  2910. */
  2911. Matrix.prototype.copyToArray = function (array, offset) {
  2912. if (offset === void 0) { offset = 0; }
  2913. for (var index = 0; index < 16; index++) {
  2914. array[offset + index] = this.m[index];
  2915. }
  2916. return this;
  2917. };
  2918. /**
  2919. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2920. */
  2921. Matrix.prototype.multiplyToRef = function (other, result) {
  2922. this.multiplyToArray(other, result.m, 0);
  2923. result._markAsUpdated();
  2924. return this;
  2925. };
  2926. /**
  2927. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2928. */
  2929. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2930. var tm0 = this.m[0];
  2931. var tm1 = this.m[1];
  2932. var tm2 = this.m[2];
  2933. var tm3 = this.m[3];
  2934. var tm4 = this.m[4];
  2935. var tm5 = this.m[5];
  2936. var tm6 = this.m[6];
  2937. var tm7 = this.m[7];
  2938. var tm8 = this.m[8];
  2939. var tm9 = this.m[9];
  2940. var tm10 = this.m[10];
  2941. var tm11 = this.m[11];
  2942. var tm12 = this.m[12];
  2943. var tm13 = this.m[13];
  2944. var tm14 = this.m[14];
  2945. var tm15 = this.m[15];
  2946. var om0 = other.m[0];
  2947. var om1 = other.m[1];
  2948. var om2 = other.m[2];
  2949. var om3 = other.m[3];
  2950. var om4 = other.m[4];
  2951. var om5 = other.m[5];
  2952. var om6 = other.m[6];
  2953. var om7 = other.m[7];
  2954. var om8 = other.m[8];
  2955. var om9 = other.m[9];
  2956. var om10 = other.m[10];
  2957. var om11 = other.m[11];
  2958. var om12 = other.m[12];
  2959. var om13 = other.m[13];
  2960. var om14 = other.m[14];
  2961. var om15 = other.m[15];
  2962. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2963. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2964. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2965. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2966. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2967. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2968. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2969. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2970. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2971. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2972. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  2973. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  2974. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  2975. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  2976. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  2977. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  2978. return this;
  2979. };
  2980. /**
  2981. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  2982. */
  2983. Matrix.prototype.equals = function (value) {
  2984. return value &&
  2985. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  2986. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  2987. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  2988. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  2989. };
  2990. /**
  2991. * Returns a new Matrix from the current Matrix.
  2992. */
  2993. Matrix.prototype.clone = function () {
  2994. 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]);
  2995. };
  2996. /**
  2997. * Returns the string "Matrix"
  2998. */
  2999. Matrix.prototype.getClassName = function () {
  3000. return "Matrix";
  3001. };
  3002. /**
  3003. * Returns the Matrix hash code.
  3004. */
  3005. Matrix.prototype.getHashCode = function () {
  3006. var hash = this.m[0] || 0;
  3007. for (var i = 1; i < 16; i++) {
  3008. hash = (hash * 397) ^ (this.m[i] || 0);
  3009. }
  3010. return hash;
  3011. };
  3012. /**
  3013. * Decomposes the current Matrix into :
  3014. * - a scale vector3 passed as a reference to update,
  3015. * - a rotation quaternion passed as a reference to update,
  3016. * - a translation vector3 passed as a reference to update.
  3017. * Returns the boolean `true`.
  3018. */
  3019. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3020. translation.x = this.m[12];
  3021. translation.y = this.m[13];
  3022. translation.z = this.m[14];
  3023. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3024. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3025. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3026. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3027. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3028. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3029. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3030. rotation.x = 0;
  3031. rotation.y = 0;
  3032. rotation.z = 0;
  3033. rotation.w = 1;
  3034. return false;
  3035. }
  3036. 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]);
  3037. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3038. return true;
  3039. };
  3040. /**
  3041. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3042. */
  3043. Matrix.prototype.getRotationMatrix = function () {
  3044. var result = Matrix.Identity();
  3045. this.getRotationMatrixToRef(result);
  3046. return result;
  3047. };
  3048. /**
  3049. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3050. * Returns the current Matrix.
  3051. */
  3052. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3053. var m = this.m;
  3054. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3055. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3056. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3057. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3058. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3059. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3060. 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);
  3061. return this;
  3062. };
  3063. // Statics
  3064. /**
  3065. * Returns a new Matrix set from the starting index of the passed array.
  3066. */
  3067. Matrix.FromArray = function (array, offset) {
  3068. var result = new Matrix();
  3069. if (!offset) {
  3070. offset = 0;
  3071. }
  3072. Matrix.FromArrayToRef(array, offset, result);
  3073. return result;
  3074. };
  3075. /**
  3076. * Sets the passed "result" matrix from the starting index of the passed array.
  3077. */
  3078. Matrix.FromArrayToRef = function (array, offset, result) {
  3079. for (var index = 0; index < 16; index++) {
  3080. result.m[index] = array[index + offset];
  3081. }
  3082. result._markAsUpdated();
  3083. };
  3084. /**
  3085. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3086. */
  3087. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3088. for (var index = 0; index < 16; index++) {
  3089. result.m[index] = array[index + offset] * scale;
  3090. }
  3091. result._markAsUpdated();
  3092. };
  3093. /**
  3094. * Sets the passed matrix "result" with the 16 passed floats.
  3095. */
  3096. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3097. result.m[0] = initialM11;
  3098. result.m[1] = initialM12;
  3099. result.m[2] = initialM13;
  3100. result.m[3] = initialM14;
  3101. result.m[4] = initialM21;
  3102. result.m[5] = initialM22;
  3103. result.m[6] = initialM23;
  3104. result.m[7] = initialM24;
  3105. result.m[8] = initialM31;
  3106. result.m[9] = initialM32;
  3107. result.m[10] = initialM33;
  3108. result.m[11] = initialM34;
  3109. result.m[12] = initialM41;
  3110. result.m[13] = initialM42;
  3111. result.m[14] = initialM43;
  3112. result.m[15] = initialM44;
  3113. result._markAsUpdated();
  3114. };
  3115. /**
  3116. * Returns the index-th row of the current matrix as a new Vector4.
  3117. */
  3118. Matrix.prototype.getRow = function (index) {
  3119. if (index < 0 || index > 3) {
  3120. return null;
  3121. }
  3122. var i = index * 4;
  3123. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3124. };
  3125. /**
  3126. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3127. * Returns the updated Matrix.
  3128. */
  3129. Matrix.prototype.setRow = function (index, row) {
  3130. if (index < 0 || index > 3) {
  3131. return this;
  3132. }
  3133. var i = index * 4;
  3134. this.m[i + 0] = row.x;
  3135. this.m[i + 1] = row.y;
  3136. this.m[i + 2] = row.z;
  3137. this.m[i + 3] = row.w;
  3138. this._markAsUpdated();
  3139. return this;
  3140. };
  3141. /**
  3142. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3143. * Returns the updated Matrix.
  3144. */
  3145. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3146. if (index < 0 || index > 3) {
  3147. return this;
  3148. }
  3149. var i = index * 4;
  3150. this.m[i + 0] = x;
  3151. this.m[i + 1] = y;
  3152. this.m[i + 2] = z;
  3153. this.m[i + 3] = w;
  3154. this._markAsUpdated();
  3155. return this;
  3156. };
  3157. /**
  3158. * Returns a new Matrix set from the 16 passed floats.
  3159. */
  3160. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3161. var result = new Matrix();
  3162. result.m[0] = initialM11;
  3163. result.m[1] = initialM12;
  3164. result.m[2] = initialM13;
  3165. result.m[3] = initialM14;
  3166. result.m[4] = initialM21;
  3167. result.m[5] = initialM22;
  3168. result.m[6] = initialM23;
  3169. result.m[7] = initialM24;
  3170. result.m[8] = initialM31;
  3171. result.m[9] = initialM32;
  3172. result.m[10] = initialM33;
  3173. result.m[11] = initialM34;
  3174. result.m[12] = initialM41;
  3175. result.m[13] = initialM42;
  3176. result.m[14] = initialM43;
  3177. result.m[15] = initialM44;
  3178. return result;
  3179. };
  3180. /**
  3181. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3182. */
  3183. Matrix.Compose = function (scale, rotation, translation) {
  3184. var result = Matrix.Identity();
  3185. Matrix.ComposeToRef(scale, rotation, translation, result);
  3186. return result;
  3187. };
  3188. /**
  3189. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3190. */
  3191. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3192. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3193. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3194. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3195. result.setTranslation(translation);
  3196. };
  3197. /**
  3198. * Returns a new indentity Matrix.
  3199. */
  3200. Matrix.Identity = function () {
  3201. 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);
  3202. };
  3203. /**
  3204. * Sets the passed "result" as an identity matrix.
  3205. */
  3206. Matrix.IdentityToRef = function (result) {
  3207. 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);
  3208. };
  3209. /**
  3210. * Returns a new zero Matrix.
  3211. */
  3212. Matrix.Zero = function () {
  3213. 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);
  3214. };
  3215. /**
  3216. * Returns a new rotation matrix for "angle" radians around the X axis.
  3217. */
  3218. Matrix.RotationX = function (angle) {
  3219. var result = new Matrix();
  3220. Matrix.RotationXToRef(angle, result);
  3221. return result;
  3222. };
  3223. /**
  3224. * Returns a new Matrix as the passed inverted one.
  3225. */
  3226. Matrix.Invert = function (source) {
  3227. var result = new Matrix();
  3228. source.invertToRef(result);
  3229. return result;
  3230. };
  3231. /**
  3232. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3233. */
  3234. Matrix.RotationXToRef = function (angle, result) {
  3235. var s = Math.sin(angle);
  3236. var c = Math.cos(angle);
  3237. result.m[0] = 1.0;
  3238. result.m[15] = 1.0;
  3239. result.m[5] = c;
  3240. result.m[10] = c;
  3241. result.m[9] = -s;
  3242. result.m[6] = s;
  3243. result.m[1] = 0.0;
  3244. result.m[2] = 0.0;
  3245. result.m[3] = 0.0;
  3246. result.m[4] = 0.0;
  3247. result.m[7] = 0.0;
  3248. result.m[8] = 0.0;
  3249. result.m[11] = 0.0;
  3250. result.m[12] = 0.0;
  3251. result.m[13] = 0.0;
  3252. result.m[14] = 0.0;
  3253. result._markAsUpdated();
  3254. };
  3255. /**
  3256. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3257. */
  3258. Matrix.RotationY = function (angle) {
  3259. var result = new Matrix();
  3260. Matrix.RotationYToRef(angle, result);
  3261. return result;
  3262. };
  3263. /**
  3264. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3265. */
  3266. Matrix.RotationYToRef = function (angle, result) {
  3267. var s = Math.sin(angle);
  3268. var c = Math.cos(angle);
  3269. result.m[5] = 1.0;
  3270. result.m[15] = 1.0;
  3271. result.m[0] = c;
  3272. result.m[2] = -s;
  3273. result.m[8] = s;
  3274. result.m[10] = c;
  3275. result.m[1] = 0.0;
  3276. result.m[3] = 0.0;
  3277. result.m[4] = 0.0;
  3278. result.m[6] = 0.0;
  3279. result.m[7] = 0.0;
  3280. result.m[9] = 0.0;
  3281. result.m[11] = 0.0;
  3282. result.m[12] = 0.0;
  3283. result.m[13] = 0.0;
  3284. result.m[14] = 0.0;
  3285. result._markAsUpdated();
  3286. };
  3287. /**
  3288. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3289. */
  3290. Matrix.RotationZ = function (angle) {
  3291. var result = new Matrix();
  3292. Matrix.RotationZToRef(angle, result);
  3293. return result;
  3294. };
  3295. /**
  3296. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3297. */
  3298. Matrix.RotationZToRef = function (angle, result) {
  3299. var s = Math.sin(angle);
  3300. var c = Math.cos(angle);
  3301. result.m[10] = 1.0;
  3302. result.m[15] = 1.0;
  3303. result.m[0] = c;
  3304. result.m[1] = s;
  3305. result.m[4] = -s;
  3306. result.m[5] = c;
  3307. result.m[2] = 0.0;
  3308. result.m[3] = 0.0;
  3309. result.m[6] = 0.0;
  3310. result.m[7] = 0.0;
  3311. result.m[8] = 0.0;
  3312. result.m[9] = 0.0;
  3313. result.m[11] = 0.0;
  3314. result.m[12] = 0.0;
  3315. result.m[13] = 0.0;
  3316. result.m[14] = 0.0;
  3317. result._markAsUpdated();
  3318. };
  3319. /**
  3320. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3321. */
  3322. Matrix.RotationAxis = function (axis, angle) {
  3323. var result = Matrix.Zero();
  3324. Matrix.RotationAxisToRef(axis, angle, result);
  3325. return result;
  3326. };
  3327. /**
  3328. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3329. */
  3330. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3331. var s = Math.sin(-angle);
  3332. var c = Math.cos(-angle);
  3333. var c1 = 1 - c;
  3334. axis.normalize();
  3335. result.m[0] = (axis.x * axis.x) * c1 + c;
  3336. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3337. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3338. result.m[3] = 0.0;
  3339. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3340. result.m[5] = (axis.y * axis.y) * c1 + c;
  3341. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3342. result.m[7] = 0.0;
  3343. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3344. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3345. result.m[10] = (axis.z * axis.z) * c1 + c;
  3346. result.m[11] = 0.0;
  3347. result.m[15] = 1.0;
  3348. result._markAsUpdated();
  3349. };
  3350. /**
  3351. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3352. */
  3353. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3354. var result = new Matrix();
  3355. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3356. return result;
  3357. };
  3358. /**
  3359. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3360. */
  3361. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3362. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3363. this._tempQuaternion.toRotationMatrix(result);
  3364. };
  3365. /**
  3366. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3367. */
  3368. Matrix.Scaling = function (x, y, z) {
  3369. var result = Matrix.Zero();
  3370. Matrix.ScalingToRef(x, y, z, result);
  3371. return result;
  3372. };
  3373. /**
  3374. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3375. */
  3376. Matrix.ScalingToRef = function (x, y, z, result) {
  3377. result.m[0] = x;
  3378. result.m[1] = 0.0;
  3379. result.m[2] = 0.0;
  3380. result.m[3] = 0.0;
  3381. result.m[4] = 0.0;
  3382. result.m[5] = y;
  3383. result.m[6] = 0.0;
  3384. result.m[7] = 0.0;
  3385. result.m[8] = 0.0;
  3386. result.m[9] = 0.0;
  3387. result.m[10] = z;
  3388. result.m[11] = 0.0;
  3389. result.m[12] = 0.0;
  3390. result.m[13] = 0.0;
  3391. result.m[14] = 0.0;
  3392. result.m[15] = 1.0;
  3393. result._markAsUpdated();
  3394. };
  3395. /**
  3396. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3397. */
  3398. Matrix.Translation = function (x, y, z) {
  3399. var result = Matrix.Identity();
  3400. Matrix.TranslationToRef(x, y, z, result);
  3401. return result;
  3402. };
  3403. /**
  3404. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3405. */
  3406. Matrix.TranslationToRef = function (x, y, z, result) {
  3407. 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);
  3408. };
  3409. /**
  3410. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3411. */
  3412. Matrix.Lerp = function (startValue, endValue, gradient) {
  3413. var result = Matrix.Zero();
  3414. for (var index = 0; index < 16; index++) {
  3415. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3416. }
  3417. result._markAsUpdated();
  3418. return result;
  3419. };
  3420. /**
  3421. * Returns a new Matrix whose values are computed by :
  3422. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3423. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3424. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3425. */
  3426. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3427. var startScale = new Vector3(0, 0, 0);
  3428. var startRotation = new Quaternion();
  3429. var startTranslation = new Vector3(0, 0, 0);
  3430. startValue.decompose(startScale, startRotation, startTranslation);
  3431. var endScale = new Vector3(0, 0, 0);
  3432. var endRotation = new Quaternion();
  3433. var endTranslation = new Vector3(0, 0, 0);
  3434. endValue.decompose(endScale, endRotation, endTranslation);
  3435. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3436. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3437. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3438. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3439. };
  3440. /**
  3441. * 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".
  3442. * This methods works for a Left-Handed system.
  3443. */
  3444. Matrix.LookAtLH = function (eye, target, up) {
  3445. var result = Matrix.Zero();
  3446. Matrix.LookAtLHToRef(eye, target, up, result);
  3447. return result;
  3448. };
  3449. /**
  3450. * 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".
  3451. * This methods works for a Left-Handed system.
  3452. */
  3453. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3454. // Z axis
  3455. target.subtractToRef(eye, this._zAxis);
  3456. this._zAxis.normalize();
  3457. // X axis
  3458. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3459. if (this._xAxis.lengthSquared() === 0) {
  3460. this._xAxis.x = 1.0;
  3461. }
  3462. else {
  3463. this._xAxis.normalize();
  3464. }
  3465. // Y axis
  3466. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3467. this._yAxis.normalize();
  3468. // Eye angles
  3469. var ex = -Vector3.Dot(this._xAxis, eye);
  3470. var ey = -Vector3.Dot(this._yAxis, eye);
  3471. var ez = -Vector3.Dot(this._zAxis, eye);
  3472. 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);
  3473. };
  3474. /**
  3475. * 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".
  3476. * This methods works for a Right-Handed system.
  3477. */
  3478. Matrix.LookAtRH = function (eye, target, up) {
  3479. var result = Matrix.Zero();
  3480. Matrix.LookAtRHToRef(eye, target, up, result);
  3481. return result;
  3482. };
  3483. /**
  3484. * 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".
  3485. * This methods works for a Left-Handed system.
  3486. */
  3487. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3488. // Z axis
  3489. eye.subtractToRef(target, this._zAxis);
  3490. this._zAxis.normalize();
  3491. // X axis
  3492. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3493. if (this._xAxis.lengthSquared() === 0) {
  3494. this._xAxis.x = 1.0;
  3495. }
  3496. else {
  3497. this._xAxis.normalize();
  3498. }
  3499. // Y axis
  3500. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3501. this._yAxis.normalize();
  3502. // Eye angles
  3503. var ex = -Vector3.Dot(this._xAxis, eye);
  3504. var ey = -Vector3.Dot(this._yAxis, eye);
  3505. var ez = -Vector3.Dot(this._zAxis, eye);
  3506. 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);
  3507. };
  3508. /**
  3509. * 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.
  3510. */
  3511. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3512. var matrix = Matrix.Zero();
  3513. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3514. return matrix;
  3515. };
  3516. /**
  3517. * 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.
  3518. */
  3519. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3520. var n = znear;
  3521. var f = zfar;
  3522. var a = 2.0 / width;
  3523. var b = 2.0 / height;
  3524. var c = 2.0 / (f - n);
  3525. var d = -(f + n) / (f - n);
  3526. 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);
  3527. };
  3528. /**
  3529. * 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.
  3530. */
  3531. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3532. var matrix = Matrix.Zero();
  3533. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3534. return matrix;
  3535. };
  3536. /**
  3537. * 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.
  3538. */
  3539. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3540. var n = znear;
  3541. var f = zfar;
  3542. var a = 2.0 / (right - left);
  3543. var b = 2.0 / (top - bottom);
  3544. var c = 2.0 / (f - n);
  3545. var d = -(f + n) / (f - n);
  3546. var i0 = (left + right) / (left - right);
  3547. var i1 = (top + bottom) / (bottom - top);
  3548. 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);
  3549. };
  3550. /**
  3551. * 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.
  3552. */
  3553. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3554. var matrix = Matrix.Zero();
  3555. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3556. return matrix;
  3557. };
  3558. /**
  3559. * 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.
  3560. */
  3561. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3562. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3563. result.m[10] *= -1.0;
  3564. };
  3565. /**
  3566. * 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.
  3567. */
  3568. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3569. var matrix = Matrix.Zero();
  3570. var n = znear;
  3571. var f = zfar;
  3572. var a = 2.0 * n / width;
  3573. var b = 2.0 * n / height;
  3574. var c = (f + n) / (f - n);
  3575. var d = -2.0 * f * n / (f - n);
  3576. 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);
  3577. return matrix;
  3578. };
  3579. /**
  3580. * 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.
  3581. */
  3582. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3583. var matrix = Matrix.Zero();
  3584. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3585. return matrix;
  3586. };
  3587. /**
  3588. * 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.
  3589. */
  3590. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3591. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3592. var n = znear;
  3593. var f = zfar;
  3594. var t = 1.0 / (Math.tan(fov * 0.5));
  3595. var a = isVerticalFovFixed ? (t / aspect) : t;
  3596. var b = isVerticalFovFixed ? t : (t * aspect);
  3597. var c = (f + n) / (f - n);
  3598. var d = -2.0 * f * n / (f - n);
  3599. 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);
  3600. };
  3601. /**
  3602. * 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.
  3603. */
  3604. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3605. var matrix = Matrix.Zero();
  3606. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3607. return matrix;
  3608. };
  3609. /**
  3610. * 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.
  3611. */
  3612. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3613. //alternatively this could be expressed as:
  3614. // m = PerspectiveFovLHToRef
  3615. // m[10] *= -1.0;
  3616. // m[11] *= -1.0;
  3617. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3618. var n = znear;
  3619. var f = zfar;
  3620. var t = 1.0 / (Math.tan(fov * 0.5));
  3621. var a = isVerticalFovFixed ? (t / aspect) : t;
  3622. var b = isVerticalFovFixed ? t : (t * aspect);
  3623. var c = -(f + n) / (f - n);
  3624. var d = -2 * f * n / (f - n);
  3625. 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);
  3626. };
  3627. /**
  3628. * 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.
  3629. */
  3630. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3631. if (rightHanded === void 0) { rightHanded = false; }
  3632. var rightHandedFactor = rightHanded ? -1 : 1;
  3633. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3634. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3635. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3636. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3637. var xScale = 2.0 / (leftTan + rightTan);
  3638. var yScale = 2.0 / (upTan + downTan);
  3639. result.m[0] = xScale;
  3640. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3641. result.m[5] = yScale;
  3642. result.m[6] = result.m[7] = 0.0;
  3643. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3644. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3645. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3646. result.m[10] = -zfar / (znear - zfar);
  3647. result.m[11] = 1.0 * rightHandedFactor;
  3648. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3649. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3650. // result.m[14] = (znear * zfar) / (znear - zfar);
  3651. result._markAsUpdated();
  3652. };
  3653. /**
  3654. * Returns the final transformation matrix : world * view * projection * viewport
  3655. */
  3656. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3657. var cw = viewport.width;
  3658. var ch = viewport.height;
  3659. var cx = viewport.x;
  3660. var cy = viewport.y;
  3661. 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);
  3662. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3663. };
  3664. /**
  3665. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3666. */
  3667. Matrix.GetAsMatrix2x2 = function (matrix) {
  3668. return new Float32Array([
  3669. matrix.m[0], matrix.m[1],
  3670. matrix.m[4], matrix.m[5]
  3671. ]);
  3672. };
  3673. /**
  3674. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3675. */
  3676. Matrix.GetAsMatrix3x3 = function (matrix) {
  3677. return new Float32Array([
  3678. matrix.m[0], matrix.m[1], matrix.m[2],
  3679. matrix.m[4], matrix.m[5], matrix.m[6],
  3680. matrix.m[8], matrix.m[9], matrix.m[10]
  3681. ]);
  3682. };
  3683. /**
  3684. * Compute the transpose of the passed Matrix.
  3685. * Returns a new Matrix.
  3686. */
  3687. Matrix.Transpose = function (matrix) {
  3688. var result = new Matrix();
  3689. result.m[0] = matrix.m[0];
  3690. result.m[1] = matrix.m[4];
  3691. result.m[2] = matrix.m[8];
  3692. result.m[3] = matrix.m[12];
  3693. result.m[4] = matrix.m[1];
  3694. result.m[5] = matrix.m[5];
  3695. result.m[6] = matrix.m[9];
  3696. result.m[7] = matrix.m[13];
  3697. result.m[8] = matrix.m[2];
  3698. result.m[9] = matrix.m[6];
  3699. result.m[10] = matrix.m[10];
  3700. result.m[11] = matrix.m[14];
  3701. result.m[12] = matrix.m[3];
  3702. result.m[13] = matrix.m[7];
  3703. result.m[14] = matrix.m[11];
  3704. result.m[15] = matrix.m[15];
  3705. return result;
  3706. };
  3707. /**
  3708. * Returns a new Matrix as the reflection matrix across the passed plane.
  3709. */
  3710. Matrix.Reflection = function (plane) {
  3711. var matrix = new Matrix();
  3712. Matrix.ReflectionToRef(plane, matrix);
  3713. return matrix;
  3714. };
  3715. /**
  3716. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3717. */
  3718. Matrix.ReflectionToRef = function (plane, result) {
  3719. plane.normalize();
  3720. var x = plane.normal.x;
  3721. var y = plane.normal.y;
  3722. var z = plane.normal.z;
  3723. var temp = -2 * x;
  3724. var temp2 = -2 * y;
  3725. var temp3 = -2 * z;
  3726. result.m[0] = (temp * x) + 1;
  3727. result.m[1] = temp2 * x;
  3728. result.m[2] = temp3 * x;
  3729. result.m[3] = 0.0;
  3730. result.m[4] = temp * y;
  3731. result.m[5] = (temp2 * y) + 1;
  3732. result.m[6] = temp3 * y;
  3733. result.m[7] = 0.0;
  3734. result.m[8] = temp * z;
  3735. result.m[9] = temp2 * z;
  3736. result.m[10] = (temp3 * z) + 1;
  3737. result.m[11] = 0.0;
  3738. result.m[12] = temp * plane.d;
  3739. result.m[13] = temp2 * plane.d;
  3740. result.m[14] = temp3 * plane.d;
  3741. result.m[15] = 1.0;
  3742. result._markAsUpdated();
  3743. };
  3744. /**
  3745. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3746. */
  3747. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3748. result.m[0] = xaxis.x;
  3749. result.m[1] = xaxis.y;
  3750. result.m[2] = xaxis.z;
  3751. result.m[3] = 0.0;
  3752. result.m[4] = yaxis.x;
  3753. result.m[5] = yaxis.y;
  3754. result.m[6] = yaxis.z;
  3755. result.m[7] = 0.0;
  3756. result.m[8] = zaxis.x;
  3757. result.m[9] = zaxis.y;
  3758. result.m[10] = zaxis.z;
  3759. result.m[11] = 0.0;
  3760. result.m[12] = 0.0;
  3761. result.m[13] = 0.0;
  3762. result.m[14] = 0.0;
  3763. result.m[15] = 1.0;
  3764. result._markAsUpdated();
  3765. };
  3766. /**
  3767. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3768. */
  3769. Matrix.FromQuaternionToRef = function (quat, result) {
  3770. var xx = quat.x * quat.x;
  3771. var yy = quat.y * quat.y;
  3772. var zz = quat.z * quat.z;
  3773. var xy = quat.x * quat.y;
  3774. var zw = quat.z * quat.w;
  3775. var zx = quat.z * quat.x;
  3776. var yw = quat.y * quat.w;
  3777. var yz = quat.y * quat.z;
  3778. var xw = quat.x * quat.w;
  3779. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3780. result.m[1] = 2.0 * (xy + zw);
  3781. result.m[2] = 2.0 * (zx - yw);
  3782. result.m[3] = 0.0;
  3783. result.m[4] = 2.0 * (xy - zw);
  3784. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3785. result.m[6] = 2.0 * (yz + xw);
  3786. result.m[7] = 0.0;
  3787. result.m[8] = 2.0 * (zx + yw);
  3788. result.m[9] = 2.0 * (yz - xw);
  3789. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3790. result.m[11] = 0.0;
  3791. result.m[12] = 0.0;
  3792. result.m[13] = 0.0;
  3793. result.m[14] = 0.0;
  3794. result.m[15] = 1.0;
  3795. result._markAsUpdated();
  3796. };
  3797. return Matrix;
  3798. }());
  3799. Matrix._tempQuaternion = new Quaternion();
  3800. Matrix._xAxis = Vector3.Zero();
  3801. Matrix._yAxis = Vector3.Zero();
  3802. Matrix._zAxis = Vector3.Zero();
  3803. Matrix._updateFlagSeed = 0;
  3804. BABYLON.Matrix = Matrix;
  3805. var Plane = (function () {
  3806. /**
  3807. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3808. */
  3809. function Plane(a, b, c, d) {
  3810. this.normal = new Vector3(a, b, c);
  3811. this.d = d;
  3812. }
  3813. /**
  3814. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3815. */
  3816. Plane.prototype.asArray = function () {
  3817. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3818. };
  3819. // Methods
  3820. /**
  3821. * Returns a new plane copied from the current Plane.
  3822. */
  3823. Plane.prototype.clone = function () {
  3824. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3825. };
  3826. /**
  3827. * Returns the string "Plane".
  3828. */
  3829. Plane.prototype.getClassName = function () {
  3830. return "Plane";
  3831. };
  3832. /**
  3833. * Returns the Plane hash code.
  3834. */
  3835. Plane.prototype.getHashCode = function () {
  3836. var hash = this.normal.getHashCode();
  3837. hash = (hash * 397) ^ (this.d || 0);
  3838. return hash;
  3839. };
  3840. /**
  3841. * Normalize the current Plane in place.
  3842. * Returns the updated Plane.
  3843. */
  3844. Plane.prototype.normalize = function () {
  3845. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3846. var magnitude = 0.0;
  3847. if (norm !== 0) {
  3848. magnitude = 1.0 / norm;
  3849. }
  3850. this.normal.x *= magnitude;
  3851. this.normal.y *= magnitude;
  3852. this.normal.z *= magnitude;
  3853. this.d *= magnitude;
  3854. return this;
  3855. };
  3856. /**
  3857. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3858. */
  3859. Plane.prototype.transform = function (transformation) {
  3860. var transposedMatrix = Matrix.Transpose(transformation);
  3861. var x = this.normal.x;
  3862. var y = this.normal.y;
  3863. var z = this.normal.z;
  3864. var d = this.d;
  3865. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3866. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3867. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3868. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3869. return new Plane(normalX, normalY, normalZ, finalD);
  3870. };
  3871. /**
  3872. * Returns the dot product (float) of the point coordinates and the plane normal.
  3873. */
  3874. Plane.prototype.dotCoordinate = function (point) {
  3875. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3876. };
  3877. /**
  3878. * Updates the current Plane from the plane defined by the three passed points.
  3879. * Returns the updated Plane.
  3880. */
  3881. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3882. var x1 = point2.x - point1.x;
  3883. var y1 = point2.y - point1.y;
  3884. var z1 = point2.z - point1.z;
  3885. var x2 = point3.x - point1.x;
  3886. var y2 = point3.y - point1.y;
  3887. var z2 = point3.z - point1.z;
  3888. var yz = (y1 * z2) - (z1 * y2);
  3889. var xz = (z1 * x2) - (x1 * z2);
  3890. var xy = (x1 * y2) - (y1 * x2);
  3891. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3892. var invPyth;
  3893. if (pyth !== 0) {
  3894. invPyth = 1.0 / pyth;
  3895. }
  3896. else {
  3897. invPyth = 0.0;
  3898. }
  3899. this.normal.x = yz * invPyth;
  3900. this.normal.y = xz * invPyth;
  3901. this.normal.z = xy * invPyth;
  3902. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3903. return this;
  3904. };
  3905. /**
  3906. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3907. */
  3908. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3909. var dot = Vector3.Dot(this.normal, direction);
  3910. return (dot <= epsilon);
  3911. };
  3912. /**
  3913. * Returns the signed distance (float) from the passed point to the Plane.
  3914. */
  3915. Plane.prototype.signedDistanceTo = function (point) {
  3916. return Vector3.Dot(point, this.normal) + this.d;
  3917. };
  3918. // Statics
  3919. /**
  3920. * Returns a new Plane from the passed array.
  3921. */
  3922. Plane.FromArray = function (array) {
  3923. return new Plane(array[0], array[1], array[2], array[3]);
  3924. };
  3925. /**
  3926. * Returns a new Plane defined by the three passed points.
  3927. */
  3928. Plane.FromPoints = function (point1, point2, point3) {
  3929. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3930. result.copyFromPoints(point1, point2, point3);
  3931. return result;
  3932. };
  3933. /**
  3934. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3935. * Note : the vector "normal" is updated because normalized.
  3936. */
  3937. Plane.FromPositionAndNormal = function (origin, normal) {
  3938. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3939. normal.normalize();
  3940. result.normal = normal;
  3941. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3942. return result;
  3943. };
  3944. /**
  3945. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3946. */
  3947. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3948. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3949. return Vector3.Dot(point, normal) + d;
  3950. };
  3951. return Plane;
  3952. }());
  3953. BABYLON.Plane = Plane;
  3954. var Viewport = (function () {
  3955. /**
  3956. * Creates a Viewport object located at (x, y) and sized (width, height).
  3957. */
  3958. function Viewport(x, y, width, height) {
  3959. this.x = x;
  3960. this.y = y;
  3961. this.width = width;
  3962. this.height = height;
  3963. }
  3964. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3965. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3966. };
  3967. /**
  3968. * Returns a new Viewport copied from the current one.
  3969. */
  3970. Viewport.prototype.clone = function () {
  3971. return new Viewport(this.x, this.y, this.width, this.height);
  3972. };
  3973. return Viewport;
  3974. }());
  3975. BABYLON.Viewport = Viewport;
  3976. var Frustum = (function () {
  3977. function Frustum() {
  3978. }
  3979. /**
  3980. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  3981. */
  3982. Frustum.GetPlanes = function (transform) {
  3983. var frustumPlanes = [];
  3984. for (var index = 0; index < 6; index++) {
  3985. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  3986. }
  3987. Frustum.GetPlanesToRef(transform, frustumPlanes);
  3988. return frustumPlanes;
  3989. };
  3990. /**
  3991. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  3992. */
  3993. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  3994. // Near
  3995. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  3996. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  3997. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  3998. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  3999. frustumPlanes[0].normalize();
  4000. // Far
  4001. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4002. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4003. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4004. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4005. frustumPlanes[1].normalize();
  4006. // Left
  4007. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4008. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4009. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4010. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4011. frustumPlanes[2].normalize();
  4012. // Right
  4013. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4014. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4015. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4016. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4017. frustumPlanes[3].normalize();
  4018. // Top
  4019. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4020. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4021. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4022. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4023. frustumPlanes[4].normalize();
  4024. // Bottom
  4025. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4026. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4027. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4028. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4029. frustumPlanes[5].normalize();
  4030. };
  4031. return Frustum;
  4032. }());
  4033. BABYLON.Frustum = Frustum;
  4034. var Space;
  4035. (function (Space) {
  4036. Space[Space["LOCAL"] = 0] = "LOCAL";
  4037. Space[Space["WORLD"] = 1] = "WORLD";
  4038. Space[Space["BONE"] = 2] = "BONE";
  4039. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4040. var Axis = (function () {
  4041. function Axis() {
  4042. }
  4043. return Axis;
  4044. }());
  4045. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4046. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4047. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4048. BABYLON.Axis = Axis;
  4049. ;
  4050. var BezierCurve = (function () {
  4051. function BezierCurve() {
  4052. }
  4053. /**
  4054. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4055. */
  4056. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4057. // Extract X (which is equal to time here)
  4058. var f0 = 1 - 3 * x2 + 3 * x1;
  4059. var f1 = 3 * x2 - 6 * x1;
  4060. var f2 = 3 * x1;
  4061. var refinedT = t;
  4062. for (var i = 0; i < 5; i++) {
  4063. var refinedT2 = refinedT * refinedT;
  4064. var refinedT3 = refinedT2 * refinedT;
  4065. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4066. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4067. refinedT -= (x - t) * slope;
  4068. refinedT = Math.min(1, Math.max(0, refinedT));
  4069. }
  4070. // Resolve cubic bezier for the given x
  4071. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4072. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4073. Math.pow(refinedT, 3);
  4074. };
  4075. return BezierCurve;
  4076. }());
  4077. BABYLON.BezierCurve = BezierCurve;
  4078. var Orientation;
  4079. (function (Orientation) {
  4080. Orientation[Orientation["CW"] = 0] = "CW";
  4081. Orientation[Orientation["CCW"] = 1] = "CCW";
  4082. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4083. var Angle = (function () {
  4084. /**
  4085. * Creates an Angle object of "radians" radians (float).
  4086. */
  4087. function Angle(radians) {
  4088. var _this = this;
  4089. /**
  4090. * Returns the Angle value in degrees (float).
  4091. */
  4092. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4093. /**
  4094. * Returns the Angle value in radians (float).
  4095. */
  4096. this.radians = function () { return _this._radians; };
  4097. this._radians = radians;
  4098. if (this._radians < 0.0)
  4099. this._radians += (2.0 * Math.PI);
  4100. }
  4101. /**
  4102. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4103. */
  4104. Angle.BetweenTwoPoints = function (a, b) {
  4105. var delta = b.subtract(a);
  4106. var theta = Math.atan2(delta.y, delta.x);
  4107. return new Angle(theta);
  4108. };
  4109. /**
  4110. * Returns a new Angle object from the passed float in radians.
  4111. */
  4112. Angle.FromRadians = function (radians) {
  4113. return new Angle(radians);
  4114. };
  4115. /**
  4116. * Returns a new Angle object from the passed float in degrees.
  4117. */
  4118. Angle.FromDegrees = function (degrees) {
  4119. return new Angle(degrees * Math.PI / 180.0);
  4120. };
  4121. return Angle;
  4122. }());
  4123. BABYLON.Angle = Angle;
  4124. var Arc2 = (function () {
  4125. /**
  4126. * Creates an Arc object from the three passed points : start, middle and end.
  4127. */
  4128. function Arc2(startPoint, midPoint, endPoint) {
  4129. this.startPoint = startPoint;
  4130. this.midPoint = midPoint;
  4131. this.endPoint = endPoint;
  4132. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4133. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4134. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4135. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4136. 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);
  4137. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4138. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4139. var a1 = this.startAngle.degrees();
  4140. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4141. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4142. // angles correction
  4143. if (a2 - a1 > +180.0)
  4144. a2 -= 360.0;
  4145. if (a2 - a1 < -180.0)
  4146. a2 += 360.0;
  4147. if (a3 - a2 > +180.0)
  4148. a3 -= 360.0;
  4149. if (a3 - a2 < -180.0)
  4150. a3 += 360.0;
  4151. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4152. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4153. }
  4154. return Arc2;
  4155. }());
  4156. BABYLON.Arc2 = Arc2;
  4157. var Path2 = (function () {
  4158. /**
  4159. * Creates a Path2 object from the starting 2D coordinates x and y.
  4160. */
  4161. function Path2(x, y) {
  4162. this._points = new Array();
  4163. this._length = 0.0;
  4164. this.closed = false;
  4165. this._points.push(new Vector2(x, y));
  4166. }
  4167. /**
  4168. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4169. * Returns the updated Path2.
  4170. */
  4171. Path2.prototype.addLineTo = function (x, y) {
  4172. if (closed) {
  4173. //Tools.Error("cannot add lines to closed paths");
  4174. return this;
  4175. }
  4176. var newPoint = new Vector2(x, y);
  4177. var previousPoint = this._points[this._points.length - 1];
  4178. this._points.push(newPoint);
  4179. this._length += newPoint.subtract(previousPoint).length();
  4180. return this;
  4181. };
  4182. /**
  4183. * 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.
  4184. * Returns the updated Path2.
  4185. */
  4186. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4187. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4188. if (closed) {
  4189. //Tools.Error("cannot add arcs to closed paths");
  4190. return this;
  4191. }
  4192. var startPoint = this._points[this._points.length - 1];
  4193. var midPoint = new Vector2(midX, midY);
  4194. var endPoint = new Vector2(endX, endY);
  4195. var arc = new Arc2(startPoint, midPoint, endPoint);
  4196. var increment = arc.angle.radians() / numberOfSegments;
  4197. if (arc.orientation === Orientation.CW)
  4198. increment *= -1;
  4199. var currentAngle = arc.startAngle.radians() + increment;
  4200. for (var i = 0; i < numberOfSegments; i++) {
  4201. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4202. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4203. this.addLineTo(x, y);
  4204. currentAngle += increment;
  4205. }
  4206. return this;
  4207. };
  4208. /**
  4209. * Closes the Path2.
  4210. * Returns the Path2.
  4211. */
  4212. Path2.prototype.close = function () {
  4213. this.closed = true;
  4214. return this;
  4215. };
  4216. /**
  4217. * Returns the Path2 total length (float).
  4218. */
  4219. Path2.prototype.length = function () {
  4220. var result = this._length;
  4221. if (!this.closed) {
  4222. var lastPoint = this._points[this._points.length - 1];
  4223. var firstPoint = this._points[0];
  4224. result += (firstPoint.subtract(lastPoint).length());
  4225. }
  4226. return result;
  4227. };
  4228. /**
  4229. * Returns the Path2 internal array of points.
  4230. */
  4231. Path2.prototype.getPoints = function () {
  4232. return this._points;
  4233. };
  4234. /**
  4235. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4236. */
  4237. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4238. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4239. //Tools.Error("normalized length position should be between 0 and 1.");
  4240. return Vector2.Zero();
  4241. }
  4242. var lengthPosition = normalizedLengthPosition * this.length();
  4243. var previousOffset = 0;
  4244. for (var i = 0; i < this._points.length; i++) {
  4245. var j = (i + 1) % this._points.length;
  4246. var a = this._points[i];
  4247. var b = this._points[j];
  4248. var bToA = b.subtract(a);
  4249. var nextOffset = (bToA.length() + previousOffset);
  4250. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4251. var dir = bToA.normalize();
  4252. var localOffset = lengthPosition - previousOffset;
  4253. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4254. }
  4255. previousOffset = nextOffset;
  4256. }
  4257. //Tools.Error("internal error");
  4258. return Vector2.Zero();
  4259. };
  4260. /**
  4261. * Returns a new Path2 starting at the coordinates (x, y).
  4262. */
  4263. Path2.StartingAt = function (x, y) {
  4264. return new Path2(x, y);
  4265. };
  4266. return Path2;
  4267. }());
  4268. BABYLON.Path2 = Path2;
  4269. var Path3D = (function () {
  4270. /**
  4271. * new Path3D(path, normal, raw)
  4272. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4273. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4274. * path : an array of Vector3, the curve axis of the Path3D
  4275. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4276. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4277. */
  4278. function Path3D(path, firstNormal, raw) {
  4279. this.path = path;
  4280. this._curve = new Array();
  4281. this._distances = new Array();
  4282. this._tangents = new Array();
  4283. this._normals = new Array();
  4284. this._binormals = new Array();
  4285. for (var p = 0; p < path.length; p++) {
  4286. this._curve[p] = path[p].clone(); // hard copy
  4287. }
  4288. this._raw = raw || false;
  4289. this._compute(firstNormal);
  4290. }
  4291. /**
  4292. * Returns the Path3D array of successive Vector3 designing its curve.
  4293. */
  4294. Path3D.prototype.getCurve = function () {
  4295. return this._curve;
  4296. };
  4297. /**
  4298. * Returns an array populated with tangent vectors on each Path3D curve point.
  4299. */
  4300. Path3D.prototype.getTangents = function () {
  4301. return this._tangents;
  4302. };
  4303. /**
  4304. * Returns an array populated with normal vectors on each Path3D curve point.
  4305. */
  4306. Path3D.prototype.getNormals = function () {
  4307. return this._normals;
  4308. };
  4309. /**
  4310. * Returns an array populated with binormal vectors on each Path3D curve point.
  4311. */
  4312. Path3D.prototype.getBinormals = function () {
  4313. return this._binormals;
  4314. };
  4315. /**
  4316. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4317. */
  4318. Path3D.prototype.getDistances = function () {
  4319. return this._distances;
  4320. };
  4321. /**
  4322. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4323. * Returns the same object updated.
  4324. */
  4325. Path3D.prototype.update = function (path, firstNormal) {
  4326. for (var p = 0; p < path.length; p++) {
  4327. this._curve[p].x = path[p].x;
  4328. this._curve[p].y = path[p].y;
  4329. this._curve[p].z = path[p].z;
  4330. }
  4331. this._compute(firstNormal);
  4332. return this;
  4333. };
  4334. // private function compute() : computes tangents, normals and binormals
  4335. Path3D.prototype._compute = function (firstNormal) {
  4336. var l = this._curve.length;
  4337. // first and last tangents
  4338. this._tangents[0] = this._getFirstNonNullVector(0);
  4339. if (!this._raw) {
  4340. this._tangents[0].normalize();
  4341. }
  4342. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4343. if (!this._raw) {
  4344. this._tangents[l - 1].normalize();
  4345. }
  4346. // normals and binormals at first point : arbitrary vector with _normalVector()
  4347. var tg0 = this._tangents[0];
  4348. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4349. this._normals[0] = pp0;
  4350. if (!this._raw) {
  4351. this._normals[0].normalize();
  4352. }
  4353. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4354. if (!this._raw) {
  4355. this._binormals[0].normalize();
  4356. }
  4357. this._distances[0] = 0.0;
  4358. // normals and binormals : next points
  4359. var prev; // previous vector (segment)
  4360. var cur; // current vector (segment)
  4361. var curTang; // current tangent
  4362. // previous normal
  4363. var prevBinor; // previous binormal
  4364. for (var i = 1; i < l; i++) {
  4365. // tangents
  4366. prev = this._getLastNonNullVector(i);
  4367. if (i < l - 1) {
  4368. cur = this._getFirstNonNullVector(i);
  4369. this._tangents[i] = prev.add(cur);
  4370. this._tangents[i].normalize();
  4371. }
  4372. this._distances[i] = this._distances[i - 1] + prev.length();
  4373. // normals and binormals
  4374. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4375. curTang = this._tangents[i];
  4376. prevBinor = this._binormals[i - 1];
  4377. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4378. if (!this._raw) {
  4379. this._normals[i].normalize();
  4380. }
  4381. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4382. if (!this._raw) {
  4383. this._binormals[i].normalize();
  4384. }
  4385. }
  4386. };
  4387. // private function getFirstNonNullVector(index)
  4388. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4389. Path3D.prototype._getFirstNonNullVector = function (index) {
  4390. var i = 1;
  4391. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4392. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4393. i++;
  4394. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4395. }
  4396. return nNVector;
  4397. };
  4398. // private function getLastNonNullVector(index)
  4399. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4400. Path3D.prototype._getLastNonNullVector = function (index) {
  4401. var i = 1;
  4402. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4403. while (nLVector.length() === 0 && index > i + 1) {
  4404. i++;
  4405. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4406. }
  4407. return nLVector;
  4408. };
  4409. // private function normalVector(v0, vt, va) :
  4410. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4411. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4412. Path3D.prototype._normalVector = function (v0, vt, va) {
  4413. var normal0;
  4414. var tgl = vt.length();
  4415. if (tgl === 0.0) {
  4416. tgl = 1.0;
  4417. }
  4418. if (va === undefined || va === null) {
  4419. var point;
  4420. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4421. point = new Vector3(0.0, -1.0, 0.0);
  4422. }
  4423. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4424. point = new Vector3(1.0, 0.0, 0.0);
  4425. }
  4426. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4427. point = new Vector3(0.0, 0.0, 1.0);
  4428. }
  4429. normal0 = Vector3.Cross(vt, point);
  4430. }
  4431. else {
  4432. normal0 = Vector3.Cross(vt, va);
  4433. Vector3.CrossToRef(normal0, vt, normal0);
  4434. }
  4435. normal0.normalize();
  4436. return normal0;
  4437. };
  4438. return Path3D;
  4439. }());
  4440. BABYLON.Path3D = Path3D;
  4441. var Curve3 = (function () {
  4442. /**
  4443. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4444. * A Curve3 is designed from a series of successive Vector3.
  4445. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4446. */
  4447. function Curve3(points) {
  4448. this._length = 0.0;
  4449. this._points = points;
  4450. this._length = this._computeLength(points);
  4451. }
  4452. /**
  4453. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4454. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4455. * @param v1 (Vector3) the control point
  4456. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4457. * @param nbPoints (integer) the wanted number of points in the curve
  4458. */
  4459. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4460. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4461. var bez = new Array();
  4462. var equation = function (t, val0, val1, val2) {
  4463. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4464. return res;
  4465. };
  4466. for (var i = 0; i <= nbPoints; i++) {
  4467. 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)));
  4468. }
  4469. return new Curve3(bez);
  4470. };
  4471. /**
  4472. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4473. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4474. * @param v1 (Vector3) the first control point
  4475. * @param v2 (Vector3) the second control point
  4476. * @param v3 (Vector3) the end point of the Cubic Bezier
  4477. * @param nbPoints (integer) the wanted number of points in the curve
  4478. */
  4479. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4480. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4481. var bez = new Array();
  4482. var equation = function (t, val0, val1, val2, val3) {
  4483. 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;
  4484. return res;
  4485. };
  4486. for (var i = 0; i <= nbPoints; i++) {
  4487. 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)));
  4488. }
  4489. return new Curve3(bez);
  4490. };
  4491. /**
  4492. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4493. * @param p1 (Vector3) the origin point of the Hermite Spline
  4494. * @param t1 (Vector3) the tangent vector at the origin point
  4495. * @param p2 (Vector3) the end point of the Hermite Spline
  4496. * @param t2 (Vector3) the tangent vector at the end point
  4497. * @param nbPoints (integer) the wanted number of points in the curve
  4498. */
  4499. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4500. var hermite = new Array();
  4501. var step = 1.0 / nbPoints;
  4502. for (var i = 0; i <= nbPoints; i++) {
  4503. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4504. }
  4505. return new Curve3(hermite);
  4506. };
  4507. /**
  4508. * Returns a Curve3 object along a CatmullRom Spline curve :
  4509. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4510. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4511. */
  4512. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4513. var totalPoints = new Array();
  4514. totalPoints.push(points[0].clone());
  4515. Array.prototype.push.apply(totalPoints, points);
  4516. totalPoints.push(points[points.length - 1].clone());
  4517. var catmullRom = new Array();
  4518. var step = 1.0 / nbPoints;
  4519. for (var i = 0; i < totalPoints.length - 3; i++) {
  4520. var amount = 0.0;
  4521. for (var c = 0; c < nbPoints; c++) {
  4522. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4523. amount += step;
  4524. }
  4525. }
  4526. i--;
  4527. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4528. return new Curve3(catmullRom);
  4529. };
  4530. /**
  4531. * Returns the Curve3 stored array of successive Vector3
  4532. */
  4533. Curve3.prototype.getPoints = function () {
  4534. return this._points;
  4535. };
  4536. /**
  4537. * Returns the computed length (float) of the curve.
  4538. */
  4539. Curve3.prototype.length = function () {
  4540. return this._length;
  4541. };
  4542. /**
  4543. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4544. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4545. * curveA and curveB keep unchanged.
  4546. */
  4547. Curve3.prototype.continue = function (curve) {
  4548. var lastPoint = this._points[this._points.length - 1];
  4549. var continuedPoints = this._points.slice();
  4550. var curvePoints = curve.getPoints();
  4551. for (var i = 1; i < curvePoints.length; i++) {
  4552. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4553. }
  4554. var continuedCurve = new Curve3(continuedPoints);
  4555. return continuedCurve;
  4556. };
  4557. Curve3.prototype._computeLength = function (path) {
  4558. var l = 0;
  4559. for (var i = 1; i < path.length; i++) {
  4560. l += (path[i].subtract(path[i - 1])).length();
  4561. }
  4562. return l;
  4563. };
  4564. return Curve3;
  4565. }());
  4566. BABYLON.Curve3 = Curve3;
  4567. // SphericalHarmonics
  4568. var SphericalHarmonics = (function () {
  4569. function SphericalHarmonics() {
  4570. this.L00 = Vector3.Zero();
  4571. this.L1_1 = Vector3.Zero();
  4572. this.L10 = Vector3.Zero();
  4573. this.L11 = Vector3.Zero();
  4574. this.L2_2 = Vector3.Zero();
  4575. this.L2_1 = Vector3.Zero();
  4576. this.L20 = Vector3.Zero();
  4577. this.L21 = Vector3.Zero();
  4578. this.L22 = Vector3.Zero();
  4579. }
  4580. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4581. var colorVector = new Vector3(color.r, color.g, color.b);
  4582. var c = colorVector.scale(deltaSolidAngle);
  4583. this.L00 = this.L00.add(c.scale(0.282095));
  4584. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4585. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4586. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4587. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4588. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4589. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4590. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4591. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4592. };
  4593. SphericalHarmonics.prototype.scale = function (scale) {
  4594. this.L00 = this.L00.scale(scale);
  4595. this.L1_1 = this.L1_1.scale(scale);
  4596. this.L10 = this.L10.scale(scale);
  4597. this.L11 = this.L11.scale(scale);
  4598. this.L2_2 = this.L2_2.scale(scale);
  4599. this.L2_1 = this.L2_1.scale(scale);
  4600. this.L20 = this.L20.scale(scale);
  4601. this.L21 = this.L21.scale(scale);
  4602. this.L22 = this.L22.scale(scale);
  4603. };
  4604. return SphericalHarmonics;
  4605. }());
  4606. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4607. // SphericalPolynomial
  4608. var SphericalPolynomial = (function () {
  4609. function SphericalPolynomial() {
  4610. this.x = Vector3.Zero();
  4611. this.y = Vector3.Zero();
  4612. this.z = Vector3.Zero();
  4613. this.xx = Vector3.Zero();
  4614. this.yy = Vector3.Zero();
  4615. this.zz = Vector3.Zero();
  4616. this.xy = Vector3.Zero();
  4617. this.yz = Vector3.Zero();
  4618. this.zx = Vector3.Zero();
  4619. }
  4620. SphericalPolynomial.prototype.addAmbient = function (color) {
  4621. var colorVector = new Vector3(color.r, color.g, color.b);
  4622. this.xx = this.xx.add(colorVector);
  4623. this.yy = this.yy.add(colorVector);
  4624. this.zz = this.zz.add(colorVector);
  4625. };
  4626. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4627. var result = new SphericalPolynomial();
  4628. result.x = harmonics.L11.scale(1.02333);
  4629. result.y = harmonics.L1_1.scale(1.02333);
  4630. result.z = harmonics.L10.scale(1.02333);
  4631. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4632. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4633. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4634. result.yz = harmonics.L2_1.scale(0.858086);
  4635. result.zx = harmonics.L21.scale(0.858086);
  4636. result.xy = harmonics.L2_2.scale(0.858086);
  4637. return result;
  4638. };
  4639. return SphericalPolynomial;
  4640. }());
  4641. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4642. // Vertex formats
  4643. var PositionNormalVertex = (function () {
  4644. function PositionNormalVertex(position, normal) {
  4645. if (position === void 0) { position = Vector3.Zero(); }
  4646. if (normal === void 0) { normal = Vector3.Up(); }
  4647. this.position = position;
  4648. this.normal = normal;
  4649. }
  4650. PositionNormalVertex.prototype.clone = function () {
  4651. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4652. };
  4653. return PositionNormalVertex;
  4654. }());
  4655. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4656. var PositionNormalTextureVertex = (function () {
  4657. function PositionNormalTextureVertex(position, normal, uv) {
  4658. if (position === void 0) { position = Vector3.Zero(); }
  4659. if (normal === void 0) { normal = Vector3.Up(); }
  4660. if (uv === void 0) { uv = Vector2.Zero(); }
  4661. this.position = position;
  4662. this.normal = normal;
  4663. this.uv = uv;
  4664. }
  4665. PositionNormalTextureVertex.prototype.clone = function () {
  4666. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4667. };
  4668. return PositionNormalTextureVertex;
  4669. }());
  4670. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4671. // Temporary pre-allocated objects for engine internal use
  4672. // usage in any internal function :
  4673. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4674. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4675. var Tmp = (function () {
  4676. function Tmp() {
  4677. }
  4678. return Tmp;
  4679. }());
  4680. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4681. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4682. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4683. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4684. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4685. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4686. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4687. Matrix.Zero(), Matrix.Zero(),
  4688. Matrix.Zero(), Matrix.Zero(),
  4689. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4690. BABYLON.Tmp = Tmp;
  4691. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4692. var MathTmp = (function () {
  4693. function MathTmp() {
  4694. }
  4695. return MathTmp;
  4696. }());
  4697. MathTmp.Vector3 = [Vector3.Zero()];
  4698. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4699. MathTmp.Quaternion = [Quaternion.Zero()];
  4700. })(BABYLON || (BABYLON = {}));
  4701. //# sourceMappingURL=babylon.math.js.map
  4702. //# sourceMappingURL=babylon.mixins.js.map
  4703. var BABYLON;
  4704. (function (BABYLON) {
  4705. function generateSerializableMember(type, sourceName) {
  4706. return function (target, propertyKey) {
  4707. if (!target.__serializableMembers) {
  4708. target.__serializableMembers = {};
  4709. }
  4710. if (!target.__serializableMembers[propertyKey]) {
  4711. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4712. }
  4713. };
  4714. }
  4715. function generateExpandMember(setCallback) {
  4716. return function (target, propertyKey) {
  4717. if (setCallback) {
  4718. var key = "_" + propertyKey;
  4719. Object.defineProperty(target, propertyKey, {
  4720. get: function () {
  4721. return this[key];
  4722. },
  4723. set: function (value) {
  4724. if (this[key] === value) {
  4725. return;
  4726. }
  4727. this[key] = value;
  4728. target[setCallback].apply(this);
  4729. },
  4730. enumerable: true,
  4731. configurable: true
  4732. });
  4733. }
  4734. };
  4735. }
  4736. function expandToProperty(callback) {
  4737. return generateExpandMember(callback);
  4738. }
  4739. BABYLON.expandToProperty = expandToProperty;
  4740. function serialize(sourceName) {
  4741. return generateSerializableMember(0, sourceName); // value member
  4742. }
  4743. BABYLON.serialize = serialize;
  4744. function serializeAsTexture(sourceName) {
  4745. return generateSerializableMember(1, sourceName); // texture member
  4746. }
  4747. BABYLON.serializeAsTexture = serializeAsTexture;
  4748. function serializeAsColor3(sourceName) {
  4749. return generateSerializableMember(2, sourceName); // color3 member
  4750. }
  4751. BABYLON.serializeAsColor3 = serializeAsColor3;
  4752. function serializeAsFresnelParameters(sourceName) {
  4753. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4754. }
  4755. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4756. function serializeAsVector2(sourceName) {
  4757. return generateSerializableMember(4, sourceName); // vector2 member
  4758. }
  4759. BABYLON.serializeAsVector2 = serializeAsVector2;
  4760. function serializeAsVector3(sourceName) {
  4761. return generateSerializableMember(5, sourceName); // vector3 member
  4762. }
  4763. BABYLON.serializeAsVector3 = serializeAsVector3;
  4764. function serializeAsMeshReference(sourceName) {
  4765. return generateSerializableMember(6, sourceName); // mesh reference member
  4766. }
  4767. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4768. function serializeAsColorCurves(sourceName) {
  4769. return generateSerializableMember(7, sourceName); // color curves
  4770. }
  4771. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4772. var SerializationHelper = (function () {
  4773. function SerializationHelper() {
  4774. }
  4775. SerializationHelper.Serialize = function (entity, serializationObject) {
  4776. if (!serializationObject) {
  4777. serializationObject = {};
  4778. }
  4779. // Tags
  4780. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4781. // Properties
  4782. for (var property in entity.__serializableMembers) {
  4783. var propertyDescriptor = entity.__serializableMembers[property];
  4784. var targetPropertyName = propertyDescriptor.sourceName || property;
  4785. var propertyType = propertyDescriptor.type;
  4786. var sourceProperty = entity[property];
  4787. if (sourceProperty !== undefined && sourceProperty !== null) {
  4788. switch (propertyType) {
  4789. case 0:
  4790. serializationObject[targetPropertyName] = sourceProperty;
  4791. break;
  4792. case 1:
  4793. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4794. break;
  4795. case 2:
  4796. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4797. break;
  4798. case 3:
  4799. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4800. break;
  4801. case 4:
  4802. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4803. break;
  4804. case 5:
  4805. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4806. break;
  4807. case 6:
  4808. serializationObject[targetPropertyName] = sourceProperty.id;
  4809. break;
  4810. case 7:
  4811. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4812. break;
  4813. }
  4814. }
  4815. }
  4816. return serializationObject;
  4817. };
  4818. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4819. var destination = creationFunction();
  4820. // Tags
  4821. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4822. // Properties
  4823. for (var property in destination.__serializableMembers) {
  4824. var propertyDescriptor = destination.__serializableMembers[property];
  4825. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4826. var propertyType = propertyDescriptor.type;
  4827. if (sourceProperty !== undefined && sourceProperty !== null) {
  4828. switch (propertyType) {
  4829. case 0:
  4830. destination[property] = sourceProperty;
  4831. break;
  4832. case 1:
  4833. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4834. break;
  4835. case 2:
  4836. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4837. break;
  4838. case 3:
  4839. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4840. break;
  4841. case 4:
  4842. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4843. break;
  4844. case 5:
  4845. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4846. break;
  4847. case 6:
  4848. destination[property] = scene.getLastMeshByID(sourceProperty);
  4849. break;
  4850. case 7:
  4851. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4852. break;
  4853. }
  4854. }
  4855. }
  4856. return destination;
  4857. };
  4858. SerializationHelper.Clone = function (creationFunction, source) {
  4859. var destination = creationFunction();
  4860. // Tags
  4861. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4862. // Properties
  4863. for (var property in destination.__serializableMembers) {
  4864. var propertyDescriptor = destination.__serializableMembers[property];
  4865. var sourceProperty = source[property];
  4866. var propertyType = propertyDescriptor.type;
  4867. if (sourceProperty !== undefined && sourceProperty !== null) {
  4868. switch (propertyType) {
  4869. case 0: // Value
  4870. case 6:
  4871. destination[property] = sourceProperty;
  4872. break;
  4873. case 1: // Texture
  4874. case 2: // Color3
  4875. case 3: // FresnelParameters
  4876. case 4: // Vector2
  4877. case 5: // Vector3
  4878. case 7:
  4879. destination[property] = sourceProperty.clone();
  4880. break;
  4881. }
  4882. }
  4883. }
  4884. return destination;
  4885. };
  4886. return SerializationHelper;
  4887. }());
  4888. BABYLON.SerializationHelper = SerializationHelper;
  4889. })(BABYLON || (BABYLON = {}));
  4890. //# sourceMappingURL=babylon.decorators.js.map
  4891. var BABYLON;
  4892. (function (BABYLON) {
  4893. /**
  4894. * A class serves as a medium between the observable and its observers
  4895. */
  4896. var EventState = (function () {
  4897. /**
  4898. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4899. */
  4900. function EventState(mask, skipNextObservers) {
  4901. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4902. this.initalize(mask, skipNextObservers);
  4903. }
  4904. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4905. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4906. this.mask = mask;
  4907. this.skipNextObservers = skipNextObservers;
  4908. return this;
  4909. };
  4910. return EventState;
  4911. }());
  4912. BABYLON.EventState = EventState;
  4913. /**
  4914. * Represent an Observer registered to a given Observable object.
  4915. */
  4916. var Observer = (function () {
  4917. function Observer(callback, mask) {
  4918. this.callback = callback;
  4919. this.mask = mask;
  4920. }
  4921. return Observer;
  4922. }());
  4923. BABYLON.Observer = Observer;
  4924. /**
  4925. * The Observable class is a simple implementation of the Observable pattern.
  4926. * 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.
  4927. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4928. * 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).
  4929. * 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.
  4930. */
  4931. var Observable = (function () {
  4932. function Observable() {
  4933. this._observers = new Array();
  4934. this._eventState = new EventState(0);
  4935. }
  4936. /**
  4937. * Create a new Observer with the specified callback
  4938. * @param callback the callback that will be executed for that Observer
  4939. * @param mask the mask used to filter observers
  4940. * @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.
  4941. */
  4942. Observable.prototype.add = function (callback, mask, insertFirst) {
  4943. if (mask === void 0) { mask = -1; }
  4944. if (insertFirst === void 0) { insertFirst = false; }
  4945. if (!callback) {
  4946. return null;
  4947. }
  4948. var observer = new Observer(callback, mask);
  4949. if (insertFirst) {
  4950. this._observers.unshift(observer);
  4951. }
  4952. else {
  4953. this._observers.push(observer);
  4954. }
  4955. return observer;
  4956. };
  4957. /**
  4958. * Remove an Observer from the Observable object
  4959. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4960. */
  4961. Observable.prototype.remove = function (observer) {
  4962. var index = this._observers.indexOf(observer);
  4963. if (index !== -1) {
  4964. this._observers.splice(index, 1);
  4965. return true;
  4966. }
  4967. return false;
  4968. };
  4969. /**
  4970. * Remove a callback from the Observable object
  4971. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4972. */
  4973. Observable.prototype.removeCallback = function (callback) {
  4974. for (var index = 0; index < this._observers.length; index++) {
  4975. if (this._observers[index].callback === callback) {
  4976. this._observers.splice(index, 1);
  4977. return true;
  4978. }
  4979. }
  4980. return false;
  4981. };
  4982. /**
  4983. * Notify all Observers by calling their respective callback with the given data
  4984. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  4985. * @param eventData
  4986. * @param mask
  4987. */
  4988. Observable.prototype.notifyObservers = function (eventData, mask) {
  4989. if (mask === void 0) { mask = -1; }
  4990. var state = this._eventState;
  4991. state.mask = mask;
  4992. state.skipNextObservers = false;
  4993. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4994. var obs = _a[_i];
  4995. if (obs.mask & mask) {
  4996. obs.callback(eventData, state);
  4997. }
  4998. if (state.skipNextObservers) {
  4999. return false;
  5000. }
  5001. }
  5002. return true;
  5003. };
  5004. /**
  5005. * return true is the Observable has at least one Observer registered
  5006. */
  5007. Observable.prototype.hasObservers = function () {
  5008. return this._observers.length > 0;
  5009. };
  5010. /**
  5011. * Clear the list of observers
  5012. */
  5013. Observable.prototype.clear = function () {
  5014. this._observers = new Array();
  5015. };
  5016. /**
  5017. * Clone the current observable
  5018. */
  5019. Observable.prototype.clone = function () {
  5020. var result = new Observable();
  5021. result._observers = this._observers.slice(0);
  5022. return result;
  5023. };
  5024. /**
  5025. * Does this observable handles observer registered with a given mask
  5026. * @param {number} trigger - the mask to be tested
  5027. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5028. **/
  5029. Observable.prototype.hasSpecificMask = function (mask) {
  5030. if (mask === void 0) { mask = -1; }
  5031. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5032. var obs = _a[_i];
  5033. if (obs.mask & mask && obs.mask === mask) {
  5034. return true;
  5035. }
  5036. }
  5037. return false;
  5038. };
  5039. return Observable;
  5040. }());
  5041. BABYLON.Observable = Observable;
  5042. })(BABYLON || (BABYLON = {}));
  5043. //# sourceMappingURL=babylon.observable.js.map
  5044. var BABYLON;
  5045. (function (BABYLON) {
  5046. var SmartArray = (function () {
  5047. function SmartArray(capacity) {
  5048. this.length = 0;
  5049. this._duplicateId = 0;
  5050. this.data = new Array(capacity);
  5051. this._id = SmartArray._GlobalId++;
  5052. }
  5053. SmartArray.prototype.push = function (value) {
  5054. this.data[this.length++] = value;
  5055. if (this.length > this.data.length) {
  5056. this.data.length *= 2;
  5057. }
  5058. if (!value.__smartArrayFlags) {
  5059. value.__smartArrayFlags = {};
  5060. }
  5061. value.__smartArrayFlags[this._id] = this._duplicateId;
  5062. };
  5063. SmartArray.prototype.forEach = function (func) {
  5064. for (var index = 0; index < this.length; index++) {
  5065. func(this.data[index]);
  5066. }
  5067. };
  5068. SmartArray.prototype.pushNoDuplicate = function (value) {
  5069. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5070. return false;
  5071. }
  5072. this.push(value);
  5073. return true;
  5074. };
  5075. SmartArray.prototype.sort = function (compareFn) {
  5076. this.data.sort(compareFn);
  5077. };
  5078. SmartArray.prototype.reset = function () {
  5079. this.length = 0;
  5080. this._duplicateId++;
  5081. };
  5082. SmartArray.prototype.dispose = function () {
  5083. this.reset();
  5084. this.data.length = 0;
  5085. };
  5086. SmartArray.prototype.concat = function (array) {
  5087. if (array.length === 0) {
  5088. return;
  5089. }
  5090. if (this.length + array.length > this.data.length) {
  5091. this.data.length = (this.length + array.length) * 2;
  5092. }
  5093. for (var index = 0; index < array.length; index++) {
  5094. this.data[this.length++] = (array.data || array)[index];
  5095. }
  5096. };
  5097. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5098. if (array.length === 0) {
  5099. return;
  5100. }
  5101. if (this.length + array.length > this.data.length) {
  5102. this.data.length = (this.length + array.length) * 2;
  5103. }
  5104. for (var index = 0; index < array.length; index++) {
  5105. var item = (array.data || array)[index];
  5106. this.pushNoDuplicate(item);
  5107. }
  5108. };
  5109. SmartArray.prototype.indexOf = function (value) {
  5110. var position = this.data.indexOf(value);
  5111. if (position >= this.length) {
  5112. return -1;
  5113. }
  5114. return position;
  5115. };
  5116. SmartArray.prototype.contains = function (value) {
  5117. return this.data.indexOf(value) !== -1;
  5118. };
  5119. return SmartArray;
  5120. }());
  5121. // Statics
  5122. SmartArray._GlobalId = 0;
  5123. BABYLON.SmartArray = SmartArray;
  5124. })(BABYLON || (BABYLON = {}));
  5125. //# sourceMappingURL=babylon.smartArray.js.map
  5126. var BABYLON;
  5127. (function (BABYLON) {
  5128. // Screenshots
  5129. var screenshotCanvas;
  5130. var cloneValue = function (source, destinationObject) {
  5131. if (!source)
  5132. return null;
  5133. if (source instanceof BABYLON.Mesh) {
  5134. return null;
  5135. }
  5136. if (source instanceof BABYLON.SubMesh) {
  5137. return source.clone(destinationObject);
  5138. }
  5139. else if (source.clone) {
  5140. return source.clone();
  5141. }
  5142. return null;
  5143. };
  5144. var Tools = (function () {
  5145. function Tools() {
  5146. }
  5147. ;
  5148. Tools.Instantiate = function (className) {
  5149. var arr = className.split(".");
  5150. var fn = (window || this);
  5151. for (var i = 0, len = arr.length; i < len; i++) {
  5152. fn = fn[arr[i]];
  5153. }
  5154. if (typeof fn !== "function") {
  5155. return null;
  5156. }
  5157. return fn;
  5158. };
  5159. Tools.SetImmediate = function (action) {
  5160. if (window.setImmediate) {
  5161. window.setImmediate(action);
  5162. }
  5163. else {
  5164. setTimeout(action, 1);
  5165. }
  5166. };
  5167. Tools.IsExponentOfTwo = function (value) {
  5168. var count = 1;
  5169. do {
  5170. count *= 2;
  5171. } while (count < value);
  5172. return count === value;
  5173. };
  5174. Tools.GetExponentOfTwo = function (value, max) {
  5175. var count = 1;
  5176. do {
  5177. count *= 2;
  5178. } while (count < value);
  5179. if (count > max)
  5180. count = max;
  5181. return count;
  5182. };
  5183. Tools.GetFilename = function (path) {
  5184. var index = path.lastIndexOf("/");
  5185. if (index < 0)
  5186. return path;
  5187. return path.substring(index + 1);
  5188. };
  5189. Tools.GetDOMTextContent = function (element) {
  5190. var result = "";
  5191. var child = element.firstChild;
  5192. while (child) {
  5193. if (child.nodeType === 3) {
  5194. result += child.textContent;
  5195. }
  5196. child = child.nextSibling;
  5197. }
  5198. return result;
  5199. };
  5200. Tools.ToDegrees = function (angle) {
  5201. return angle * 180 / Math.PI;
  5202. };
  5203. Tools.ToRadians = function (angle) {
  5204. return angle * Math.PI / 180;
  5205. };
  5206. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5207. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5208. var output = "";
  5209. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5210. var i = 0;
  5211. var bytes = new Uint8Array(buffer);
  5212. while (i < bytes.length) {
  5213. chr1 = bytes[i++];
  5214. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5215. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5216. enc1 = chr1 >> 2;
  5217. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5218. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5219. enc4 = chr3 & 63;
  5220. if (isNaN(chr2)) {
  5221. enc3 = enc4 = 64;
  5222. }
  5223. else if (isNaN(chr3)) {
  5224. enc4 = 64;
  5225. }
  5226. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5227. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5228. }
  5229. return "data:image/png;base64," + output;
  5230. };
  5231. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5232. if (bias === void 0) { bias = null; }
  5233. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5234. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5235. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5236. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5237. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5238. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5239. }
  5240. if (bias) {
  5241. minimum.x -= minimum.x * bias.x + bias.y;
  5242. minimum.y -= minimum.y * bias.x + bias.y;
  5243. minimum.z -= minimum.z * bias.x + bias.y;
  5244. maximum.x += maximum.x * bias.x + bias.y;
  5245. maximum.y += maximum.y * bias.x + bias.y;
  5246. maximum.z += maximum.z * bias.x + bias.y;
  5247. }
  5248. return {
  5249. minimum: minimum,
  5250. maximum: maximum
  5251. };
  5252. };
  5253. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5254. if (bias === void 0) { bias = null; }
  5255. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5256. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5257. if (!stride) {
  5258. stride = 3;
  5259. }
  5260. for (var index = start; index < start + count; index++) {
  5261. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5262. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5263. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5264. }
  5265. if (bias) {
  5266. minimum.x -= minimum.x * bias.x + bias.y;
  5267. minimum.y -= minimum.y * bias.x + bias.y;
  5268. minimum.z -= minimum.z * bias.x + bias.y;
  5269. maximum.x += maximum.x * bias.x + bias.y;
  5270. maximum.y += maximum.y * bias.x + bias.y;
  5271. maximum.z += maximum.z * bias.x + bias.y;
  5272. }
  5273. return {
  5274. minimum: minimum,
  5275. maximum: maximum
  5276. };
  5277. };
  5278. Tools.Vector2ArrayFeeder = function (array) {
  5279. return function (index) {
  5280. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5281. var length = isFloatArray ? array.length / 2 : array.length;
  5282. if (index >= length) {
  5283. return null;
  5284. }
  5285. if (isFloatArray) {
  5286. var fa = array;
  5287. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5288. }
  5289. var a = array;
  5290. return a[index];
  5291. };
  5292. };
  5293. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5294. if (bias === void 0) { bias = null; }
  5295. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5296. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5297. var i = 0;
  5298. var cur = feeder(i++);
  5299. while (cur) {
  5300. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5301. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5302. cur = feeder(i++);
  5303. }
  5304. if (bias) {
  5305. minimum.x -= minimum.x * bias.x + bias.y;
  5306. minimum.y -= minimum.y * bias.x + bias.y;
  5307. maximum.x += maximum.x * bias.x + bias.y;
  5308. maximum.y += maximum.y * bias.x + bias.y;
  5309. }
  5310. return {
  5311. minimum: minimum,
  5312. maximum: maximum
  5313. };
  5314. };
  5315. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5316. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5317. return undefined;
  5318. return Array.isArray(obj) ? obj : [obj];
  5319. };
  5320. // Misc.
  5321. Tools.GetPointerPrefix = function () {
  5322. var eventPrefix = "pointer";
  5323. // Check if pointer events are supported
  5324. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5325. eventPrefix = "mouse";
  5326. }
  5327. return eventPrefix;
  5328. };
  5329. /**
  5330. * @param func - the function to be called
  5331. * @param requester - the object that will request the next frame. Falls back to window.
  5332. */
  5333. Tools.QueueNewFrame = function (func, requester) {
  5334. if (requester === void 0) { requester = window; }
  5335. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5336. /*if(requester.isPresenting) {
  5337. return;
  5338. } else*/ if (requester.requestAnimationFrame)
  5339. requester.requestAnimationFrame(func);
  5340. else if (requester.msRequestAnimationFrame)
  5341. requester.msRequestAnimationFrame(func);
  5342. else if (requester.webkitRequestAnimationFrame)
  5343. requester.webkitRequestAnimationFrame(func);
  5344. else if (requester.mozRequestAnimationFrame)
  5345. requester.mozRequestAnimationFrame(func);
  5346. else if (requester.oRequestAnimationFrame)
  5347. requester.oRequestAnimationFrame(func);
  5348. else {
  5349. window.setTimeout(func, 16);
  5350. }
  5351. };
  5352. Tools.RequestFullscreen = function (element) {
  5353. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5354. if (!requestFunction)
  5355. return;
  5356. requestFunction.call(element);
  5357. };
  5358. Tools.ExitFullscreen = function () {
  5359. if (document.exitFullscreen) {
  5360. document.exitFullscreen();
  5361. }
  5362. else if (document.mozCancelFullScreen) {
  5363. document.mozCancelFullScreen();
  5364. }
  5365. else if (document.webkitCancelFullScreen) {
  5366. document.webkitCancelFullScreen();
  5367. }
  5368. else if (document.msCancelFullScreen) {
  5369. document.msCancelFullScreen();
  5370. }
  5371. };
  5372. Tools.SetCorsBehavior = function (url, img) {
  5373. if (Tools.CorsBehavior) {
  5374. switch (typeof (Tools.CorsBehavior)) {
  5375. case "function":
  5376. var result = Tools.CorsBehavior(url);
  5377. if (result) {
  5378. img.crossOrigin = result;
  5379. }
  5380. break;
  5381. case "string":
  5382. default:
  5383. img.crossOrigin = Tools.CorsBehavior;
  5384. break;
  5385. }
  5386. }
  5387. };
  5388. // External files
  5389. Tools.CleanUrl = function (url) {
  5390. url = url.replace(/#/mg, "%23");
  5391. return url;
  5392. };
  5393. Tools.LoadImage = function (url, onload, onerror, database) {
  5394. if (url instanceof ArrayBuffer) {
  5395. url = Tools.EncodeArrayBufferTobase64(url);
  5396. }
  5397. url = Tools.CleanUrl(url);
  5398. var img = new Image();
  5399. if (url.substr(0, 5) !== "data:") {
  5400. Tools.SetCorsBehavior(url, img);
  5401. }
  5402. img.onload = function () {
  5403. onload(img);
  5404. };
  5405. img.onerror = function (err) {
  5406. Tools.Error("Error while trying to load image: " + url);
  5407. if (Tools.UseFallbackTexture) {
  5408. img.src = Tools.fallbackTexture;
  5409. onload(img);
  5410. }
  5411. else {
  5412. onerror();
  5413. }
  5414. };
  5415. var noIndexedDB = function () {
  5416. img.src = url;
  5417. };
  5418. var loadFromIndexedDB = function () {
  5419. database.loadImageFromDB(url, img);
  5420. };
  5421. //ANY database to do!
  5422. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5423. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5424. }
  5425. else {
  5426. if (url.indexOf("file:") === -1) {
  5427. noIndexedDB();
  5428. }
  5429. else {
  5430. var textureName = url.substring(5).toLowerCase();
  5431. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5432. try {
  5433. var blobURL;
  5434. try {
  5435. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5436. }
  5437. catch (ex) {
  5438. // Chrome doesn't support oneTimeOnly parameter
  5439. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5440. }
  5441. img.src = blobURL;
  5442. }
  5443. catch (e) {
  5444. img.src = null;
  5445. }
  5446. }
  5447. else {
  5448. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5449. img.src = Tools.fallbackTexture;
  5450. }
  5451. }
  5452. }
  5453. return img;
  5454. };
  5455. //ANY
  5456. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5457. url = Tools.CleanUrl(url);
  5458. var noIndexedDB = function () {
  5459. var request = new XMLHttpRequest();
  5460. var loadUrl = Tools.BaseUrl + url;
  5461. request.open('GET', loadUrl, true);
  5462. if (useArrayBuffer) {
  5463. request.responseType = "arraybuffer";
  5464. }
  5465. request.onprogress = progressCallBack;
  5466. request.onreadystatechange = function () {
  5467. if (request.readyState === 4) {
  5468. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5469. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5470. callback(!useArrayBuffer ? request.responseText : request.response);
  5471. }
  5472. else {
  5473. if (onError) {
  5474. onError();
  5475. }
  5476. else {
  5477. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5478. }
  5479. }
  5480. }
  5481. };
  5482. request.send(null);
  5483. };
  5484. var loadFromIndexedDB = function () {
  5485. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5486. };
  5487. if (url.indexOf("file:") !== -1) {
  5488. var fileName = url.substring(5).toLowerCase();
  5489. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5490. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5491. }
  5492. else {
  5493. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5494. }
  5495. }
  5496. else {
  5497. // Caching all files
  5498. if (database && database.enableSceneOffline) {
  5499. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5500. }
  5501. else {
  5502. noIndexedDB();
  5503. }
  5504. }
  5505. };
  5506. /**
  5507. * Load a script (identified by an url). When the url returns, the
  5508. * content of this file is added into a new script element, attached to the DOM (body element)
  5509. */
  5510. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5511. var head = document.getElementsByTagName('head')[0];
  5512. var script = document.createElement('script');
  5513. script.type = 'text/javascript';
  5514. script.src = scriptUrl;
  5515. var self = this;
  5516. script.onload = function () {
  5517. if (onSuccess) {
  5518. onSuccess();
  5519. }
  5520. };
  5521. script.onerror = function () {
  5522. if (onError) {
  5523. onError();
  5524. }
  5525. };
  5526. head.appendChild(script);
  5527. };
  5528. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5529. var reader = new FileReader();
  5530. reader.onload = function (e) {
  5531. //target doesn't have result from ts 1.3
  5532. callback(e.target['result']);
  5533. };
  5534. reader.onprogress = progressCallback;
  5535. reader.readAsDataURL(fileToLoad);
  5536. };
  5537. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5538. var reader = new FileReader();
  5539. reader.onerror = function (e) {
  5540. Tools.Log("Error while reading file: " + fileToLoad.name);
  5541. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5542. };
  5543. reader.onload = function (e) {
  5544. //target doesn't have result from ts 1.3
  5545. callback(e.target['result']);
  5546. };
  5547. reader.onprogress = progressCallBack;
  5548. if (!useArrayBuffer) {
  5549. // Asynchronous read
  5550. reader.readAsText(fileToLoad);
  5551. }
  5552. else {
  5553. reader.readAsArrayBuffer(fileToLoad);
  5554. }
  5555. };
  5556. //returns a downloadable url to a file content.
  5557. Tools.FileAsURL = function (content) {
  5558. var fileBlob = new Blob([content]);
  5559. var url = window.URL || window.webkitURL;
  5560. var link = url.createObjectURL(fileBlob);
  5561. return link;
  5562. };
  5563. // Misc.
  5564. Tools.Format = function (value, decimals) {
  5565. if (decimals === void 0) { decimals = 2; }
  5566. return value.toFixed(decimals);
  5567. };
  5568. Tools.CheckExtends = function (v, min, max) {
  5569. if (v.x < min.x)
  5570. min.x = v.x;
  5571. if (v.y < min.y)
  5572. min.y = v.y;
  5573. if (v.z < min.z)
  5574. min.z = v.z;
  5575. if (v.x > max.x)
  5576. max.x = v.x;
  5577. if (v.y > max.y)
  5578. max.y = v.y;
  5579. if (v.z > max.z)
  5580. max.z = v.z;
  5581. };
  5582. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5583. for (var prop in source) {
  5584. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5585. continue;
  5586. }
  5587. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5588. continue;
  5589. }
  5590. var sourceValue = source[prop];
  5591. var typeOfSourceValue = typeof sourceValue;
  5592. if (typeOfSourceValue === "function") {
  5593. continue;
  5594. }
  5595. if (typeOfSourceValue === "object") {
  5596. if (sourceValue instanceof Array) {
  5597. destination[prop] = [];
  5598. if (sourceValue.length > 0) {
  5599. if (typeof sourceValue[0] == "object") {
  5600. for (var index = 0; index < sourceValue.length; index++) {
  5601. var clonedValue = cloneValue(sourceValue[index], destination);
  5602. if (destination[prop].indexOf(clonedValue) === -1) {
  5603. destination[prop].push(clonedValue);
  5604. }
  5605. }
  5606. }
  5607. else {
  5608. destination[prop] = sourceValue.slice(0);
  5609. }
  5610. }
  5611. }
  5612. else {
  5613. destination[prop] = cloneValue(sourceValue, destination);
  5614. }
  5615. }
  5616. else {
  5617. destination[prop] = sourceValue;
  5618. }
  5619. }
  5620. };
  5621. Tools.IsEmpty = function (obj) {
  5622. for (var i in obj) {
  5623. return false;
  5624. }
  5625. return true;
  5626. };
  5627. Tools.RegisterTopRootEvents = function (events) {
  5628. for (var index = 0; index < events.length; index++) {
  5629. var event = events[index];
  5630. window.addEventListener(event.name, event.handler, false);
  5631. try {
  5632. if (window.parent) {
  5633. window.parent.addEventListener(event.name, event.handler, false);
  5634. }
  5635. }
  5636. catch (e) {
  5637. // Silently fails...
  5638. }
  5639. }
  5640. };
  5641. Tools.UnregisterTopRootEvents = function (events) {
  5642. for (var index = 0; index < events.length; index++) {
  5643. var event = events[index];
  5644. window.removeEventListener(event.name, event.handler);
  5645. try {
  5646. if (window.parent) {
  5647. window.parent.removeEventListener(event.name, event.handler);
  5648. }
  5649. }
  5650. catch (e) {
  5651. // Silently fails...
  5652. }
  5653. }
  5654. };
  5655. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5656. if (mimeType === void 0) { mimeType = "image/png"; }
  5657. // Read the contents of the framebuffer
  5658. var numberOfChannelsByLine = width * 4;
  5659. var halfHeight = height / 2;
  5660. //Reading datas from WebGL
  5661. var data = engine.readPixels(0, 0, width, height);
  5662. //To flip image on Y axis.
  5663. for (var i = 0; i < halfHeight; i++) {
  5664. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5665. var currentCell = j + i * numberOfChannelsByLine;
  5666. var targetLine = height - i - 1;
  5667. var targetCell = j + targetLine * numberOfChannelsByLine;
  5668. var temp = data[currentCell];
  5669. data[currentCell] = data[targetCell];
  5670. data[targetCell] = temp;
  5671. }
  5672. }
  5673. // Create a 2D canvas to store the result
  5674. if (!screenshotCanvas) {
  5675. screenshotCanvas = document.createElement('canvas');
  5676. }
  5677. screenshotCanvas.width = width;
  5678. screenshotCanvas.height = height;
  5679. var context = screenshotCanvas.getContext('2d');
  5680. // Copy the pixels to a 2D canvas
  5681. var imageData = context.createImageData(width, height);
  5682. var castData = (imageData.data);
  5683. castData.set(data);
  5684. context.putImageData(imageData, 0, 0);
  5685. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5686. };
  5687. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5688. if (mimeType === void 0) { mimeType = "image/png"; }
  5689. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5690. if (successCallback) {
  5691. successCallback(base64Image);
  5692. }
  5693. else {
  5694. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5695. if (("download" in document.createElement("a"))) {
  5696. var a = window.document.createElement("a");
  5697. a.href = base64Image;
  5698. var date = new Date();
  5699. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5700. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5701. window.document.body.appendChild(a);
  5702. a.addEventListener("click", function () {
  5703. a.parentElement.removeChild(a);
  5704. });
  5705. a.click();
  5706. //Or opening a new tab with the image if it is not possible to automatically start download.
  5707. }
  5708. else {
  5709. var newWindow = window.open("");
  5710. var img = newWindow.document.createElement("img");
  5711. img.src = base64Image;
  5712. newWindow.document.body.appendChild(img);
  5713. }
  5714. }
  5715. };
  5716. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5717. if (mimeType === void 0) { mimeType = "image/png"; }
  5718. var width;
  5719. var height;
  5720. // If a precision value is specified
  5721. if (size.precision) {
  5722. width = Math.round(engine.getRenderWidth() * size.precision);
  5723. height = Math.round(width / engine.getAspectRatio(camera));
  5724. }
  5725. else if (size.width && size.height) {
  5726. width = size.width;
  5727. height = size.height;
  5728. }
  5729. else if (size.width && !size.height) {
  5730. width = size.width;
  5731. height = Math.round(width / engine.getAspectRatio(camera));
  5732. }
  5733. else if (size.height && !size.width) {
  5734. height = size.height;
  5735. width = Math.round(height * engine.getAspectRatio(camera));
  5736. }
  5737. else if (!isNaN(size)) {
  5738. height = size;
  5739. width = size;
  5740. }
  5741. else {
  5742. Tools.Error("Invalid 'size' parameter !");
  5743. return;
  5744. }
  5745. if (!screenshotCanvas) {
  5746. screenshotCanvas = document.createElement('canvas');
  5747. }
  5748. screenshotCanvas.width = width;
  5749. screenshotCanvas.height = height;
  5750. var renderContext = screenshotCanvas.getContext("2d");
  5751. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5752. var newWidth = width;
  5753. var newHeight = newWidth / ratio;
  5754. if (newHeight > height) {
  5755. newHeight = height;
  5756. newWidth = newHeight * ratio;
  5757. }
  5758. var offsetX = Math.max(0, width - newWidth) / 2;
  5759. var offsetY = Math.max(0, height - newHeight) / 2;
  5760. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5761. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5762. };
  5763. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5764. if (mimeType === void 0) { mimeType = "image/png"; }
  5765. if (samples === void 0) { samples = 1; }
  5766. var width;
  5767. var height;
  5768. //If a precision value is specified
  5769. if (size.precision) {
  5770. width = Math.round(engine.getRenderWidth() * size.precision);
  5771. height = Math.round(width / engine.getAspectRatio(camera));
  5772. size = { width: width, height: height };
  5773. }
  5774. else if (size.width && size.height) {
  5775. width = size.width;
  5776. height = size.height;
  5777. }
  5778. else if (size.width && !size.height) {
  5779. width = size.width;
  5780. height = Math.round(width / engine.getAspectRatio(camera));
  5781. size = { width: width, height: height };
  5782. }
  5783. else if (size.height && !size.width) {
  5784. height = size.height;
  5785. width = Math.round(height * engine.getAspectRatio(camera));
  5786. size = { width: width, height: height };
  5787. }
  5788. else if (!isNaN(size)) {
  5789. height = size;
  5790. width = size;
  5791. }
  5792. else {
  5793. Tools.Error("Invalid 'size' parameter !");
  5794. return;
  5795. }
  5796. var scene = camera.getScene();
  5797. var previousCamera = null;
  5798. if (scene.activeCamera !== camera) {
  5799. previousCamera = scene.activeCamera;
  5800. scene.activeCamera = camera;
  5801. }
  5802. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5803. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5804. texture.renderList = scene.meshes;
  5805. texture.samples = samples;
  5806. texture.onAfterRenderObservable.add(function () {
  5807. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5808. });
  5809. scene.incrementRenderId();
  5810. scene.resetCachedMaterial();
  5811. texture.render(true);
  5812. texture.dispose();
  5813. if (previousCamera) {
  5814. scene.activeCamera = previousCamera;
  5815. }
  5816. camera.getProjectionMatrix(true); // Force cache refresh;
  5817. };
  5818. // XHR response validator for local file scenario
  5819. Tools.ValidateXHRData = function (xhr, dataType) {
  5820. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5821. if (dataType === void 0) { dataType = 7; }
  5822. try {
  5823. if (dataType & 1) {
  5824. if (xhr.responseText && xhr.responseText.length > 0) {
  5825. return true;
  5826. }
  5827. else if (dataType === 1) {
  5828. return false;
  5829. }
  5830. }
  5831. if (dataType & 2) {
  5832. // Check header width and height since there is no "TGA" magic number
  5833. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5834. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5835. return true;
  5836. }
  5837. else if (dataType === 2) {
  5838. return false;
  5839. }
  5840. }
  5841. if (dataType & 4) {
  5842. // Check for the "DDS" magic number
  5843. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5844. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5845. return true;
  5846. }
  5847. else {
  5848. return false;
  5849. }
  5850. }
  5851. }
  5852. catch (e) {
  5853. // Global protection
  5854. }
  5855. return false;
  5856. };
  5857. /**
  5858. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5859. * Be aware Math.random() could cause collisions, but:
  5860. * "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"
  5861. */
  5862. Tools.RandomId = function () {
  5863. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5864. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5865. return v.toString(16);
  5866. });
  5867. };
  5868. Object.defineProperty(Tools, "NoneLogLevel", {
  5869. get: function () {
  5870. return Tools._NoneLogLevel;
  5871. },
  5872. enumerable: true,
  5873. configurable: true
  5874. });
  5875. Object.defineProperty(Tools, "MessageLogLevel", {
  5876. get: function () {
  5877. return Tools._MessageLogLevel;
  5878. },
  5879. enumerable: true,
  5880. configurable: true
  5881. });
  5882. Object.defineProperty(Tools, "WarningLogLevel", {
  5883. get: function () {
  5884. return Tools._WarningLogLevel;
  5885. },
  5886. enumerable: true,
  5887. configurable: true
  5888. });
  5889. Object.defineProperty(Tools, "ErrorLogLevel", {
  5890. get: function () {
  5891. return Tools._ErrorLogLevel;
  5892. },
  5893. enumerable: true,
  5894. configurable: true
  5895. });
  5896. Object.defineProperty(Tools, "AllLogLevel", {
  5897. get: function () {
  5898. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5899. },
  5900. enumerable: true,
  5901. configurable: true
  5902. });
  5903. Tools._AddLogEntry = function (entry) {
  5904. Tools._LogCache = entry + Tools._LogCache;
  5905. if (Tools.OnNewCacheEntry) {
  5906. Tools.OnNewCacheEntry(entry);
  5907. }
  5908. };
  5909. Tools._FormatMessage = function (message) {
  5910. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5911. var date = new Date();
  5912. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5913. };
  5914. Tools._LogDisabled = function (message) {
  5915. // nothing to do
  5916. };
  5917. Tools._LogEnabled = function (message) {
  5918. var formattedMessage = Tools._FormatMessage(message);
  5919. console.log("BJS - " + formattedMessage);
  5920. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5921. Tools._AddLogEntry(entry);
  5922. };
  5923. Tools._WarnDisabled = function (message) {
  5924. // nothing to do
  5925. };
  5926. Tools._WarnEnabled = function (message) {
  5927. var formattedMessage = Tools._FormatMessage(message);
  5928. console.warn("BJS - " + formattedMessage);
  5929. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5930. Tools._AddLogEntry(entry);
  5931. };
  5932. Tools._ErrorDisabled = function (message) {
  5933. // nothing to do
  5934. };
  5935. Tools._ErrorEnabled = function (message) {
  5936. Tools.errorsCount++;
  5937. var formattedMessage = Tools._FormatMessage(message);
  5938. console.error("BJS - " + formattedMessage);
  5939. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5940. Tools._AddLogEntry(entry);
  5941. };
  5942. Object.defineProperty(Tools, "LogCache", {
  5943. get: function () {
  5944. return Tools._LogCache;
  5945. },
  5946. enumerable: true,
  5947. configurable: true
  5948. });
  5949. Tools.ClearLogCache = function () {
  5950. Tools._LogCache = "";
  5951. Tools.errorsCount = 0;
  5952. };
  5953. Object.defineProperty(Tools, "LogLevels", {
  5954. set: function (level) {
  5955. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5956. Tools.Log = Tools._LogEnabled;
  5957. }
  5958. else {
  5959. Tools.Log = Tools._LogDisabled;
  5960. }
  5961. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5962. Tools.Warn = Tools._WarnEnabled;
  5963. }
  5964. else {
  5965. Tools.Warn = Tools._WarnDisabled;
  5966. }
  5967. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5968. Tools.Error = Tools._ErrorEnabled;
  5969. }
  5970. else {
  5971. Tools.Error = Tools._ErrorDisabled;
  5972. }
  5973. },
  5974. enumerable: true,
  5975. configurable: true
  5976. });
  5977. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5978. get: function () {
  5979. return Tools._PerformanceNoneLogLevel;
  5980. },
  5981. enumerable: true,
  5982. configurable: true
  5983. });
  5984. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5985. get: function () {
  5986. return Tools._PerformanceUserMarkLogLevel;
  5987. },
  5988. enumerable: true,
  5989. configurable: true
  5990. });
  5991. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5992. get: function () {
  5993. return Tools._PerformanceConsoleLogLevel;
  5994. },
  5995. enumerable: true,
  5996. configurable: true
  5997. });
  5998. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5999. set: function (level) {
  6000. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6001. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6002. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6003. return;
  6004. }
  6005. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6006. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6007. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6008. return;
  6009. }
  6010. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6011. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6012. },
  6013. enumerable: true,
  6014. configurable: true
  6015. });
  6016. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6017. };
  6018. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6019. };
  6020. Tools._StartUserMark = function (counterName, condition) {
  6021. if (condition === void 0) { condition = true; }
  6022. if (!condition || !Tools._performance.mark) {
  6023. return;
  6024. }
  6025. Tools._performance.mark(counterName + "-Begin");
  6026. };
  6027. Tools._EndUserMark = function (counterName, condition) {
  6028. if (condition === void 0) { condition = true; }
  6029. if (!condition || !Tools._performance.mark) {
  6030. return;
  6031. }
  6032. Tools._performance.mark(counterName + "-End");
  6033. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6034. };
  6035. Tools._StartPerformanceConsole = function (counterName, condition) {
  6036. if (condition === void 0) { condition = true; }
  6037. if (!condition) {
  6038. return;
  6039. }
  6040. Tools._StartUserMark(counterName, condition);
  6041. if (console.time) {
  6042. console.time(counterName);
  6043. }
  6044. };
  6045. Tools._EndPerformanceConsole = function (counterName, condition) {
  6046. if (condition === void 0) { condition = true; }
  6047. if (!condition) {
  6048. return;
  6049. }
  6050. Tools._EndUserMark(counterName, condition);
  6051. if (console.time) {
  6052. console.timeEnd(counterName);
  6053. }
  6054. };
  6055. Object.defineProperty(Tools, "Now", {
  6056. get: function () {
  6057. if (window.performance && window.performance.now) {
  6058. return window.performance.now();
  6059. }
  6060. return new Date().getTime();
  6061. },
  6062. enumerable: true,
  6063. configurable: true
  6064. });
  6065. /**
  6066. * This method will return the name of the class used to create the instance of the given object.
  6067. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6068. * @param object the object to get the class name from
  6069. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6070. */
  6071. Tools.getClassName = function (object, isType) {
  6072. if (isType === void 0) { isType = false; }
  6073. var name = null;
  6074. if (!isType && object.getClassName) {
  6075. name = object.getClassName();
  6076. }
  6077. else {
  6078. if (object instanceof Object) {
  6079. var classObj = isType ? object : Object.getPrototypeOf(object);
  6080. name = classObj.constructor["__bjsclassName__"];
  6081. }
  6082. if (!name) {
  6083. name = typeof object;
  6084. }
  6085. }
  6086. return name;
  6087. };
  6088. Tools.first = function (array, predicate) {
  6089. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6090. var el = array_1[_i];
  6091. if (predicate(el)) {
  6092. return el;
  6093. }
  6094. }
  6095. };
  6096. /**
  6097. * This method will return the name of the full name of the class, including its owning module (if any).
  6098. * 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).
  6099. * @param object the object to get the class name from
  6100. * @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.
  6101. */
  6102. Tools.getFullClassName = function (object, isType) {
  6103. if (isType === void 0) { isType = false; }
  6104. var className = null;
  6105. var moduleName = null;
  6106. if (!isType && object.getClassName) {
  6107. className = object.getClassName();
  6108. }
  6109. else {
  6110. if (object instanceof Object) {
  6111. var classObj = isType ? object : Object.getPrototypeOf(object);
  6112. className = classObj.constructor["__bjsclassName__"];
  6113. moduleName = classObj.constructor["__bjsmoduleName__"];
  6114. }
  6115. if (!className) {
  6116. className = typeof object;
  6117. }
  6118. }
  6119. if (!className) {
  6120. return null;
  6121. }
  6122. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6123. };
  6124. /**
  6125. * 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.
  6126. * @param array
  6127. */
  6128. Tools.arrayOrStringFeeder = function (array) {
  6129. return function (index) {
  6130. if (index >= array.length) {
  6131. return null;
  6132. }
  6133. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6134. if (val && val.getHashCode) {
  6135. val = val.getHashCode();
  6136. }
  6137. if (typeof val === "string") {
  6138. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6139. }
  6140. return val;
  6141. };
  6142. };
  6143. /**
  6144. * Compute the hashCode of a stream of number
  6145. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6146. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6147. * @return the hash code computed
  6148. */
  6149. Tools.hashCodeFromStream = function (feeder) {
  6150. // Based from here: http://stackoverflow.com/a/7616484/802124
  6151. var hash = 0;
  6152. var index = 0;
  6153. var chr = feeder(index++);
  6154. while (chr != null) {
  6155. hash = ((hash << 5) - hash) + chr;
  6156. hash |= 0; // Convert to 32bit integer
  6157. chr = feeder(index++);
  6158. }
  6159. return hash;
  6160. };
  6161. return Tools;
  6162. }());
  6163. Tools.BaseUrl = "";
  6164. Tools.CorsBehavior = "anonymous";
  6165. Tools.UseFallbackTexture = true;
  6166. // Used in case of a texture loading problem
  6167. 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";
  6168. // Logs
  6169. Tools._NoneLogLevel = 0;
  6170. Tools._MessageLogLevel = 1;
  6171. Tools._WarningLogLevel = 2;
  6172. Tools._ErrorLogLevel = 4;
  6173. Tools._LogCache = "";
  6174. Tools.errorsCount = 0;
  6175. Tools.Log = Tools._LogEnabled;
  6176. Tools.Warn = Tools._WarnEnabled;
  6177. Tools.Error = Tools._ErrorEnabled;
  6178. // Performances
  6179. Tools._PerformanceNoneLogLevel = 0;
  6180. Tools._PerformanceUserMarkLogLevel = 1;
  6181. Tools._PerformanceConsoleLogLevel = 2;
  6182. Tools._performance = window.performance;
  6183. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6184. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6185. BABYLON.Tools = Tools;
  6186. /**
  6187. * This class is used to track a performance counter which is number based.
  6188. * The user has access to many properties which give statistics of different nature
  6189. *
  6190. * The implementer can track two kinds of Performance Counter: time and count
  6191. * 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.
  6192. * 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.
  6193. */
  6194. var PerfCounter = (function () {
  6195. function PerfCounter() {
  6196. this._startMonitoringTime = 0;
  6197. this._min = 0;
  6198. this._max = 0;
  6199. this._average = 0;
  6200. this._lastSecAverage = 0;
  6201. this._current = 0;
  6202. this._totalValueCount = 0;
  6203. this._totalAccumulated = 0;
  6204. this._lastSecAccumulated = 0;
  6205. this._lastSecTime = 0;
  6206. this._lastSecValueCount = 0;
  6207. }
  6208. Object.defineProperty(PerfCounter.prototype, "min", {
  6209. /**
  6210. * Returns the smallest value ever
  6211. */
  6212. get: function () {
  6213. return this._min;
  6214. },
  6215. enumerable: true,
  6216. configurable: true
  6217. });
  6218. Object.defineProperty(PerfCounter.prototype, "max", {
  6219. /**
  6220. * Returns the biggest value ever
  6221. */
  6222. get: function () {
  6223. return this._max;
  6224. },
  6225. enumerable: true,
  6226. configurable: true
  6227. });
  6228. Object.defineProperty(PerfCounter.prototype, "average", {
  6229. /**
  6230. * Returns the average value since the performance counter is running
  6231. */
  6232. get: function () {
  6233. return this._average;
  6234. },
  6235. enumerable: true,
  6236. configurable: true
  6237. });
  6238. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6239. /**
  6240. * Returns the average value of the last second the counter was monitored
  6241. */
  6242. get: function () {
  6243. return this._lastSecAverage;
  6244. },
  6245. enumerable: true,
  6246. configurable: true
  6247. });
  6248. Object.defineProperty(PerfCounter.prototype, "current", {
  6249. /**
  6250. * Returns the current value
  6251. */
  6252. get: function () {
  6253. return this._current;
  6254. },
  6255. enumerable: true,
  6256. configurable: true
  6257. });
  6258. Object.defineProperty(PerfCounter.prototype, "total", {
  6259. get: function () {
  6260. return this._totalAccumulated;
  6261. },
  6262. enumerable: true,
  6263. configurable: true
  6264. });
  6265. /**
  6266. * Call this method to start monitoring a new frame.
  6267. * 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.
  6268. */
  6269. PerfCounter.prototype.fetchNewFrame = function () {
  6270. this._totalValueCount++;
  6271. this._current = 0;
  6272. this._lastSecValueCount++;
  6273. };
  6274. /**
  6275. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6276. * @param newCount the count value to add to the monitored count
  6277. * @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.
  6278. */
  6279. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6280. if (!PerfCounter.Enabled) {
  6281. return;
  6282. }
  6283. this._current += newCount;
  6284. if (fetchResult) {
  6285. this._fetchResult();
  6286. }
  6287. };
  6288. /**
  6289. * Start monitoring this performance counter
  6290. */
  6291. PerfCounter.prototype.beginMonitoring = function () {
  6292. if (!PerfCounter.Enabled) {
  6293. return;
  6294. }
  6295. this._startMonitoringTime = Tools.Now;
  6296. };
  6297. /**
  6298. * Compute the time lapsed since the previous beginMonitoring() call.
  6299. * @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
  6300. */
  6301. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6302. if (newFrame === void 0) { newFrame = true; }
  6303. if (!PerfCounter.Enabled) {
  6304. return;
  6305. }
  6306. if (newFrame) {
  6307. this.fetchNewFrame();
  6308. }
  6309. var currentTime = Tools.Now;
  6310. this._current = currentTime - this._startMonitoringTime;
  6311. if (newFrame) {
  6312. this._fetchResult();
  6313. }
  6314. };
  6315. PerfCounter.prototype._fetchResult = function () {
  6316. this._totalAccumulated += this._current;
  6317. this._lastSecAccumulated += this._current;
  6318. // Min/Max update
  6319. this._min = Math.min(this._min, this._current);
  6320. this._max = Math.max(this._max, this._current);
  6321. this._average = this._totalAccumulated / this._totalValueCount;
  6322. // Reset last sec?
  6323. var now = Tools.Now;
  6324. if ((now - this._lastSecTime) > 1000) {
  6325. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6326. this._lastSecTime = now;
  6327. this._lastSecAccumulated = 0;
  6328. this._lastSecValueCount = 0;
  6329. }
  6330. };
  6331. return PerfCounter;
  6332. }());
  6333. PerfCounter.Enabled = true;
  6334. BABYLON.PerfCounter = PerfCounter;
  6335. /**
  6336. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6337. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6338. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6339. * @param name The name of the class, case should be preserved
  6340. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6341. */
  6342. function className(name, module) {
  6343. return function (target) {
  6344. target["__bjsclassName__"] = name;
  6345. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6346. };
  6347. }
  6348. BABYLON.className = className;
  6349. /**
  6350. * An implementation of a loop for asynchronous functions.
  6351. */
  6352. var AsyncLoop = (function () {
  6353. /**
  6354. * Constroctor.
  6355. * @param iterations the number of iterations.
  6356. * @param _fn the function to run each iteration
  6357. * @param _successCallback the callback that will be called upon succesful execution
  6358. * @param offset starting offset.
  6359. */
  6360. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6361. if (offset === void 0) { offset = 0; }
  6362. this.iterations = iterations;
  6363. this._fn = _fn;
  6364. this._successCallback = _successCallback;
  6365. this.index = offset - 1;
  6366. this._done = false;
  6367. }
  6368. /**
  6369. * Execute the next iteration. Must be called after the last iteration was finished.
  6370. */
  6371. AsyncLoop.prototype.executeNext = function () {
  6372. if (!this._done) {
  6373. if (this.index + 1 < this.iterations) {
  6374. ++this.index;
  6375. this._fn(this);
  6376. }
  6377. else {
  6378. this.breakLoop();
  6379. }
  6380. }
  6381. };
  6382. /**
  6383. * Break the loop and run the success callback.
  6384. */
  6385. AsyncLoop.prototype.breakLoop = function () {
  6386. this._done = true;
  6387. this._successCallback();
  6388. };
  6389. /**
  6390. * Helper function
  6391. */
  6392. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6393. if (offset === void 0) { offset = 0; }
  6394. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6395. loop.executeNext();
  6396. return loop;
  6397. };
  6398. /**
  6399. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6400. * @param iterations total number of iterations
  6401. * @param syncedIterations number of synchronous iterations in each async iteration.
  6402. * @param fn the function to call each iteration.
  6403. * @param callback a success call back that will be called when iterating stops.
  6404. * @param breakFunction a break condition (optional)
  6405. * @param timeout timeout settings for the setTimeout function. default - 0.
  6406. * @constructor
  6407. */
  6408. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6409. if (timeout === void 0) { timeout = 0; }
  6410. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6411. if (breakFunction && breakFunction())
  6412. loop.breakLoop();
  6413. else {
  6414. setTimeout(function () {
  6415. for (var i = 0; i < syncedIterations; ++i) {
  6416. var iteration = (loop.index * syncedIterations) + i;
  6417. if (iteration >= iterations)
  6418. break;
  6419. fn(iteration);
  6420. if (breakFunction && breakFunction()) {
  6421. loop.breakLoop();
  6422. break;
  6423. }
  6424. }
  6425. loop.executeNext();
  6426. }, timeout);
  6427. }
  6428. }, callback);
  6429. };
  6430. return AsyncLoop;
  6431. }());
  6432. BABYLON.AsyncLoop = AsyncLoop;
  6433. })(BABYLON || (BABYLON = {}));
  6434. //# sourceMappingURL=babylon.tools.js.map
  6435. var BABYLON;
  6436. (function (BABYLON) {
  6437. var Internals;
  6438. (function (Internals) {
  6439. var _AlphaState = (function () {
  6440. /**
  6441. * Initializes the state.
  6442. */
  6443. function _AlphaState() {
  6444. this._isAlphaBlendDirty = false;
  6445. this._isBlendFunctionParametersDirty = false;
  6446. this._alphaBlend = false;
  6447. this._blendFunctionParameters = new Array(4);
  6448. this.reset();
  6449. }
  6450. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6451. get: function () {
  6452. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6453. },
  6454. enumerable: true,
  6455. configurable: true
  6456. });
  6457. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6458. get: function () {
  6459. return this._alphaBlend;
  6460. },
  6461. set: function (value) {
  6462. if (this._alphaBlend === value) {
  6463. return;
  6464. }
  6465. this._alphaBlend = value;
  6466. this._isAlphaBlendDirty = true;
  6467. },
  6468. enumerable: true,
  6469. configurable: true
  6470. });
  6471. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6472. if (this._blendFunctionParameters[0] === value0 &&
  6473. this._blendFunctionParameters[1] === value1 &&
  6474. this._blendFunctionParameters[2] === value2 &&
  6475. this._blendFunctionParameters[3] === value3) {
  6476. return;
  6477. }
  6478. this._blendFunctionParameters[0] = value0;
  6479. this._blendFunctionParameters[1] = value1;
  6480. this._blendFunctionParameters[2] = value2;
  6481. this._blendFunctionParameters[3] = value3;
  6482. this._isBlendFunctionParametersDirty = true;
  6483. };
  6484. _AlphaState.prototype.reset = function () {
  6485. this._alphaBlend = false;
  6486. this._blendFunctionParameters[0] = null;
  6487. this._blendFunctionParameters[1] = null;
  6488. this._blendFunctionParameters[2] = null;
  6489. this._blendFunctionParameters[3] = null;
  6490. this._isAlphaBlendDirty = true;
  6491. this._isBlendFunctionParametersDirty = false;
  6492. };
  6493. _AlphaState.prototype.apply = function (gl) {
  6494. if (!this.isDirty) {
  6495. return;
  6496. }
  6497. // Alpha blend
  6498. if (this._isAlphaBlendDirty) {
  6499. if (this._alphaBlend) {
  6500. gl.enable(gl.BLEND);
  6501. }
  6502. else {
  6503. gl.disable(gl.BLEND);
  6504. }
  6505. this._isAlphaBlendDirty = false;
  6506. }
  6507. // Alpha function
  6508. if (this._isBlendFunctionParametersDirty) {
  6509. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6510. this._isBlendFunctionParametersDirty = false;
  6511. }
  6512. };
  6513. return _AlphaState;
  6514. }());
  6515. Internals._AlphaState = _AlphaState;
  6516. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6517. })(BABYLON || (BABYLON = {}));
  6518. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6519. var BABYLON;
  6520. (function (BABYLON) {
  6521. var Internals;
  6522. (function (Internals) {
  6523. var _DepthCullingState = (function () {
  6524. /**
  6525. * Initializes the state.
  6526. */
  6527. function _DepthCullingState() {
  6528. this._isDepthTestDirty = false;
  6529. this._isDepthMaskDirty = false;
  6530. this._isDepthFuncDirty = false;
  6531. this._isCullFaceDirty = false;
  6532. this._isCullDirty = false;
  6533. this._isZOffsetDirty = false;
  6534. this.reset();
  6535. }
  6536. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6537. get: function () {
  6538. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6539. },
  6540. enumerable: true,
  6541. configurable: true
  6542. });
  6543. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6544. get: function () {
  6545. return this._zOffset;
  6546. },
  6547. set: function (value) {
  6548. if (this._zOffset === value) {
  6549. return;
  6550. }
  6551. this._zOffset = value;
  6552. this._isZOffsetDirty = true;
  6553. },
  6554. enumerable: true,
  6555. configurable: true
  6556. });
  6557. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6558. get: function () {
  6559. return this._cullFace;
  6560. },
  6561. set: function (value) {
  6562. if (this._cullFace === value) {
  6563. return;
  6564. }
  6565. this._cullFace = value;
  6566. this._isCullFaceDirty = true;
  6567. },
  6568. enumerable: true,
  6569. configurable: true
  6570. });
  6571. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6572. get: function () {
  6573. return this._cull;
  6574. },
  6575. set: function (value) {
  6576. if (this._cull === value) {
  6577. return;
  6578. }
  6579. this._cull = value;
  6580. this._isCullDirty = true;
  6581. },
  6582. enumerable: true,
  6583. configurable: true
  6584. });
  6585. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6586. get: function () {
  6587. return this._depthFunc;
  6588. },
  6589. set: function (value) {
  6590. if (this._depthFunc === value) {
  6591. return;
  6592. }
  6593. this._depthFunc = value;
  6594. this._isDepthFuncDirty = true;
  6595. },
  6596. enumerable: true,
  6597. configurable: true
  6598. });
  6599. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6600. get: function () {
  6601. return this._depthMask;
  6602. },
  6603. set: function (value) {
  6604. if (this._depthMask === value) {
  6605. return;
  6606. }
  6607. this._depthMask = value;
  6608. this._isDepthMaskDirty = true;
  6609. },
  6610. enumerable: true,
  6611. configurable: true
  6612. });
  6613. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6614. get: function () {
  6615. return this._depthTest;
  6616. },
  6617. set: function (value) {
  6618. if (this._depthTest === value) {
  6619. return;
  6620. }
  6621. this._depthTest = value;
  6622. this._isDepthTestDirty = true;
  6623. },
  6624. enumerable: true,
  6625. configurable: true
  6626. });
  6627. _DepthCullingState.prototype.reset = function () {
  6628. this._depthMask = true;
  6629. this._depthTest = true;
  6630. this._depthFunc = null;
  6631. this._cullFace = null;
  6632. this._cull = null;
  6633. this._zOffset = 0;
  6634. this._isDepthTestDirty = true;
  6635. this._isDepthMaskDirty = true;
  6636. this._isDepthFuncDirty = false;
  6637. this._isCullFaceDirty = false;
  6638. this._isCullDirty = false;
  6639. this._isZOffsetDirty = false;
  6640. };
  6641. _DepthCullingState.prototype.apply = function (gl) {
  6642. if (!this.isDirty) {
  6643. return;
  6644. }
  6645. // Cull
  6646. if (this._isCullDirty) {
  6647. if (this.cull) {
  6648. gl.enable(gl.CULL_FACE);
  6649. }
  6650. else {
  6651. gl.disable(gl.CULL_FACE);
  6652. }
  6653. this._isCullDirty = false;
  6654. }
  6655. // Cull face
  6656. if (this._isCullFaceDirty) {
  6657. gl.cullFace(this.cullFace);
  6658. this._isCullFaceDirty = false;
  6659. }
  6660. // Depth mask
  6661. if (this._isDepthMaskDirty) {
  6662. gl.depthMask(this.depthMask);
  6663. this._isDepthMaskDirty = false;
  6664. }
  6665. // Depth test
  6666. if (this._isDepthTestDirty) {
  6667. if (this.depthTest) {
  6668. gl.enable(gl.DEPTH_TEST);
  6669. }
  6670. else {
  6671. gl.disable(gl.DEPTH_TEST);
  6672. }
  6673. this._isDepthTestDirty = false;
  6674. }
  6675. // Depth func
  6676. if (this._isDepthFuncDirty) {
  6677. gl.depthFunc(this.depthFunc);
  6678. this._isDepthFuncDirty = false;
  6679. }
  6680. // zOffset
  6681. if (this._isZOffsetDirty) {
  6682. if (this.zOffset) {
  6683. gl.enable(gl.POLYGON_OFFSET_FILL);
  6684. gl.polygonOffset(this.zOffset, 0);
  6685. }
  6686. else {
  6687. gl.disable(gl.POLYGON_OFFSET_FILL);
  6688. }
  6689. this._isZOffsetDirty = false;
  6690. }
  6691. };
  6692. return _DepthCullingState;
  6693. }());
  6694. Internals._DepthCullingState = _DepthCullingState;
  6695. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6696. })(BABYLON || (BABYLON = {}));
  6697. //# sourceMappingURL=babylon.depthCullingState.js.map
  6698. var BABYLON;
  6699. (function (BABYLON) {
  6700. var Internals;
  6701. (function (Internals) {
  6702. var _StencilState = (function () {
  6703. function _StencilState() {
  6704. this._isStencilTestDirty = false;
  6705. this._isStencilMaskDirty = false;
  6706. this._isStencilFuncDirty = false;
  6707. this._isStencilOpDirty = false;
  6708. this.reset();
  6709. }
  6710. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6711. get: function () {
  6712. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6713. },
  6714. enumerable: true,
  6715. configurable: true
  6716. });
  6717. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6718. get: function () {
  6719. return this._stencilFunc;
  6720. },
  6721. set: function (value) {
  6722. if (this._stencilFunc === value) {
  6723. return;
  6724. }
  6725. this._stencilFunc = value;
  6726. this._isStencilFuncDirty = true;
  6727. },
  6728. enumerable: true,
  6729. configurable: true
  6730. });
  6731. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6732. get: function () {
  6733. return this._stencilFuncRef;
  6734. },
  6735. set: function (value) {
  6736. if (this._stencilFuncRef === value) {
  6737. return;
  6738. }
  6739. this._stencilFuncRef = value;
  6740. this._isStencilFuncDirty = true;
  6741. },
  6742. enumerable: true,
  6743. configurable: true
  6744. });
  6745. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6746. get: function () {
  6747. return this._stencilFuncMask;
  6748. },
  6749. set: function (value) {
  6750. if (this._stencilFuncMask === value) {
  6751. return;
  6752. }
  6753. this._stencilFuncMask = value;
  6754. this._isStencilFuncDirty = true;
  6755. },
  6756. enumerable: true,
  6757. configurable: true
  6758. });
  6759. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6760. get: function () {
  6761. return this._stencilOpStencilFail;
  6762. },
  6763. set: function (value) {
  6764. if (this._stencilOpStencilFail === value) {
  6765. return;
  6766. }
  6767. this._stencilOpStencilFail = value;
  6768. this._isStencilOpDirty = true;
  6769. },
  6770. enumerable: true,
  6771. configurable: true
  6772. });
  6773. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6774. get: function () {
  6775. return this._stencilOpDepthFail;
  6776. },
  6777. set: function (value) {
  6778. if (this._stencilOpDepthFail === value) {
  6779. return;
  6780. }
  6781. this._stencilOpDepthFail = value;
  6782. this._isStencilOpDirty = true;
  6783. },
  6784. enumerable: true,
  6785. configurable: true
  6786. });
  6787. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6788. get: function () {
  6789. return this._stencilOpStencilDepthPass;
  6790. },
  6791. set: function (value) {
  6792. if (this._stencilOpStencilDepthPass === value) {
  6793. return;
  6794. }
  6795. this._stencilOpStencilDepthPass = value;
  6796. this._isStencilOpDirty = true;
  6797. },
  6798. enumerable: true,
  6799. configurable: true
  6800. });
  6801. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6802. get: function () {
  6803. return this._stencilMask;
  6804. },
  6805. set: function (value) {
  6806. if (this._stencilMask === value) {
  6807. return;
  6808. }
  6809. this._stencilMask = value;
  6810. this._isStencilMaskDirty = true;
  6811. },
  6812. enumerable: true,
  6813. configurable: true
  6814. });
  6815. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6816. get: function () {
  6817. return this._stencilTest;
  6818. },
  6819. set: function (value) {
  6820. if (this._stencilTest === value) {
  6821. return;
  6822. }
  6823. this._stencilTest = value;
  6824. this._isStencilTestDirty = true;
  6825. },
  6826. enumerable: true,
  6827. configurable: true
  6828. });
  6829. _StencilState.prototype.reset = function () {
  6830. this._stencilTest = false;
  6831. this._stencilMask = 0xFF;
  6832. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6833. this._stencilFuncRef = 1;
  6834. this._stencilFuncMask = 0xFF;
  6835. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6836. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6837. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6838. this._isStencilTestDirty = true;
  6839. this._isStencilMaskDirty = true;
  6840. this._isStencilFuncDirty = true;
  6841. this._isStencilOpDirty = true;
  6842. };
  6843. _StencilState.prototype.apply = function (gl) {
  6844. if (!this.isDirty) {
  6845. return;
  6846. }
  6847. // Stencil test
  6848. if (this._isStencilTestDirty) {
  6849. if (this.stencilTest) {
  6850. gl.enable(gl.STENCIL_TEST);
  6851. }
  6852. else {
  6853. gl.disable(gl.STENCIL_TEST);
  6854. }
  6855. this._isStencilTestDirty = false;
  6856. }
  6857. // Stencil mask
  6858. if (this._isStencilMaskDirty) {
  6859. gl.stencilMask(this.stencilMask);
  6860. this._isStencilMaskDirty = false;
  6861. }
  6862. // Stencil func
  6863. if (this._isStencilFuncDirty) {
  6864. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6865. this._isStencilFuncDirty = false;
  6866. }
  6867. // Stencil op
  6868. if (this._isStencilOpDirty) {
  6869. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6870. this._isStencilOpDirty = false;
  6871. }
  6872. };
  6873. return _StencilState;
  6874. }());
  6875. Internals._StencilState = _StencilState;
  6876. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6877. })(BABYLON || (BABYLON = {}));
  6878. //# sourceMappingURL=babylon.stencilState.js.map
  6879. var BABYLON;
  6880. (function (BABYLON) {
  6881. var compileShader = function (gl, source, type, defines, shaderVersion) {
  6882. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6883. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  6884. gl.compileShader(shader);
  6885. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6886. throw new Error(gl.getShaderInfoLog(shader));
  6887. }
  6888. return shader;
  6889. };
  6890. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6891. var magFilter = gl.NEAREST;
  6892. var minFilter = gl.NEAREST;
  6893. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6894. magFilter = gl.LINEAR;
  6895. if (generateMipMaps) {
  6896. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6897. }
  6898. else {
  6899. minFilter = gl.LINEAR;
  6900. }
  6901. }
  6902. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6903. magFilter = gl.LINEAR;
  6904. if (generateMipMaps) {
  6905. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6906. }
  6907. else {
  6908. minFilter = gl.LINEAR;
  6909. }
  6910. }
  6911. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6912. magFilter = gl.NEAREST;
  6913. if (generateMipMaps) {
  6914. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6915. }
  6916. else {
  6917. minFilter = gl.NEAREST;
  6918. }
  6919. }
  6920. return {
  6921. min: minFilter,
  6922. mag: magFilter
  6923. };
  6924. };
  6925. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6926. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6927. var engine = scene.getEngine();
  6928. if (!engine) {
  6929. return;
  6930. }
  6931. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6932. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6933. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6934. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6935. texture._baseWidth = width;
  6936. texture._baseHeight = height;
  6937. texture._width = potWidth;
  6938. texture._height = potHeight;
  6939. texture.isReady = true;
  6940. processFunction(potWidth, potHeight);
  6941. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6942. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6943. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6944. if (!noMipmap && !isCompressed) {
  6945. gl.generateMipmap(gl.TEXTURE_2D);
  6946. }
  6947. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6948. engine.resetTextureCache();
  6949. scene._removePendingData(texture);
  6950. texture.onLoadedCallbacks.forEach(function (callback) {
  6951. callback();
  6952. });
  6953. texture.onLoadedCallbacks = [];
  6954. };
  6955. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6956. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6957. var img;
  6958. var onload = function () {
  6959. loadedImages[index] = img;
  6960. loadedImages._internalCount++;
  6961. scene._removePendingData(img);
  6962. if (loadedImages._internalCount === 6) {
  6963. onfinish(loadedImages);
  6964. }
  6965. };
  6966. var onerror = function () {
  6967. scene._removePendingData(img);
  6968. if (onErrorCallBack) {
  6969. onErrorCallBack();
  6970. }
  6971. };
  6972. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6973. scene._addPendingData(img);
  6974. };
  6975. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6976. if (onError === void 0) { onError = null; }
  6977. var loadedImages = [];
  6978. loadedImages._internalCount = 0;
  6979. for (var index = 0; index < 6; index++) {
  6980. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6981. }
  6982. };
  6983. var InstancingAttributeInfo = (function () {
  6984. function InstancingAttributeInfo() {
  6985. }
  6986. return InstancingAttributeInfo;
  6987. }());
  6988. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6989. var EngineCapabilities = (function () {
  6990. function EngineCapabilities() {
  6991. }
  6992. return EngineCapabilities;
  6993. }());
  6994. BABYLON.EngineCapabilities = EngineCapabilities;
  6995. /**
  6996. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6997. */
  6998. var Engine = (function () {
  6999. /**
  7000. * @constructor
  7001. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  7002. * @param {boolean} [antialias] - enable antialias
  7003. * @param options - further options to be sent to the getContext function
  7004. */
  7005. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  7006. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7007. var _this = this;
  7008. // Public members
  7009. this.isFullscreen = false;
  7010. this.isPointerLock = false;
  7011. this.cullBackFaces = true;
  7012. this.renderEvenInBackground = true;
  7013. this.preventCacheWipeBetweenFrames = false;
  7014. // To enable/disable IDB support and avoid XHR on .manifest
  7015. this.enableOfflineSupport = BABYLON.Database;
  7016. this.scenes = new Array();
  7017. // Observables
  7018. /**
  7019. * Observable event triggered each time the rendering canvas is resized
  7020. */
  7021. this.onResizeObservable = new BABYLON.Observable();
  7022. this._windowIsBackground = false;
  7023. this._webGLVersion = 1.0;
  7024. this._badOS = false;
  7025. this._drawCalls = new BABYLON.PerfCounter();
  7026. this._renderingQueueLaunched = false;
  7027. this._activeRenderLoops = [];
  7028. // FPS
  7029. this.fpsRange = 60;
  7030. this.previousFramesDuration = [];
  7031. this.fps = 60;
  7032. this.deltaTime = 0;
  7033. // States
  7034. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7035. this._stencilState = new BABYLON.Internals._StencilState();
  7036. this._alphaState = new BABYLON.Internals._AlphaState();
  7037. this._alphaMode = Engine.ALPHA_DISABLE;
  7038. // Cache
  7039. this._loadedTexturesCache = new Array();
  7040. this._maxTextureChannels = 16;
  7041. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7042. this._compiledEffects = {};
  7043. this._vertexAttribArraysEnabled = [];
  7044. this._uintIndicesCurrentlySet = false;
  7045. this._currentBoundBuffer = new Array();
  7046. this._currentBufferPointers = [];
  7047. this._currentInstanceLocations = new Array();
  7048. this._currentInstanceBuffers = new Array();
  7049. this._vaoRecordInProgress = false;
  7050. this._mustWipeVertexAttributes = false;
  7051. // Hardware supported Compressed Textures
  7052. this._texturesSupported = new Array();
  7053. this._onVRFullScreenTriggered = function () {
  7054. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7055. //get the old size before we change
  7056. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7057. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7058. //get the width and height, change the render size
  7059. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7060. var width, height;
  7061. _this.setHardwareScalingLevel(1);
  7062. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7063. }
  7064. else {
  7065. //When the specs are implemented, need to uncomment this.
  7066. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7067. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7068. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7069. _this._vrDisplayEnabled = undefined;
  7070. }
  7071. };
  7072. this._renderingCanvas = canvas;
  7073. Engine.Instances.push(this);
  7074. options = options || {};
  7075. if (antialias != null) {
  7076. options.antialias = antialias;
  7077. }
  7078. if (options.preserveDrawingBuffer === undefined) {
  7079. options.preserveDrawingBuffer = false;
  7080. }
  7081. if (options.audioEngine === undefined) {
  7082. options.audioEngine = true;
  7083. }
  7084. if (options.stencil === undefined) {
  7085. options.stencil = true;
  7086. }
  7087. // GL
  7088. if (!options.disableWebGL2Support) {
  7089. try {
  7090. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7091. if (this._gl) {
  7092. this._webGLVersion = 2.0;
  7093. }
  7094. }
  7095. catch (e) {
  7096. // Do nothing
  7097. }
  7098. }
  7099. if (!this._gl) {
  7100. if (!canvas) {
  7101. throw new Error("The provided canvas is null or undefined.");
  7102. }
  7103. try {
  7104. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7105. }
  7106. catch (e) {
  7107. throw new Error("WebGL not supported");
  7108. }
  7109. }
  7110. if (!this._gl) {
  7111. throw new Error("WebGL not supported");
  7112. }
  7113. this._onBlur = function () {
  7114. _this._windowIsBackground = true;
  7115. };
  7116. this._onFocus = function () {
  7117. _this._windowIsBackground = false;
  7118. };
  7119. window.addEventListener("blur", this._onBlur);
  7120. window.addEventListener("focus", this._onFocus);
  7121. // Viewport
  7122. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7123. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7124. this.resize();
  7125. // Caps
  7126. this._isStencilEnable = options.stencil;
  7127. this._caps = new EngineCapabilities();
  7128. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7129. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7130. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7131. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7132. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7133. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7134. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7135. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7136. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7137. // Infos
  7138. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7139. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7140. if (rendererInfo != null) {
  7141. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7142. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7143. }
  7144. if (!this._glVendor) {
  7145. this._glVendor = "Unknown vendor";
  7146. }
  7147. if (!this._glRenderer) {
  7148. this._glRenderer = "Unknown renderer";
  7149. }
  7150. // Extensions
  7151. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7152. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7153. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7154. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7155. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7156. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7157. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7158. 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');
  7159. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7160. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7161. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7162. this._caps.highPrecisionShaderSupported = true;
  7163. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7164. // Checks if some of the format renders first to allow the use of webgl inspector.
  7165. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7166. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7167. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7168. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7169. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7170. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7171. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7172. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7173. // Vertex array object
  7174. if (this._webGLVersion > 1) {
  7175. this._caps.vertexArrayObject = true;
  7176. }
  7177. else {
  7178. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7179. if (vertexArrayObjectExtension != null) {
  7180. this._caps.vertexArrayObject = true;
  7181. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7182. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7183. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7184. }
  7185. else {
  7186. this._caps.vertexArrayObject = false;
  7187. }
  7188. }
  7189. // Instances count
  7190. if (this._webGLVersion > 1) {
  7191. this._caps.instancedArrays = true;
  7192. }
  7193. else {
  7194. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7195. if (instanceExtension != null) {
  7196. this._caps.instancedArrays = true;
  7197. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7198. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7199. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7200. }
  7201. else {
  7202. this._caps.instancedArrays = false;
  7203. }
  7204. }
  7205. // Intelligently add supported compressed formats in order to check for.
  7206. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7207. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7208. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7209. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7210. if (this._caps.astc)
  7211. this.texturesSupported.push('-astc.ktx');
  7212. if (this._caps.s3tc)
  7213. this.texturesSupported.push('-dxt.ktx');
  7214. if (this._caps.pvrtc)
  7215. this.texturesSupported.push('-pvrtc.ktx');
  7216. if (this._caps.etc2)
  7217. this.texturesSupported.push('-etc2.ktx');
  7218. if (this._caps.etc1)
  7219. this.texturesSupported.push('-etc1.ktx');
  7220. if (this._gl.getShaderPrecisionFormat) {
  7221. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7222. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7223. }
  7224. // Depth buffer
  7225. this.setDepthBuffer(true);
  7226. this.setDepthFunctionToLessOrEqual();
  7227. this.setDepthWrite(true);
  7228. // Fullscreen
  7229. this._onFullscreenChange = function () {
  7230. if (document.fullscreen !== undefined) {
  7231. _this.isFullscreen = document.fullscreen;
  7232. }
  7233. else if (document.mozFullScreen !== undefined) {
  7234. _this.isFullscreen = document.mozFullScreen;
  7235. }
  7236. else if (document.webkitIsFullScreen !== undefined) {
  7237. _this.isFullscreen = document.webkitIsFullScreen;
  7238. }
  7239. else if (document.msIsFullScreen !== undefined) {
  7240. _this.isFullscreen = document.msIsFullScreen;
  7241. }
  7242. // Pointer lock
  7243. if (_this.isFullscreen && _this._pointerLockRequested) {
  7244. canvas.requestPointerLock = canvas.requestPointerLock ||
  7245. canvas.msRequestPointerLock ||
  7246. canvas.mozRequestPointerLock ||
  7247. canvas.webkitRequestPointerLock;
  7248. if (canvas.requestPointerLock) {
  7249. canvas.requestPointerLock();
  7250. }
  7251. }
  7252. };
  7253. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7254. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7255. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7256. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7257. // Pointer lock
  7258. this._onPointerLockChange = function () {
  7259. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7260. document.webkitPointerLockElement === canvas ||
  7261. document.msPointerLockElement === canvas ||
  7262. document.pointerLockElement === canvas);
  7263. };
  7264. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7265. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7266. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7267. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7268. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7269. Engine.audioEngine = new BABYLON.AudioEngine();
  7270. }
  7271. //Load WebVR Devices
  7272. if (options.autoEnableWebVR) {
  7273. this.initWebVR();
  7274. }
  7275. //Detect if we are running on a faulty buggy OS.
  7276. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7277. //ua sniffing is the tool of the devil.
  7278. this._badOS = regexp.test(navigator.userAgent);
  7279. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7280. }
  7281. Object.defineProperty(Engine, "LastCreatedEngine", {
  7282. get: function () {
  7283. if (Engine.Instances.length === 0) {
  7284. return null;
  7285. }
  7286. return Engine.Instances[Engine.Instances.length - 1];
  7287. },
  7288. enumerable: true,
  7289. configurable: true
  7290. });
  7291. Object.defineProperty(Engine, "LastCreatedScene", {
  7292. get: function () {
  7293. var lastCreatedEngine = Engine.LastCreatedEngine;
  7294. if (!lastCreatedEngine) {
  7295. return null;
  7296. }
  7297. if (lastCreatedEngine.scenes.length === 0) {
  7298. return null;
  7299. }
  7300. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7301. },
  7302. enumerable: true,
  7303. configurable: true
  7304. });
  7305. /**
  7306. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7307. */
  7308. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7309. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7310. var engine = Engine.Instances[engineIndex];
  7311. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7312. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7313. }
  7314. }
  7315. };
  7316. Object.defineProperty(Engine, "NEVER", {
  7317. get: function () {
  7318. return Engine._NEVER;
  7319. },
  7320. enumerable: true,
  7321. configurable: true
  7322. });
  7323. Object.defineProperty(Engine, "ALWAYS", {
  7324. get: function () {
  7325. return Engine._ALWAYS;
  7326. },
  7327. enumerable: true,
  7328. configurable: true
  7329. });
  7330. Object.defineProperty(Engine, "LESS", {
  7331. get: function () {
  7332. return Engine._LESS;
  7333. },
  7334. enumerable: true,
  7335. configurable: true
  7336. });
  7337. Object.defineProperty(Engine, "EQUAL", {
  7338. get: function () {
  7339. return Engine._EQUAL;
  7340. },
  7341. enumerable: true,
  7342. configurable: true
  7343. });
  7344. Object.defineProperty(Engine, "LEQUAL", {
  7345. get: function () {
  7346. return Engine._LEQUAL;
  7347. },
  7348. enumerable: true,
  7349. configurable: true
  7350. });
  7351. Object.defineProperty(Engine, "GREATER", {
  7352. get: function () {
  7353. return Engine._GREATER;
  7354. },
  7355. enumerable: true,
  7356. configurable: true
  7357. });
  7358. Object.defineProperty(Engine, "GEQUAL", {
  7359. get: function () {
  7360. return Engine._GEQUAL;
  7361. },
  7362. enumerable: true,
  7363. configurable: true
  7364. });
  7365. Object.defineProperty(Engine, "NOTEQUAL", {
  7366. get: function () {
  7367. return Engine._NOTEQUAL;
  7368. },
  7369. enumerable: true,
  7370. configurable: true
  7371. });
  7372. Object.defineProperty(Engine, "KEEP", {
  7373. get: function () {
  7374. return Engine._KEEP;
  7375. },
  7376. enumerable: true,
  7377. configurable: true
  7378. });
  7379. Object.defineProperty(Engine, "REPLACE", {
  7380. get: function () {
  7381. return Engine._REPLACE;
  7382. },
  7383. enumerable: true,
  7384. configurable: true
  7385. });
  7386. Object.defineProperty(Engine, "INCR", {
  7387. get: function () {
  7388. return Engine._INCR;
  7389. },
  7390. enumerable: true,
  7391. configurable: true
  7392. });
  7393. Object.defineProperty(Engine, "DECR", {
  7394. get: function () {
  7395. return Engine._DECR;
  7396. },
  7397. enumerable: true,
  7398. configurable: true
  7399. });
  7400. Object.defineProperty(Engine, "INVERT", {
  7401. get: function () {
  7402. return Engine._INVERT;
  7403. },
  7404. enumerable: true,
  7405. configurable: true
  7406. });
  7407. Object.defineProperty(Engine, "INCR_WRAP", {
  7408. get: function () {
  7409. return Engine._INCR_WRAP;
  7410. },
  7411. enumerable: true,
  7412. configurable: true
  7413. });
  7414. Object.defineProperty(Engine, "DECR_WRAP", {
  7415. get: function () {
  7416. return Engine._DECR_WRAP;
  7417. },
  7418. enumerable: true,
  7419. configurable: true
  7420. });
  7421. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7422. get: function () {
  7423. return Engine._ALPHA_DISABLE;
  7424. },
  7425. enumerable: true,
  7426. configurable: true
  7427. });
  7428. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7429. get: function () {
  7430. return Engine._ALPHA_ONEONE;
  7431. },
  7432. enumerable: true,
  7433. configurable: true
  7434. });
  7435. Object.defineProperty(Engine, "ALPHA_ADD", {
  7436. get: function () {
  7437. return Engine._ALPHA_ADD;
  7438. },
  7439. enumerable: true,
  7440. configurable: true
  7441. });
  7442. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7443. get: function () {
  7444. return Engine._ALPHA_COMBINE;
  7445. },
  7446. enumerable: true,
  7447. configurable: true
  7448. });
  7449. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7450. get: function () {
  7451. return Engine._ALPHA_SUBTRACT;
  7452. },
  7453. enumerable: true,
  7454. configurable: true
  7455. });
  7456. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7457. get: function () {
  7458. return Engine._ALPHA_MULTIPLY;
  7459. },
  7460. enumerable: true,
  7461. configurable: true
  7462. });
  7463. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7464. get: function () {
  7465. return Engine._ALPHA_MAXIMIZED;
  7466. },
  7467. enumerable: true,
  7468. configurable: true
  7469. });
  7470. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7471. get: function () {
  7472. return Engine._ALPHA_PREMULTIPLIED;
  7473. },
  7474. enumerable: true,
  7475. configurable: true
  7476. });
  7477. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7478. get: function () {
  7479. return Engine._DELAYLOADSTATE_NONE;
  7480. },
  7481. enumerable: true,
  7482. configurable: true
  7483. });
  7484. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7485. get: function () {
  7486. return Engine._DELAYLOADSTATE_LOADED;
  7487. },
  7488. enumerable: true,
  7489. configurable: true
  7490. });
  7491. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7492. get: function () {
  7493. return Engine._DELAYLOADSTATE_LOADING;
  7494. },
  7495. enumerable: true,
  7496. configurable: true
  7497. });
  7498. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7499. get: function () {
  7500. return Engine._DELAYLOADSTATE_NOTLOADED;
  7501. },
  7502. enumerable: true,
  7503. configurable: true
  7504. });
  7505. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7506. get: function () {
  7507. return Engine._TEXTUREFORMAT_ALPHA;
  7508. },
  7509. enumerable: true,
  7510. configurable: true
  7511. });
  7512. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7513. get: function () {
  7514. return Engine._TEXTUREFORMAT_LUMINANCE;
  7515. },
  7516. enumerable: true,
  7517. configurable: true
  7518. });
  7519. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7520. get: function () {
  7521. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7522. },
  7523. enumerable: true,
  7524. configurable: true
  7525. });
  7526. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7527. get: function () {
  7528. return Engine._TEXTUREFORMAT_RGB;
  7529. },
  7530. enumerable: true,
  7531. configurable: true
  7532. });
  7533. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7534. get: function () {
  7535. return Engine._TEXTUREFORMAT_RGBA;
  7536. },
  7537. enumerable: true,
  7538. configurable: true
  7539. });
  7540. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7541. get: function () {
  7542. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7543. },
  7544. enumerable: true,
  7545. configurable: true
  7546. });
  7547. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7548. get: function () {
  7549. return Engine._TEXTURETYPE_FLOAT;
  7550. },
  7551. enumerable: true,
  7552. configurable: true
  7553. });
  7554. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7555. get: function () {
  7556. return Engine._TEXTURETYPE_HALF_FLOAT;
  7557. },
  7558. enumerable: true,
  7559. configurable: true
  7560. });
  7561. Object.defineProperty(Engine, "Version", {
  7562. get: function () {
  7563. return "3.0-alpha";
  7564. },
  7565. enumerable: true,
  7566. configurable: true
  7567. });
  7568. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7569. get: function () {
  7570. return this._texturesSupported;
  7571. },
  7572. enumerable: true,
  7573. configurable: true
  7574. });
  7575. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7576. get: function () {
  7577. return this._textureFormatInUse;
  7578. },
  7579. enumerable: true,
  7580. configurable: true
  7581. });
  7582. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7583. get: function () {
  7584. return this._webGLVersion;
  7585. },
  7586. enumerable: true,
  7587. configurable: true
  7588. });
  7589. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7590. /**
  7591. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7592. */
  7593. get: function () {
  7594. return this._isStencilEnable;
  7595. },
  7596. enumerable: true,
  7597. configurable: true
  7598. });
  7599. Engine.prototype._prepareWorkingCanvas = function () {
  7600. if (this._workingCanvas) {
  7601. return;
  7602. }
  7603. this._workingCanvas = document.createElement("canvas");
  7604. this._workingContext = this._workingCanvas.getContext("2d");
  7605. };
  7606. Engine.prototype.resetTextureCache = function () {
  7607. for (var index = 0; index < this._maxTextureChannels; index++) {
  7608. this._activeTexturesCache[index] = null;
  7609. }
  7610. };
  7611. Engine.prototype.getGlInfo = function () {
  7612. return {
  7613. vendor: this._glVendor,
  7614. renderer: this._glRenderer,
  7615. version: this._glVersion
  7616. };
  7617. };
  7618. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7619. if (useScreen === void 0) { useScreen = false; }
  7620. var viewport = camera.viewport;
  7621. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7622. };
  7623. Engine.prototype.getRenderWidth = function (useScreen) {
  7624. if (useScreen === void 0) { useScreen = false; }
  7625. if (!useScreen && this._currentRenderTarget) {
  7626. return this._currentRenderTarget._width;
  7627. }
  7628. return this._renderingCanvas.width;
  7629. };
  7630. Engine.prototype.getRenderHeight = function (useScreen) {
  7631. if (useScreen === void 0) { useScreen = false; }
  7632. if (!useScreen && this._currentRenderTarget) {
  7633. return this._currentRenderTarget._height;
  7634. }
  7635. return this._renderingCanvas.height;
  7636. };
  7637. Engine.prototype.getRenderingCanvas = function () {
  7638. return this._renderingCanvas;
  7639. };
  7640. Engine.prototype.getRenderingCanvasClientRect = function () {
  7641. return this._renderingCanvas.getBoundingClientRect();
  7642. };
  7643. Engine.prototype.setHardwareScalingLevel = function (level) {
  7644. this._hardwareScalingLevel = level;
  7645. this.resize();
  7646. };
  7647. Engine.prototype.getHardwareScalingLevel = function () {
  7648. return this._hardwareScalingLevel;
  7649. };
  7650. Engine.prototype.getLoadedTexturesCache = function () {
  7651. return this._loadedTexturesCache;
  7652. };
  7653. Engine.prototype.getCaps = function () {
  7654. return this._caps;
  7655. };
  7656. Object.defineProperty(Engine.prototype, "drawCalls", {
  7657. get: function () {
  7658. return this._drawCalls.current;
  7659. },
  7660. enumerable: true,
  7661. configurable: true
  7662. });
  7663. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7664. get: function () {
  7665. return this._drawCalls;
  7666. },
  7667. enumerable: true,
  7668. configurable: true
  7669. });
  7670. Engine.prototype.getDepthFunction = function () {
  7671. return this._depthCullingState.depthFunc;
  7672. };
  7673. Engine.prototype.setDepthFunction = function (depthFunc) {
  7674. this._depthCullingState.depthFunc = depthFunc;
  7675. };
  7676. Engine.prototype.setDepthFunctionToGreater = function () {
  7677. this._depthCullingState.depthFunc = this._gl.GREATER;
  7678. };
  7679. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7680. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7681. };
  7682. Engine.prototype.setDepthFunctionToLess = function () {
  7683. this._depthCullingState.depthFunc = this._gl.LESS;
  7684. };
  7685. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7686. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7687. };
  7688. Engine.prototype.getStencilBuffer = function () {
  7689. return this._stencilState.stencilTest;
  7690. };
  7691. Engine.prototype.setStencilBuffer = function (enable) {
  7692. this._stencilState.stencilTest = enable;
  7693. };
  7694. Engine.prototype.getStencilMask = function () {
  7695. return this._stencilState.stencilMask;
  7696. };
  7697. Engine.prototype.setStencilMask = function (mask) {
  7698. this._stencilState.stencilMask = mask;
  7699. };
  7700. Engine.prototype.getStencilFunction = function () {
  7701. return this._stencilState.stencilFunc;
  7702. };
  7703. Engine.prototype.getStencilFunctionReference = function () {
  7704. return this._stencilState.stencilFuncRef;
  7705. };
  7706. Engine.prototype.getStencilFunctionMask = function () {
  7707. return this._stencilState.stencilFuncMask;
  7708. };
  7709. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7710. this._stencilState.stencilFunc = stencilFunc;
  7711. };
  7712. Engine.prototype.setStencilFunctionReference = function (reference) {
  7713. this._stencilState.stencilFuncRef = reference;
  7714. };
  7715. Engine.prototype.setStencilFunctionMask = function (mask) {
  7716. this._stencilState.stencilFuncMask = mask;
  7717. };
  7718. Engine.prototype.getStencilOperationFail = function () {
  7719. return this._stencilState.stencilOpStencilFail;
  7720. };
  7721. Engine.prototype.getStencilOperationDepthFail = function () {
  7722. return this._stencilState.stencilOpDepthFail;
  7723. };
  7724. Engine.prototype.getStencilOperationPass = function () {
  7725. return this._stencilState.stencilOpStencilDepthPass;
  7726. };
  7727. Engine.prototype.setStencilOperationFail = function (operation) {
  7728. this._stencilState.stencilOpStencilFail = operation;
  7729. };
  7730. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7731. this._stencilState.stencilOpDepthFail = operation;
  7732. };
  7733. Engine.prototype.setStencilOperationPass = function (operation) {
  7734. this._stencilState.stencilOpStencilDepthPass = operation;
  7735. };
  7736. Engine.prototype.setDitheringState = function (value) {
  7737. if (value) {
  7738. this._gl.enable(this._gl.DITHER);
  7739. }
  7740. else {
  7741. this._gl.disable(this._gl.DITHER);
  7742. }
  7743. };
  7744. /**
  7745. * stop executing a render loop function and remove it from the execution array
  7746. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7747. */
  7748. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7749. if (!renderFunction) {
  7750. this._activeRenderLoops = [];
  7751. return;
  7752. }
  7753. var index = this._activeRenderLoops.indexOf(renderFunction);
  7754. if (index >= 0) {
  7755. this._activeRenderLoops.splice(index, 1);
  7756. }
  7757. };
  7758. Engine.prototype._renderLoop = function () {
  7759. var shouldRender = true;
  7760. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7761. shouldRender = false;
  7762. }
  7763. if (shouldRender) {
  7764. // Start new frame
  7765. this.beginFrame();
  7766. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7767. var renderFunction = this._activeRenderLoops[index];
  7768. renderFunction();
  7769. }
  7770. // Present
  7771. this.endFrame();
  7772. }
  7773. if (this._activeRenderLoops.length > 0) {
  7774. // Register new frame
  7775. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7776. }
  7777. else {
  7778. this._renderingQueueLaunched = false;
  7779. }
  7780. };
  7781. /**
  7782. * Register and execute a render loop. The engine can have more than one render function.
  7783. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7784. * @example
  7785. * engine.runRenderLoop(function () {
  7786. * scene.render()
  7787. * })
  7788. */
  7789. Engine.prototype.runRenderLoop = function (renderFunction) {
  7790. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7791. return;
  7792. }
  7793. this._activeRenderLoops.push(renderFunction);
  7794. if (!this._renderingQueueLaunched) {
  7795. this._renderingQueueLaunched = true;
  7796. this._bindedRenderFunction = this._renderLoop.bind(this);
  7797. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7798. }
  7799. };
  7800. /**
  7801. * Toggle full screen mode.
  7802. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7803. * @param {any} options - an options object to be sent to the requestFullscreen function
  7804. */
  7805. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7806. if (this.isFullscreen) {
  7807. BABYLON.Tools.ExitFullscreen();
  7808. }
  7809. else {
  7810. this._pointerLockRequested = requestPointerLock;
  7811. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7812. }
  7813. };
  7814. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7815. if (stencil === void 0) { stencil = false; }
  7816. this.applyStates();
  7817. var mode = 0;
  7818. if (backBuffer && color) {
  7819. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7820. mode |= this._gl.COLOR_BUFFER_BIT;
  7821. }
  7822. if (depth) {
  7823. this._gl.clearDepth(1.0);
  7824. mode |= this._gl.DEPTH_BUFFER_BIT;
  7825. }
  7826. if (stencil) {
  7827. this._gl.clearStencil(0);
  7828. mode |= this._gl.STENCIL_BUFFER_BIT;
  7829. }
  7830. this._gl.clear(mode);
  7831. };
  7832. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7833. var gl = this._gl;
  7834. // Save state
  7835. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7836. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7837. // Change state
  7838. gl.enable(gl.SCISSOR_TEST);
  7839. gl.scissor(x, y, width, height);
  7840. // Clear
  7841. this.clear(clearColor, true, true, true);
  7842. // Restore state
  7843. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7844. if (curScissor === true) {
  7845. gl.enable(gl.SCISSOR_TEST);
  7846. }
  7847. else {
  7848. gl.disable(gl.SCISSOR_TEST);
  7849. }
  7850. };
  7851. /**
  7852. * Set the WebGL's viewport
  7853. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7854. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7855. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7856. */
  7857. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7858. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7859. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7860. var x = viewport.x || 0;
  7861. var y = viewport.y || 0;
  7862. this._cachedViewport = viewport;
  7863. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7864. };
  7865. /**
  7866. * Directly set the WebGL Viewport
  7867. * The x, y, width & height are directly passed to the WebGL call
  7868. * @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.
  7869. */
  7870. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7871. var currentViewport = this._cachedViewport;
  7872. this._cachedViewport = null;
  7873. this._gl.viewport(x, y, width, height);
  7874. return currentViewport;
  7875. };
  7876. Engine.prototype.beginFrame = function () {
  7877. this._measureFps();
  7878. };
  7879. Engine.prototype.endFrame = function () {
  7880. //force a flush in case we are using a bad OS.
  7881. if (this._badOS) {
  7882. this.flushFramebuffer();
  7883. }
  7884. //submit frame to the vr device, if enabled
  7885. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7886. this._vrDisplayEnabled.submitFrame();
  7887. }
  7888. };
  7889. /**
  7890. * resize the view according to the canvas' size.
  7891. * @example
  7892. * window.addEventListener("resize", function () {
  7893. * engine.resize();
  7894. * });
  7895. */
  7896. Engine.prototype.resize = function () {
  7897. // We're not resizing the size of the canvas while in VR mode & presenting
  7898. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  7899. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7900. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7901. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7902. }
  7903. };
  7904. /**
  7905. * force a specific size of the canvas
  7906. * @param {number} width - the new canvas' width
  7907. * @param {number} height - the new canvas' height
  7908. */
  7909. Engine.prototype.setSize = function (width, height) {
  7910. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  7911. return;
  7912. }
  7913. this._renderingCanvas.width = width;
  7914. this._renderingCanvas.height = height;
  7915. for (var index = 0; index < this.scenes.length; index++) {
  7916. var scene = this.scenes[index];
  7917. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7918. var cam = scene.cameras[camIndex];
  7919. cam._currentRenderId = 0;
  7920. }
  7921. }
  7922. if (this.onResizeObservable.hasObservers) {
  7923. this.onResizeObservable.notifyObservers(this);
  7924. }
  7925. };
  7926. //WebVR functions
  7927. Engine.prototype.initWebVR = function () {
  7928. if (!this.vrDisplaysPromise) {
  7929. this._getVRDisplays();
  7930. }
  7931. };
  7932. Engine.prototype.enableVR = function (vrDevice) {
  7933. this._vrDisplayEnabled = vrDevice;
  7934. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7935. };
  7936. Engine.prototype.disableVR = function () {
  7937. if (this._vrDisplayEnabled) {
  7938. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7939. }
  7940. };
  7941. Engine.prototype._getVRDisplays = function () {
  7942. var _this = this;
  7943. var getWebVRDevices = function (devices) {
  7944. var size = devices.length;
  7945. var i = 0;
  7946. _this._vrDisplays = devices.filter(function (device) {
  7947. return devices[i] instanceof VRDisplay;
  7948. });
  7949. return _this._vrDisplays;
  7950. };
  7951. //using a key due to typescript
  7952. if (navigator.getVRDisplays) {
  7953. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7954. }
  7955. };
  7956. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7957. this._currentRenderTarget = texture;
  7958. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  7959. var gl = this._gl;
  7960. if (texture.isCube) {
  7961. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7962. }
  7963. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7964. this.wipeCaches();
  7965. };
  7966. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7967. if (this._currentFramebuffer !== framebuffer) {
  7968. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7969. this._currentFramebuffer = framebuffer;
  7970. }
  7971. };
  7972. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  7973. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7974. this._currentRenderTarget = null;
  7975. // If MSAA, we need to bitblt back to main texture
  7976. var gl = this._gl;
  7977. if (texture._MSAAFramebuffer) {
  7978. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  7979. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  7980. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  7981. }
  7982. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7983. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7984. gl.generateMipmap(gl.TEXTURE_2D);
  7985. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7986. }
  7987. if (onBeforeUnbind) {
  7988. if (texture._MSAAFramebuffer) {
  7989. // Bind the correct framebuffer
  7990. this.bindUnboundFramebuffer(texture._framebuffer);
  7991. }
  7992. onBeforeUnbind();
  7993. }
  7994. this.bindUnboundFramebuffer(null);
  7995. };
  7996. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7997. if (texture.generateMipMaps) {
  7998. var gl = this._gl;
  7999. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8000. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8001. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8002. }
  8003. };
  8004. Engine.prototype.flushFramebuffer = function () {
  8005. this._gl.flush();
  8006. };
  8007. Engine.prototype.restoreDefaultFramebuffer = function () {
  8008. this._currentRenderTarget = null;
  8009. this.bindUnboundFramebuffer(null);
  8010. this.setViewport(this._cachedViewport);
  8011. this.wipeCaches();
  8012. };
  8013. // UBOs
  8014. Engine.prototype.createUniformBuffer = function (elements) {
  8015. var ubo = this._gl.createBuffer();
  8016. this.bindUniformBuffer(ubo);
  8017. if (elements instanceof Float32Array) {
  8018. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8019. }
  8020. else {
  8021. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8022. }
  8023. this.bindUniformBuffer(null);
  8024. ubo.references = 1;
  8025. return ubo;
  8026. };
  8027. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8028. var ubo = this._gl.createBuffer();
  8029. this.bindUniformBuffer(ubo);
  8030. if (elements instanceof Float32Array) {
  8031. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8032. }
  8033. else {
  8034. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8035. }
  8036. this.bindUniformBuffer(null);
  8037. ubo.references = 1;
  8038. return ubo;
  8039. };
  8040. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8041. this.bindUniformBuffer(uniformBuffer);
  8042. if (offset === undefined) {
  8043. offset = 0;
  8044. }
  8045. if (count === undefined) {
  8046. if (elements instanceof Float32Array) {
  8047. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8048. }
  8049. else {
  8050. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8051. }
  8052. }
  8053. else {
  8054. if (elements instanceof Float32Array) {
  8055. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8056. }
  8057. else {
  8058. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8059. }
  8060. }
  8061. this.bindUniformBuffer(null);
  8062. };
  8063. // VBOs
  8064. Engine.prototype._resetVertexBufferBinding = function () {
  8065. this.bindArrayBuffer(null);
  8066. this._cachedVertexBuffers = null;
  8067. };
  8068. Engine.prototype.createVertexBuffer = function (vertices) {
  8069. var vbo = this._gl.createBuffer();
  8070. this.bindArrayBuffer(vbo);
  8071. if (vertices instanceof Float32Array) {
  8072. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8073. }
  8074. else {
  8075. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8076. }
  8077. this._resetVertexBufferBinding();
  8078. vbo.references = 1;
  8079. return vbo;
  8080. };
  8081. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8082. var vbo = this._gl.createBuffer();
  8083. this.bindArrayBuffer(vbo);
  8084. if (vertices instanceof Float32Array) {
  8085. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8086. }
  8087. else {
  8088. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8089. }
  8090. this._resetVertexBufferBinding();
  8091. vbo.references = 1;
  8092. return vbo;
  8093. };
  8094. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8095. this.bindArrayBuffer(vertexBuffer);
  8096. if (offset === undefined) {
  8097. offset = 0;
  8098. }
  8099. if (count === undefined) {
  8100. if (vertices instanceof Float32Array) {
  8101. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8102. }
  8103. else {
  8104. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8105. }
  8106. }
  8107. else {
  8108. if (vertices instanceof Float32Array) {
  8109. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8110. }
  8111. else {
  8112. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8113. }
  8114. }
  8115. this._resetVertexBufferBinding();
  8116. };
  8117. Engine.prototype._resetIndexBufferBinding = function () {
  8118. this.bindIndexBuffer(null);
  8119. this._cachedIndexBuffer = null;
  8120. };
  8121. Engine.prototype.createIndexBuffer = function (indices) {
  8122. var vbo = this._gl.createBuffer();
  8123. this.bindIndexBuffer(vbo);
  8124. // Check for 32 bits indices
  8125. var arrayBuffer;
  8126. var need32Bits = false;
  8127. if (indices instanceof Uint16Array) {
  8128. arrayBuffer = indices;
  8129. }
  8130. else {
  8131. //check 32 bit support
  8132. if (this._caps.uintIndices) {
  8133. if (indices instanceof Uint32Array) {
  8134. arrayBuffer = indices;
  8135. need32Bits = true;
  8136. }
  8137. else {
  8138. //number[] or Int32Array, check if 32 bit is necessary
  8139. for (var index = 0; index < indices.length; index++) {
  8140. if (indices[index] > 65535) {
  8141. need32Bits = true;
  8142. break;
  8143. }
  8144. }
  8145. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8146. }
  8147. }
  8148. else {
  8149. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8150. arrayBuffer = new Uint16Array(indices);
  8151. }
  8152. }
  8153. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8154. this._resetIndexBufferBinding();
  8155. vbo.references = 1;
  8156. vbo.is32Bits = need32Bits;
  8157. return vbo;
  8158. };
  8159. Engine.prototype.bindArrayBuffer = function (buffer) {
  8160. if (!this._vaoRecordInProgress) {
  8161. this._unBindVertexArrayObject();
  8162. }
  8163. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8164. };
  8165. Engine.prototype.bindUniformBuffer = function (buffer) {
  8166. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8167. };
  8168. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8169. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8170. };
  8171. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8172. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8173. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8174. };
  8175. ;
  8176. Engine.prototype.bindIndexBuffer = function (buffer) {
  8177. if (!this._vaoRecordInProgress) {
  8178. this._unBindVertexArrayObject();
  8179. }
  8180. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8181. };
  8182. Engine.prototype.bindBuffer = function (buffer, target) {
  8183. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8184. this._gl.bindBuffer(target, buffer);
  8185. this._currentBoundBuffer[target] = buffer;
  8186. }
  8187. };
  8188. Engine.prototype.updateArrayBuffer = function (data) {
  8189. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8190. };
  8191. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8192. var pointer = this._currentBufferPointers[indx];
  8193. var changed = false;
  8194. if (!pointer) {
  8195. changed = true;
  8196. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8197. }
  8198. else {
  8199. if (pointer.buffer !== buffer) {
  8200. pointer.buffer = buffer;
  8201. changed = true;
  8202. }
  8203. if (pointer.size !== size) {
  8204. pointer.size = size;
  8205. changed = true;
  8206. }
  8207. if (pointer.type !== type) {
  8208. pointer.type = type;
  8209. changed = true;
  8210. }
  8211. if (pointer.normalized !== normalized) {
  8212. pointer.normalized = normalized;
  8213. changed = true;
  8214. }
  8215. if (pointer.stride !== stride) {
  8216. pointer.stride = stride;
  8217. changed = true;
  8218. }
  8219. if (pointer.offset !== offset) {
  8220. pointer.offset = offset;
  8221. changed = true;
  8222. }
  8223. }
  8224. if (changed || this._vaoRecordInProgress) {
  8225. this.bindArrayBuffer(buffer);
  8226. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8227. }
  8228. };
  8229. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8230. if (indexBuffer == null) {
  8231. return;
  8232. }
  8233. if (this._cachedIndexBuffer !== indexBuffer) {
  8234. this._cachedIndexBuffer = indexBuffer;
  8235. this.bindIndexBuffer(indexBuffer);
  8236. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8237. }
  8238. };
  8239. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8240. var attributes = effect.getAttributesNames();
  8241. if (!this._vaoRecordInProgress) {
  8242. this._unBindVertexArrayObject();
  8243. }
  8244. this.unbindAllAttributes();
  8245. for (var index = 0; index < attributes.length; index++) {
  8246. var order = effect.getAttributeLocation(index);
  8247. if (order >= 0) {
  8248. var vertexBuffer = vertexBuffers[attributes[index]];
  8249. if (!vertexBuffer) {
  8250. continue;
  8251. }
  8252. this._gl.enableVertexAttribArray(order);
  8253. if (!this._vaoRecordInProgress) {
  8254. this._vertexAttribArraysEnabled[order] = true;
  8255. }
  8256. var buffer = vertexBuffer.getBuffer();
  8257. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8258. if (vertexBuffer.getIsInstanced()) {
  8259. this._gl.vertexAttribDivisor(order, 1);
  8260. if (!this._vaoRecordInProgress) {
  8261. this._currentInstanceLocations.push(order);
  8262. this._currentInstanceBuffers.push(buffer);
  8263. }
  8264. }
  8265. }
  8266. }
  8267. };
  8268. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8269. var vao = this._gl.createVertexArray();
  8270. this._vaoRecordInProgress = true;
  8271. this._gl.bindVertexArray(vao);
  8272. this._mustWipeVertexAttributes = true;
  8273. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8274. this.bindIndexBuffer(indexBuffer);
  8275. this._vaoRecordInProgress = false;
  8276. this._gl.bindVertexArray(null);
  8277. return vao;
  8278. };
  8279. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8280. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8281. this._cachedVertexArrayObject = vertexArrayObject;
  8282. this._gl.bindVertexArray(vertexArrayObject);
  8283. this._cachedVertexBuffers = null;
  8284. this._cachedIndexBuffer = null;
  8285. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8286. this._mustWipeVertexAttributes = true;
  8287. }
  8288. };
  8289. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8290. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8291. this._cachedVertexBuffers = vertexBuffer;
  8292. this._cachedEffectForVertexBuffers = effect;
  8293. var attributesCount = effect.getAttributesCount();
  8294. this._unBindVertexArrayObject();
  8295. this.unbindAllAttributes();
  8296. var offset = 0;
  8297. for (var index = 0; index < attributesCount; index++) {
  8298. if (index < vertexDeclaration.length) {
  8299. var order = effect.getAttributeLocation(index);
  8300. if (order >= 0) {
  8301. this._gl.enableVertexAttribArray(order);
  8302. this._vertexAttribArraysEnabled[order] = true;
  8303. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8304. }
  8305. offset += vertexDeclaration[index] * 4;
  8306. }
  8307. }
  8308. }
  8309. this._bindIndexBufferWithCache(indexBuffer);
  8310. };
  8311. Engine.prototype._unBindVertexArrayObject = function () {
  8312. if (!this._cachedVertexArrayObject) {
  8313. return;
  8314. }
  8315. this._cachedVertexArrayObject = null;
  8316. this._gl.bindVertexArray(null);
  8317. };
  8318. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8319. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8320. this._cachedVertexBuffers = vertexBuffers;
  8321. this._cachedEffectForVertexBuffers = effect;
  8322. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8323. }
  8324. this._bindIndexBufferWithCache(indexBuffer);
  8325. };
  8326. Engine.prototype.unbindInstanceAttributes = function () {
  8327. var boundBuffer;
  8328. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8329. var instancesBuffer = this._currentInstanceBuffers[i];
  8330. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  8331. boundBuffer = instancesBuffer;
  8332. this.bindArrayBuffer(instancesBuffer);
  8333. }
  8334. var offsetLocation = this._currentInstanceLocations[i];
  8335. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8336. }
  8337. this._currentInstanceBuffers.length = 0;
  8338. this._currentInstanceLocations.length = 0;
  8339. };
  8340. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8341. this._gl.deleteVertexArray(vao);
  8342. };
  8343. Engine.prototype._releaseBuffer = function (buffer) {
  8344. buffer.references--;
  8345. if (buffer.references === 0) {
  8346. this._gl.deleteBuffer(buffer);
  8347. return true;
  8348. }
  8349. return false;
  8350. };
  8351. Engine.prototype.createInstancesBuffer = function (capacity) {
  8352. var buffer = this._gl.createBuffer();
  8353. buffer.capacity = capacity;
  8354. this.bindArrayBuffer(buffer);
  8355. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8356. return buffer;
  8357. };
  8358. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8359. this._gl.deleteBuffer(buffer);
  8360. };
  8361. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8362. this.bindArrayBuffer(instancesBuffer);
  8363. if (data) {
  8364. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8365. }
  8366. if (offsetLocations[0].index !== undefined) {
  8367. var stride = 0;
  8368. for (var i = 0; i < offsetLocations.length; i++) {
  8369. var ai = offsetLocations[i];
  8370. stride += ai.attributeSize * 4;
  8371. }
  8372. for (var i = 0; i < offsetLocations.length; i++) {
  8373. var ai = offsetLocations[i];
  8374. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8375. this._gl.enableVertexAttribArray(ai.index);
  8376. this._vertexAttribArraysEnabled[ai.index] = true;
  8377. }
  8378. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8379. this._gl.vertexAttribDivisor(ai.index, 1);
  8380. this._currentInstanceLocations.push(ai.index);
  8381. this._currentInstanceBuffers.push(instancesBuffer);
  8382. }
  8383. }
  8384. else {
  8385. for (var index = 0; index < 4; index++) {
  8386. var offsetLocation = offsetLocations[index];
  8387. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8388. this._gl.enableVertexAttribArray(offsetLocation);
  8389. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8390. }
  8391. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8392. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8393. this._currentInstanceLocations.push(offsetLocation);
  8394. this._currentInstanceBuffers.push(instancesBuffer);
  8395. }
  8396. }
  8397. };
  8398. Engine.prototype.applyStates = function () {
  8399. this._depthCullingState.apply(this._gl);
  8400. this._stencilState.apply(this._gl);
  8401. this._alphaState.apply(this._gl);
  8402. };
  8403. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8404. // Apply states
  8405. this.applyStates();
  8406. this._drawCalls.addCount(1, false);
  8407. // Render
  8408. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8409. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8410. if (instancesCount) {
  8411. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8412. return;
  8413. }
  8414. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8415. };
  8416. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8417. // Apply states
  8418. this.applyStates();
  8419. this._drawCalls.addCount(1, false);
  8420. if (instancesCount) {
  8421. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8422. return;
  8423. }
  8424. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8425. };
  8426. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8427. // Apply states
  8428. this.applyStates();
  8429. this._drawCalls.addCount(1, false);
  8430. if (instancesCount) {
  8431. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8432. return;
  8433. }
  8434. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8435. };
  8436. // Shaders
  8437. Engine.prototype._releaseEffect = function (effect) {
  8438. if (this._compiledEffects[effect._key]) {
  8439. delete this._compiledEffects[effect._key];
  8440. if (effect.getProgram()) {
  8441. this._gl.deleteProgram(effect.getProgram());
  8442. }
  8443. }
  8444. };
  8445. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8446. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8447. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8448. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8449. if (this._compiledEffects[name]) {
  8450. return this._compiledEffects[name];
  8451. }
  8452. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8453. effect._key = name;
  8454. this._compiledEffects[name] = effect;
  8455. return effect;
  8456. };
  8457. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8458. if (uniformsNames === void 0) { uniformsNames = []; }
  8459. if (samplers === void 0) { samplers = []; }
  8460. if (defines === void 0) { defines = ""; }
  8461. return this.createEffect({
  8462. vertex: "particles",
  8463. fragmentElement: fragmentName
  8464. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8465. };
  8466. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8467. context = context || this._gl;
  8468. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8469. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8470. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8471. var shaderProgram = context.createProgram();
  8472. context.attachShader(shaderProgram, vertexShader);
  8473. context.attachShader(shaderProgram, fragmentShader);
  8474. context.linkProgram(shaderProgram);
  8475. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8476. if (!linked) {
  8477. var error = context.getProgramInfoLog(shaderProgram);
  8478. if (error) {
  8479. throw new Error(error);
  8480. }
  8481. }
  8482. context.deleteShader(vertexShader);
  8483. context.deleteShader(fragmentShader);
  8484. return shaderProgram;
  8485. };
  8486. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8487. var results = [];
  8488. for (var index = 0; index < uniformsNames.length; index++) {
  8489. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8490. }
  8491. return results;
  8492. };
  8493. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8494. var results = [];
  8495. for (var index = 0; index < attributesNames.length; index++) {
  8496. try {
  8497. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8498. }
  8499. catch (e) {
  8500. results.push(-1);
  8501. }
  8502. }
  8503. return results;
  8504. };
  8505. Engine.prototype.enableEffect = function (effect) {
  8506. // Use program
  8507. this.setProgram(effect.getProgram());
  8508. this._currentEffect = effect;
  8509. if (effect.onBind) {
  8510. effect.onBind(effect);
  8511. }
  8512. };
  8513. Engine.prototype.setIntArray = function (uniform, array) {
  8514. if (!uniform)
  8515. return;
  8516. this._gl.uniform1iv(uniform, array);
  8517. };
  8518. Engine.prototype.setIntArray2 = function (uniform, array) {
  8519. if (!uniform || array.length % 2 !== 0)
  8520. return;
  8521. this._gl.uniform2iv(uniform, array);
  8522. };
  8523. Engine.prototype.setIntArray3 = function (uniform, array) {
  8524. if (!uniform || array.length % 3 !== 0)
  8525. return;
  8526. this._gl.uniform3iv(uniform, array);
  8527. };
  8528. Engine.prototype.setIntArray4 = function (uniform, array) {
  8529. if (!uniform || array.length % 4 !== 0)
  8530. return;
  8531. this._gl.uniform4iv(uniform, array);
  8532. };
  8533. Engine.prototype.setFloatArray = function (uniform, array) {
  8534. if (!uniform)
  8535. return;
  8536. this._gl.uniform1fv(uniform, array);
  8537. };
  8538. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8539. if (!uniform || array.length % 2 !== 0)
  8540. return;
  8541. this._gl.uniform2fv(uniform, array);
  8542. };
  8543. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8544. if (!uniform || array.length % 3 !== 0)
  8545. return;
  8546. this._gl.uniform3fv(uniform, array);
  8547. };
  8548. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8549. if (!uniform || array.length % 4 !== 0)
  8550. return;
  8551. this._gl.uniform4fv(uniform, array);
  8552. };
  8553. Engine.prototype.setArray = function (uniform, array) {
  8554. if (!uniform)
  8555. return;
  8556. this._gl.uniform1fv(uniform, array);
  8557. };
  8558. Engine.prototype.setArray2 = function (uniform, array) {
  8559. if (!uniform || array.length % 2 !== 0)
  8560. return;
  8561. this._gl.uniform2fv(uniform, array);
  8562. };
  8563. Engine.prototype.setArray3 = function (uniform, array) {
  8564. if (!uniform || array.length % 3 !== 0)
  8565. return;
  8566. this._gl.uniform3fv(uniform, array);
  8567. };
  8568. Engine.prototype.setArray4 = function (uniform, array) {
  8569. if (!uniform || array.length % 4 !== 0)
  8570. return;
  8571. this._gl.uniform4fv(uniform, array);
  8572. };
  8573. Engine.prototype.setMatrices = function (uniform, matrices) {
  8574. if (!uniform)
  8575. return;
  8576. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8577. };
  8578. Engine.prototype.setMatrix = function (uniform, matrix) {
  8579. if (!uniform)
  8580. return;
  8581. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8582. };
  8583. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8584. if (!uniform)
  8585. return;
  8586. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8587. };
  8588. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8589. if (!uniform)
  8590. return;
  8591. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8592. };
  8593. Engine.prototype.setFloat = function (uniform, value) {
  8594. if (!uniform)
  8595. return;
  8596. this._gl.uniform1f(uniform, value);
  8597. };
  8598. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8599. if (!uniform)
  8600. return;
  8601. this._gl.uniform2f(uniform, x, y);
  8602. };
  8603. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8604. if (!uniform)
  8605. return;
  8606. this._gl.uniform3f(uniform, x, y, z);
  8607. };
  8608. Engine.prototype.setBool = function (uniform, bool) {
  8609. if (!uniform)
  8610. return;
  8611. this._gl.uniform1i(uniform, bool);
  8612. };
  8613. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8614. if (!uniform)
  8615. return;
  8616. this._gl.uniform4f(uniform, x, y, z, w);
  8617. };
  8618. Engine.prototype.setColor3 = function (uniform, color3) {
  8619. if (!uniform)
  8620. return;
  8621. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8622. };
  8623. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8624. if (!uniform)
  8625. return;
  8626. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8627. };
  8628. // States
  8629. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8630. if (zOffset === void 0) { zOffset = 0; }
  8631. if (reverseSide === void 0) { reverseSide = false; }
  8632. // Culling
  8633. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8634. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8635. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8636. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8637. if (culling) {
  8638. this._depthCullingState.cullFace = cullFace;
  8639. this._depthCullingState.cull = true;
  8640. }
  8641. else {
  8642. this._depthCullingState.cull = false;
  8643. }
  8644. }
  8645. // Z offset
  8646. this._depthCullingState.zOffset = zOffset;
  8647. };
  8648. Engine.prototype.setDepthBuffer = function (enable) {
  8649. this._depthCullingState.depthTest = enable;
  8650. };
  8651. Engine.prototype.getDepthWrite = function () {
  8652. return this._depthCullingState.depthMask;
  8653. };
  8654. Engine.prototype.setDepthWrite = function (enable) {
  8655. this._depthCullingState.depthMask = enable;
  8656. };
  8657. Engine.prototype.setColorWrite = function (enable) {
  8658. this._gl.colorMask(enable, enable, enable, enable);
  8659. };
  8660. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8661. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8662. if (this._alphaMode === mode) {
  8663. return;
  8664. }
  8665. switch (mode) {
  8666. case Engine.ALPHA_DISABLE:
  8667. this._alphaState.alphaBlend = false;
  8668. break;
  8669. case Engine.ALPHA_PREMULTIPLIED:
  8670. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8671. this._alphaState.alphaBlend = true;
  8672. break;
  8673. case Engine.ALPHA_COMBINE:
  8674. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8675. this._alphaState.alphaBlend = true;
  8676. break;
  8677. case Engine.ALPHA_ONEONE:
  8678. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8679. this._alphaState.alphaBlend = true;
  8680. break;
  8681. case Engine.ALPHA_ADD:
  8682. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8683. this._alphaState.alphaBlend = true;
  8684. break;
  8685. case Engine.ALPHA_SUBTRACT:
  8686. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8687. this._alphaState.alphaBlend = true;
  8688. break;
  8689. case Engine.ALPHA_MULTIPLY:
  8690. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8691. this._alphaState.alphaBlend = true;
  8692. break;
  8693. case Engine.ALPHA_MAXIMIZED:
  8694. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8695. this._alphaState.alphaBlend = true;
  8696. break;
  8697. }
  8698. if (!noDepthWriteChange) {
  8699. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8700. }
  8701. this._alphaMode = mode;
  8702. };
  8703. Engine.prototype.getAlphaMode = function () {
  8704. return this._alphaMode;
  8705. };
  8706. Engine.prototype.setAlphaTesting = function (enable) {
  8707. this._alphaTest = enable;
  8708. };
  8709. Engine.prototype.getAlphaTesting = function () {
  8710. return !!this._alphaTest;
  8711. };
  8712. // Textures
  8713. Engine.prototype.wipeCaches = function () {
  8714. if (this.preventCacheWipeBetweenFrames) {
  8715. return;
  8716. }
  8717. this.resetTextureCache();
  8718. this._currentEffect = null;
  8719. this._stencilState.reset();
  8720. this._depthCullingState.reset();
  8721. this.setDepthFunctionToLessOrEqual();
  8722. this._alphaState.reset();
  8723. this._cachedVertexBuffers = null;
  8724. this._cachedIndexBuffer = null;
  8725. this._cachedEffectForVertexBuffers = null;
  8726. this._unBindVertexArrayObject();
  8727. this.bindIndexBuffer(null);
  8728. this.bindArrayBuffer(null);
  8729. };
  8730. /**
  8731. * Set the compressed texture format to use, based on the formats you have, and the formats
  8732. * supported by the hardware / browser.
  8733. *
  8734. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  8735. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  8736. * to API arguments needed to compressed textures. This puts the burden on the container
  8737. * generator to house the arcane code for determining these for current & future formats.
  8738. *
  8739. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  8740. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  8741. *
  8742. * Note: The result of this call is not taken into account when a texture is base64.
  8743. *
  8744. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  8745. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  8746. *
  8747. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  8748. * @returns The extension selected.
  8749. */
  8750. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8751. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8752. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8753. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8754. return this._textureFormatInUse = this._texturesSupported[i];
  8755. }
  8756. }
  8757. }
  8758. // actively set format to nothing, to allow this to be called more than once
  8759. // and possibly fail the 2nd time
  8760. return this._textureFormatInUse = null;
  8761. };
  8762. /**
  8763. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  8764. * @param {string} urlArg- This contains one of the following:
  8765. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  8766. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  8767. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  8768. *
  8769. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  8770. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  8771. * @param {Scene} scene- Needed for loading to the correct scene.
  8772. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  8773. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  8774. * @param {callback} onError- Optional callback to be called upon failure.
  8775. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  8776. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  8777. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  8778. *
  8779. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  8780. */
  8781. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  8782. var _this = this;
  8783. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8784. if (onLoad === void 0) { onLoad = null; }
  8785. if (onError === void 0) { onError = null; }
  8786. if (buffer === void 0) { buffer = null; }
  8787. var texture = fallBack ? fallBack : this._gl.createTexture();
  8788. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  8789. var fromData = url.substr(0, 5) === "data:";
  8790. var isBase64 = fromData && url.indexOf("base64") !== -1;
  8791. // establish the file extension, if possible
  8792. var lastDot = url.lastIndexOf('.');
  8793. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  8794. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8795. if (isDDS) {
  8796. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  8797. }
  8798. var isTGA = (extension === ".tga");
  8799. // determine if a ktx file should be substituted
  8800. var isKTX = false;
  8801. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  8802. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8803. isKTX = true;
  8804. }
  8805. scene._addPendingData(texture);
  8806. texture.url = url;
  8807. texture.noMipmap = noMipmap;
  8808. texture.references = 1;
  8809. texture.samplingMode = samplingMode;
  8810. texture.onLoadedCallbacks = [];
  8811. if (onLoad) {
  8812. texture.onLoadedCallbacks.push(onLoad);
  8813. }
  8814. if (!fallBack)
  8815. this._loadedTexturesCache.push(texture);
  8816. var onerror = function () {
  8817. scene._removePendingData(texture);
  8818. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  8819. if (isKTX) {
  8820. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  8821. }
  8822. else if (onError) {
  8823. onError();
  8824. }
  8825. };
  8826. var callback;
  8827. // processing for non-image formats
  8828. if (isKTX || isTGA || isDDS) {
  8829. if (isKTX) {
  8830. callback = function (data) {
  8831. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  8832. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  8833. ktx.uploadLevels(_this._gl, !noMipmap);
  8834. }, samplingMode);
  8835. };
  8836. }
  8837. else if (isTGA) {
  8838. callback = function (arrayBuffer) {
  8839. var data = new Uint8Array(arrayBuffer);
  8840. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8841. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8842. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8843. }, samplingMode);
  8844. };
  8845. }
  8846. else if (isDDS) {
  8847. callback = function (data) {
  8848. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8849. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8850. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8851. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8852. }, samplingMode);
  8853. };
  8854. }
  8855. if (!buffer) {
  8856. BABYLON.Tools.LoadFile(url, function (data) {
  8857. callback(data);
  8858. }, null, scene.database, true, onerror);
  8859. }
  8860. else {
  8861. callback(buffer);
  8862. }
  8863. // image format processing
  8864. }
  8865. else {
  8866. var onload = function (img) {
  8867. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8868. var isPot = (img.width === potWidth && img.height === potHeight);
  8869. if (!isPot) {
  8870. _this._prepareWorkingCanvas();
  8871. _this._workingCanvas.width = potWidth;
  8872. _this._workingCanvas.height = potHeight;
  8873. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8874. _this._workingContext.imageSmoothingEnabled = false;
  8875. _this._workingContext.mozImageSmoothingEnabled = false;
  8876. _this._workingContext.oImageSmoothingEnabled = false;
  8877. _this._workingContext.webkitImageSmoothingEnabled = false;
  8878. _this._workingContext.msImageSmoothingEnabled = false;
  8879. }
  8880. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8881. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8882. _this._workingContext.imageSmoothingEnabled = true;
  8883. _this._workingContext.mozImageSmoothingEnabled = true;
  8884. _this._workingContext.oImageSmoothingEnabled = true;
  8885. _this._workingContext.webkitImageSmoothingEnabled = true;
  8886. _this._workingContext.msImageSmoothingEnabled = true;
  8887. }
  8888. }
  8889. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  8890. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8891. }, samplingMode);
  8892. };
  8893. if (!fromData || isBase64)
  8894. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8895. else if (buffer instanceof Array || typeof buffer === "string")
  8896. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8897. else
  8898. onload(buffer);
  8899. }
  8900. return texture;
  8901. };
  8902. Engine.prototype._getInternalFormat = function (format) {
  8903. var internalFormat = this._gl.RGBA;
  8904. switch (format) {
  8905. case Engine.TEXTUREFORMAT_ALPHA:
  8906. internalFormat = this._gl.ALPHA;
  8907. break;
  8908. case Engine.TEXTUREFORMAT_LUMINANCE:
  8909. internalFormat = this._gl.LUMINANCE;
  8910. break;
  8911. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8912. internalFormat = this._gl.LUMINANCE_ALPHA;
  8913. break;
  8914. case Engine.TEXTUREFORMAT_RGB:
  8915. internalFormat = this._gl.RGB;
  8916. break;
  8917. case Engine.TEXTUREFORMAT_RGBA:
  8918. internalFormat = this._gl.RGBA;
  8919. break;
  8920. }
  8921. return internalFormat;
  8922. };
  8923. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8924. if (compression === void 0) { compression = null; }
  8925. var internalFormat = this._getInternalFormat(format);
  8926. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8927. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8928. if (texture._width % 4 !== 0) {
  8929. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8930. }
  8931. if (compression) {
  8932. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8933. }
  8934. else {
  8935. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8936. }
  8937. if (texture.generateMipMaps) {
  8938. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8939. }
  8940. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8941. this.resetTextureCache();
  8942. texture.isReady = true;
  8943. };
  8944. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8945. if (compression === void 0) { compression = null; }
  8946. var texture = this._gl.createTexture();
  8947. texture._baseWidth = width;
  8948. texture._baseHeight = height;
  8949. texture._width = width;
  8950. texture._height = height;
  8951. texture.references = 1;
  8952. this.updateRawTexture(texture, data, format, invertY, compression);
  8953. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8954. // Filters
  8955. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8956. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8957. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8958. if (generateMipMaps) {
  8959. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8960. }
  8961. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8962. texture.samplingMode = samplingMode;
  8963. this._loadedTexturesCache.push(texture);
  8964. return texture;
  8965. };
  8966. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8967. var texture = this._gl.createTexture();
  8968. texture._baseWidth = width;
  8969. texture._baseHeight = height;
  8970. if (generateMipMaps) {
  8971. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8972. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8973. }
  8974. this.resetTextureCache();
  8975. texture._width = width;
  8976. texture._height = height;
  8977. texture.isReady = false;
  8978. texture.generateMipMaps = generateMipMaps;
  8979. texture.references = 1;
  8980. texture.samplingMode = samplingMode;
  8981. this.updateTextureSamplingMode(samplingMode, texture);
  8982. this._loadedTexturesCache.push(texture);
  8983. return texture;
  8984. };
  8985. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8986. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8987. if (texture.isCube) {
  8988. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8989. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8990. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8991. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8992. }
  8993. else {
  8994. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8995. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8996. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8997. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8998. }
  8999. texture.samplingMode = samplingMode;
  9000. };
  9001. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9002. if (premulAlpha === void 0) { premulAlpha = false; }
  9003. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9004. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9005. if (premulAlpha) {
  9006. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9007. }
  9008. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9009. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9010. if (texture.generateMipMaps) {
  9011. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9012. }
  9013. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9014. if (premulAlpha) {
  9015. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9016. }
  9017. this.resetTextureCache();
  9018. texture.isReady = true;
  9019. };
  9020. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9021. if (texture._isDisabled) {
  9022. return;
  9023. }
  9024. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9025. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9026. try {
  9027. // Testing video texture support
  9028. if (this._videoTextureSupported === undefined) {
  9029. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9030. if (this._gl.getError() !== 0) {
  9031. this._videoTextureSupported = false;
  9032. }
  9033. else {
  9034. this._videoTextureSupported = true;
  9035. }
  9036. }
  9037. // Copy video through the current working canvas if video texture is not supported
  9038. if (!this._videoTextureSupported) {
  9039. if (!texture._workingCanvas) {
  9040. texture._workingCanvas = document.createElement("canvas");
  9041. texture._workingContext = texture._workingCanvas.getContext("2d");
  9042. texture._workingCanvas.width = texture._width;
  9043. texture._workingCanvas.height = texture._height;
  9044. }
  9045. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9046. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9047. }
  9048. else {
  9049. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9050. }
  9051. if (texture.generateMipMaps) {
  9052. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9053. }
  9054. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9055. this.resetTextureCache();
  9056. texture.isReady = true;
  9057. }
  9058. catch (ex) {
  9059. // Something unexpected
  9060. // Let's disable the texture
  9061. texture._isDisabled = true;
  9062. }
  9063. };
  9064. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9065. // old version had a "generateMipMaps" arg instead of options.
  9066. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9067. // in the same way, generateDepthBuffer is defaulted to true
  9068. var generateMipMaps = false;
  9069. var generateDepthBuffer = true;
  9070. var generateStencilBuffer = false;
  9071. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9072. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9073. if (options !== undefined) {
  9074. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9075. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9076. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9077. type = options.type === undefined ? type : options.type;
  9078. if (options.samplingMode !== undefined) {
  9079. samplingMode = options.samplingMode;
  9080. }
  9081. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9082. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9083. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9084. }
  9085. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9086. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9087. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9088. }
  9089. }
  9090. var gl = this._gl;
  9091. var texture = gl.createTexture();
  9092. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9093. var width = size.width || size;
  9094. var height = size.height || size;
  9095. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9096. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9097. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9098. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9099. }
  9100. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9101. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9102. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9103. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9104. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9105. // Create the framebuffer
  9106. var framebuffer = gl.createFramebuffer();
  9107. this.bindUnboundFramebuffer(framebuffer);
  9108. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9109. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9110. if (generateMipMaps) {
  9111. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9112. }
  9113. // Unbind
  9114. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9115. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9116. this.bindUnboundFramebuffer(null);
  9117. texture._framebuffer = framebuffer;
  9118. texture._baseWidth = width;
  9119. texture._baseHeight = height;
  9120. texture._width = width;
  9121. texture._height = height;
  9122. texture.isReady = true;
  9123. texture.samples = 1;
  9124. texture.generateMipMaps = generateMipMaps;
  9125. texture.references = 1;
  9126. texture.samplingMode = samplingMode;
  9127. texture.type = type;
  9128. texture._generateDepthBuffer = generateDepthBuffer;
  9129. texture._generateStencilBuffer = generateStencilBuffer;
  9130. this.resetTextureCache();
  9131. this._loadedTexturesCache.push(texture);
  9132. return texture;
  9133. };
  9134. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9135. if (samples === void 0) { samples = 1; }
  9136. var depthStencilBuffer = null;
  9137. var gl = this._gl;
  9138. // Create the depth/stencil buffer
  9139. if (generateStencilBuffer) {
  9140. depthStencilBuffer = gl.createRenderbuffer();
  9141. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9142. if (samples > 1) {
  9143. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9144. }
  9145. else {
  9146. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9147. }
  9148. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9149. }
  9150. else if (generateDepthBuffer) {
  9151. depthStencilBuffer = gl.createRenderbuffer();
  9152. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9153. if (samples > 1) {
  9154. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9155. }
  9156. else {
  9157. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9158. }
  9159. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9160. }
  9161. return depthStencilBuffer;
  9162. };
  9163. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9164. if (this.webGLVersion < 2) {
  9165. return 1;
  9166. }
  9167. if (texture.samples === samples) {
  9168. return samples;
  9169. }
  9170. var gl = this._gl;
  9171. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9172. // Dispose previous render buffers
  9173. if (texture._depthStencilBuffer) {
  9174. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9175. }
  9176. if (texture._MSAAFramebuffer) {
  9177. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9178. }
  9179. if (texture._MSAARenderBuffer) {
  9180. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9181. }
  9182. if (samples > 1) {
  9183. texture._MSAAFramebuffer = gl.createFramebuffer();
  9184. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9185. var colorRenderbuffer = gl.createRenderbuffer();
  9186. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9187. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9188. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9189. texture._MSAARenderBuffer = colorRenderbuffer;
  9190. }
  9191. else {
  9192. this.bindUnboundFramebuffer(texture._framebuffer);
  9193. }
  9194. texture.samples = samples;
  9195. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9196. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9197. this.bindUnboundFramebuffer(null);
  9198. return samples;
  9199. };
  9200. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9201. var gl = this._gl;
  9202. var texture = gl.createTexture();
  9203. var generateMipMaps = true;
  9204. var generateDepthBuffer = true;
  9205. var generateStencilBuffer = false;
  9206. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9207. if (options !== undefined) {
  9208. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9209. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9210. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9211. if (options.samplingMode !== undefined) {
  9212. samplingMode = options.samplingMode;
  9213. }
  9214. }
  9215. texture.isCube = true;
  9216. texture.references = 1;
  9217. texture.generateMipMaps = generateMipMaps;
  9218. texture.references = 1;
  9219. texture.samples = 1;
  9220. texture.samplingMode = samplingMode;
  9221. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9222. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9223. for (var face = 0; face < 6; face++) {
  9224. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9225. }
  9226. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9227. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9228. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9229. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9230. // Create the framebuffer
  9231. var framebuffer = gl.createFramebuffer();
  9232. this.bindUnboundFramebuffer(framebuffer);
  9233. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9234. // Mipmaps
  9235. if (texture.generateMipMaps) {
  9236. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9237. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9238. }
  9239. // Unbind
  9240. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9241. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9242. this.bindUnboundFramebuffer(null);
  9243. texture._framebuffer = framebuffer;
  9244. texture._width = size;
  9245. texture._height = size;
  9246. texture.isReady = true;
  9247. this.resetTextureCache();
  9248. this._loadedTexturesCache.push(texture);
  9249. return texture;
  9250. };
  9251. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9252. var _this = this;
  9253. if (onLoad === void 0) { onLoad = null; }
  9254. if (onError === void 0) { onError = null; }
  9255. var gl = this._gl;
  9256. var texture = gl.createTexture();
  9257. texture.isCube = true;
  9258. texture.url = rootUrl;
  9259. texture.references = 1;
  9260. texture.onLoadedCallbacks = [];
  9261. var isKTX = false;
  9262. var lastDot = rootUrl.lastIndexOf('.');
  9263. var extension = rootUrl.substring(lastDot).toLowerCase();
  9264. if (this._textureFormatInUse) {
  9265. extension = this._textureFormatInUse;
  9266. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9267. isKTX = true;
  9268. }
  9269. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9270. if (isDDS) {
  9271. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9272. }
  9273. if (isKTX) {
  9274. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9275. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9276. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9277. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9278. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9279. ktx.uploadLevels(_this._gl, !noMipmap);
  9280. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9281. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9282. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9283. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9284. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9285. _this.resetTextureCache();
  9286. texture._width = ktx.pixelWidth;
  9287. texture._height = ktx.pixelHeight;
  9288. texture.isReady = true;
  9289. }, null, null, true, onError);
  9290. }
  9291. else if (isDDS) {
  9292. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9293. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9294. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9295. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9296. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9297. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9298. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9299. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9300. }
  9301. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9302. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9303. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9304. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9305. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9306. _this.resetTextureCache();
  9307. texture._width = info.width;
  9308. texture._height = info.height;
  9309. texture.isReady = true;
  9310. }, null, null, true, onError);
  9311. }
  9312. else {
  9313. cascadeLoad(rootUrl, scene, function (imgs) {
  9314. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9315. var height = width;
  9316. _this._prepareWorkingCanvas();
  9317. _this._workingCanvas.width = width;
  9318. _this._workingCanvas.height = height;
  9319. var faces = [
  9320. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9321. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9322. ];
  9323. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9324. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9325. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9326. for (var index = 0; index < faces.length; index++) {
  9327. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9328. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9329. }
  9330. if (!noMipmap) {
  9331. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9332. }
  9333. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9334. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9335. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9336. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9337. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9338. _this.resetTextureCache();
  9339. texture._width = width;
  9340. texture._height = height;
  9341. texture.isReady = true;
  9342. texture.onLoadedCallbacks.forEach(function (callback) {
  9343. callback();
  9344. });
  9345. if (onLoad) {
  9346. onLoad();
  9347. }
  9348. }, files, onError);
  9349. }
  9350. this._loadedTexturesCache.push(texture);
  9351. return texture;
  9352. };
  9353. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9354. texture._width = width;
  9355. texture._height = height;
  9356. texture._size = width * height;
  9357. texture._baseWidth = width;
  9358. texture._baseHeight = height;
  9359. };
  9360. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  9361. var _this = this;
  9362. if (onLoad === void 0) { onLoad = null; }
  9363. if (onError === void 0) { onError = null; }
  9364. var gl = this._gl;
  9365. var texture = gl.createTexture();
  9366. scene._addPendingData(texture);
  9367. texture.isCube = true;
  9368. texture.references = 1;
  9369. texture.url = url;
  9370. var textureType = gl.UNSIGNED_BYTE;
  9371. if (type === Engine.TEXTURETYPE_FLOAT) {
  9372. textureType = gl.FLOAT;
  9373. }
  9374. var internalFormat = this._getInternalFormat(format);
  9375. var needConversion = false;
  9376. if (internalFormat === gl.RGB) {
  9377. internalFormat = gl.RGBA;
  9378. needConversion = true;
  9379. }
  9380. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9381. var width = size;
  9382. var height = width;
  9383. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9384. texture._width = width;
  9385. texture._height = height;
  9386. var onerror = function () {
  9387. scene._removePendingData(texture);
  9388. if (onError) {
  9389. onError();
  9390. }
  9391. };
  9392. var internalCallback = function (data) {
  9393. var rgbeDataArrays = callback(data);
  9394. var facesIndex = [
  9395. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9396. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9397. ];
  9398. width = texture._width;
  9399. height = texture._height;
  9400. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9401. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9402. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9403. if (mipmmapGenerator) {
  9404. var arrayTemp = [];
  9405. // Data are known to be in +X +Y +Z -X -Y -Z
  9406. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9407. arrayTemp.push(rgbeDataArrays[0]); // +X
  9408. arrayTemp.push(rgbeDataArrays[3]); // -X
  9409. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9410. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9411. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9412. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9413. var mipData = mipmmapGenerator(arrayTemp);
  9414. // mipData is order in +X -X +Y -Y +Z -Z
  9415. var mipFaces = [0, 2, 4, 1, 3, 5];
  9416. for (var level = 0; level < mipData.length; level++) {
  9417. var mipSize = width >> level;
  9418. for (var mipIndex in mipFaces) {
  9419. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9420. if (needConversion) {
  9421. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9422. }
  9423. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9424. }
  9425. }
  9426. }
  9427. else {
  9428. // Data are known to be in +X +Y +Z -X -Y -Z
  9429. for (var index = 0; index < facesIndex.length; index++) {
  9430. var faceData = rgbeDataArrays[index];
  9431. if (needConversion) {
  9432. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  9433. }
  9434. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  9435. }
  9436. if (!noMipmap && isPot) {
  9437. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9438. }
  9439. else {
  9440. noMipmap = true;
  9441. }
  9442. }
  9443. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  9444. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9445. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9446. }
  9447. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  9448. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9449. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9450. }
  9451. else {
  9452. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9453. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9454. }
  9455. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9456. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9457. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9458. texture.isReady = true;
  9459. _this.resetTextureCache();
  9460. scene._removePendingData(texture);
  9461. if (onLoad) {
  9462. onLoad();
  9463. }
  9464. };
  9465. BABYLON.Tools.LoadFile(url, function (data) {
  9466. internalCallback(data);
  9467. }, onerror, scene.database, true);
  9468. return texture;
  9469. };
  9470. ;
  9471. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9472. // Create new RGBA data container.
  9473. var rgbaData;
  9474. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9475. rgbaData = new Float32Array(width * height * 4);
  9476. }
  9477. else {
  9478. rgbaData = new Uint32Array(width * height * 4);
  9479. }
  9480. // Convert each pixel.
  9481. for (var x = 0; x < width; x++) {
  9482. for (var y = 0; y < height; y++) {
  9483. var index = (y * width + x) * 3;
  9484. var newIndex = (y * width + x) * 4;
  9485. // Map Old Value to new value.
  9486. rgbaData[newIndex + 0] = rgbData[index + 0];
  9487. rgbaData[newIndex + 1] = rgbData[index + 1];
  9488. rgbaData[newIndex + 2] = rgbData[index + 2];
  9489. // Add fully opaque alpha channel.
  9490. rgbaData[newIndex + 3] = 1;
  9491. }
  9492. }
  9493. return rgbaData;
  9494. };
  9495. Engine.prototype._releaseTexture = function (texture) {
  9496. var gl = this._gl;
  9497. if (texture._framebuffer) {
  9498. gl.deleteFramebuffer(texture._framebuffer);
  9499. }
  9500. if (texture._depthStencilBuffer) {
  9501. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9502. }
  9503. if (texture._MSAAFramebuffer) {
  9504. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9505. }
  9506. if (texture._MSAARenderBuffer) {
  9507. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9508. }
  9509. gl.deleteTexture(texture);
  9510. // Unbind channels
  9511. this.unbindAllTextures();
  9512. var index = this._loadedTexturesCache.indexOf(texture);
  9513. if (index !== -1) {
  9514. this._loadedTexturesCache.splice(index, 1);
  9515. }
  9516. };
  9517. Engine.prototype.setProgram = function (program) {
  9518. if (this._currentProgram !== program) {
  9519. this._gl.useProgram(program);
  9520. this._currentProgram = program;
  9521. }
  9522. };
  9523. Engine.prototype.bindSamplers = function (effect) {
  9524. this.setProgram(effect.getProgram());
  9525. var samplers = effect.getSamplers();
  9526. for (var index = 0; index < samplers.length; index++) {
  9527. var uniform = effect.getUniform(samplers[index]);
  9528. this._gl.uniform1i(uniform, index);
  9529. }
  9530. this._currentEffect = null;
  9531. };
  9532. Engine.prototype.activateTexture = function (texture) {
  9533. if (this._activeTexture !== texture) {
  9534. this._gl.activeTexture(texture);
  9535. this._activeTexture = texture;
  9536. }
  9537. };
  9538. Engine.prototype._bindTextureDirectly = function (target, texture) {
  9539. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  9540. this._gl.bindTexture(target, texture);
  9541. this._activeTexturesCache[this._activeTexture] = texture;
  9542. }
  9543. };
  9544. Engine.prototype._bindTexture = function (channel, texture) {
  9545. if (channel < 0) {
  9546. return;
  9547. }
  9548. this.activateTexture(this._gl.TEXTURE0 + channel);
  9549. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9550. };
  9551. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9552. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  9553. };
  9554. Engine.prototype.unbindAllTextures = function () {
  9555. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  9556. this.activateTexture(this._gl["TEXTURE" + channel]);
  9557. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9558. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9559. }
  9560. };
  9561. Engine.prototype.setTexture = function (channel, uniform, texture) {
  9562. if (channel < 0) {
  9563. return;
  9564. }
  9565. this._gl.uniform1i(uniform, channel);
  9566. this._setTexture(channel, texture);
  9567. };
  9568. Engine.prototype._setTexture = function (channel, texture) {
  9569. // Not ready?
  9570. if (!texture || !texture.isReady()) {
  9571. if (this._activeTexturesCache[channel] != null) {
  9572. this.activateTexture(this._gl["TEXTURE" + channel]);
  9573. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9574. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9575. }
  9576. return;
  9577. }
  9578. // Video
  9579. var alreadyActivated = false;
  9580. if (texture.video) {
  9581. this.activateTexture(this._gl["TEXTURE" + channel]);
  9582. alreadyActivated = true;
  9583. texture.update();
  9584. }
  9585. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  9586. texture.delayLoad();
  9587. return;
  9588. }
  9589. var internalTexture = texture.getInternalTexture();
  9590. if (this._activeTexturesCache[channel] === internalTexture) {
  9591. return;
  9592. }
  9593. if (!alreadyActivated) {
  9594. this.activateTexture(this._gl["TEXTURE" + channel]);
  9595. }
  9596. if (internalTexture.isCube) {
  9597. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  9598. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  9599. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  9600. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  9601. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  9602. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  9603. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  9604. }
  9605. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  9606. }
  9607. else {
  9608. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  9609. if (internalTexture._cachedWrapU !== texture.wrapU) {
  9610. internalTexture._cachedWrapU = texture.wrapU;
  9611. switch (texture.wrapU) {
  9612. case BABYLON.Texture.WRAP_ADDRESSMODE:
  9613. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  9614. break;
  9615. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  9616. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  9617. break;
  9618. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  9619. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  9620. break;
  9621. }
  9622. }
  9623. if (internalTexture._cachedWrapV !== texture.wrapV) {
  9624. internalTexture._cachedWrapV = texture.wrapV;
  9625. switch (texture.wrapV) {
  9626. case BABYLON.Texture.WRAP_ADDRESSMODE:
  9627. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  9628. break;
  9629. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  9630. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  9631. break;
  9632. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  9633. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  9634. break;
  9635. }
  9636. }
  9637. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  9638. }
  9639. };
  9640. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  9641. if (channel < 0) {
  9642. return;
  9643. }
  9644. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  9645. this._textureUnits = new Int32Array(textures.length);
  9646. }
  9647. for (var i = 0; i < textures.length; i++) {
  9648. this._textureUnits[i] = channel + i;
  9649. }
  9650. this._gl.uniform1iv(uniform, this._textureUnits);
  9651. for (var index = 0; index < textures.length; index++) {
  9652. this._setTexture(channel + index, textures[index]);
  9653. }
  9654. };
  9655. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  9656. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  9657. var value = texture.anisotropicFilteringLevel;
  9658. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9659. value = 1;
  9660. }
  9661. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  9662. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  9663. texture._cachedAnisotropicFilteringLevel = value;
  9664. }
  9665. };
  9666. Engine.prototype.readPixels = function (x, y, width, height) {
  9667. var data = new Uint8Array(height * width * 4);
  9668. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  9669. return data;
  9670. };
  9671. /**
  9672. * Add an externaly attached data from its key.
  9673. * This method call will fail and return false, if such key already exists.
  9674. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  9675. * @param key the unique key that identifies the data
  9676. * @param data the data object to associate to the key for this Engine instance
  9677. * @return true if no such key were already present and the data was added successfully, false otherwise
  9678. */
  9679. Engine.prototype.addExternalData = function (key, data) {
  9680. if (!this._externalData) {
  9681. this._externalData = new BABYLON.StringDictionary();
  9682. }
  9683. return this._externalData.add(key, data);
  9684. };
  9685. /**
  9686. * Get an externaly attached data from its key
  9687. * @param key the unique key that identifies the data
  9688. * @return the associated data, if present (can be null), or undefined if not present
  9689. */
  9690. Engine.prototype.getExternalData = function (key) {
  9691. if (!this._externalData) {
  9692. this._externalData = new BABYLON.StringDictionary();
  9693. }
  9694. return this._externalData.get(key);
  9695. };
  9696. /**
  9697. * Get an externaly attached data from its key, create it using a factory if it's not already present
  9698. * @param key the unique key that identifies the data
  9699. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  9700. * @return the associated data, can be null if the factory returned null.
  9701. */
  9702. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  9703. if (!this._externalData) {
  9704. this._externalData = new BABYLON.StringDictionary();
  9705. }
  9706. return this._externalData.getOrAddWithFactory(key, factory);
  9707. };
  9708. /**
  9709. * Remove an externaly attached data from the Engine instance
  9710. * @param key the unique key that identifies the data
  9711. * @return true if the data was successfully removed, false if it doesn't exist
  9712. */
  9713. Engine.prototype.removeExternalData = function (key) {
  9714. if (!this._externalData) {
  9715. this._externalData = new BABYLON.StringDictionary();
  9716. }
  9717. return this._externalData.remove(key);
  9718. };
  9719. Engine.prototype.releaseInternalTexture = function (texture) {
  9720. if (!texture) {
  9721. return;
  9722. }
  9723. texture.references--;
  9724. // Final reference ?
  9725. if (texture.references === 0) {
  9726. var texturesCache = this.getLoadedTexturesCache();
  9727. var index = texturesCache.indexOf(texture);
  9728. if (index > -1) {
  9729. texturesCache.splice(index, 1);
  9730. }
  9731. this._releaseTexture(texture);
  9732. }
  9733. };
  9734. Engine.prototype.unbindAllAttributes = function () {
  9735. if (this._mustWipeVertexAttributes) {
  9736. this._mustWipeVertexAttributes = false;
  9737. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9738. this._gl.disableVertexAttribArray(i);
  9739. this._vertexAttribArraysEnabled[i] = false;
  9740. this._currentBufferPointers[i] = null;
  9741. }
  9742. return;
  9743. }
  9744. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  9745. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  9746. continue;
  9747. }
  9748. this._gl.disableVertexAttribArray(i);
  9749. this._vertexAttribArraysEnabled[i] = false;
  9750. this._currentBufferPointers[i] = null;
  9751. }
  9752. };
  9753. Engine.prototype.releaseEffects = function () {
  9754. for (var name in this._compiledEffects) {
  9755. this._gl.deleteProgram(this._compiledEffects[name]._program);
  9756. }
  9757. this._compiledEffects = {};
  9758. };
  9759. // Dispose
  9760. Engine.prototype.dispose = function () {
  9761. this.hideLoadingUI();
  9762. this.stopRenderLoop();
  9763. // Release scenes
  9764. while (this.scenes.length) {
  9765. this.scenes[0].dispose();
  9766. }
  9767. // Release audio engine
  9768. Engine.audioEngine.dispose();
  9769. // Release effects
  9770. this.releaseEffects();
  9771. // Unbind
  9772. this.unbindAllAttributes();
  9773. this._gl = null;
  9774. //WebVR
  9775. this.disableVR();
  9776. // Events
  9777. window.removeEventListener("blur", this._onBlur);
  9778. window.removeEventListener("focus", this._onFocus);
  9779. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  9780. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  9781. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  9782. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  9783. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  9784. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  9785. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  9786. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  9787. // Remove from Instances
  9788. var index = Engine.Instances.indexOf(this);
  9789. if (index >= 0) {
  9790. Engine.Instances.splice(index, 1);
  9791. }
  9792. };
  9793. // Loading screen
  9794. Engine.prototype.displayLoadingUI = function () {
  9795. this.loadingScreen.displayLoadingUI();
  9796. };
  9797. Engine.prototype.hideLoadingUI = function () {
  9798. this.loadingScreen.hideLoadingUI();
  9799. };
  9800. Object.defineProperty(Engine.prototype, "loadingScreen", {
  9801. get: function () {
  9802. if (!this._loadingScreen)
  9803. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  9804. return this._loadingScreen;
  9805. },
  9806. set: function (loadingScreen) {
  9807. this._loadingScreen = loadingScreen;
  9808. },
  9809. enumerable: true,
  9810. configurable: true
  9811. });
  9812. Object.defineProperty(Engine.prototype, "loadingUIText", {
  9813. set: function (text) {
  9814. this.loadingScreen.loadingUIText = text;
  9815. },
  9816. enumerable: true,
  9817. configurable: true
  9818. });
  9819. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  9820. set: function (color) {
  9821. this.loadingScreen.loadingUIBackgroundColor = color;
  9822. },
  9823. enumerable: true,
  9824. configurable: true
  9825. });
  9826. Engine.prototype.attachContextLostEvent = function (callback) {
  9827. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  9828. };
  9829. Engine.prototype.attachContextRestoredEvent = function (callback) {
  9830. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  9831. };
  9832. Engine.prototype.getVertexShaderSource = function (program) {
  9833. var shaders = this._gl.getAttachedShaders(program);
  9834. return this._gl.getShaderSource(shaders[0]);
  9835. };
  9836. Engine.prototype.getFragmentShaderSource = function (program) {
  9837. var shaders = this._gl.getAttachedShaders(program);
  9838. return this._gl.getShaderSource(shaders[1]);
  9839. };
  9840. // FPS
  9841. Engine.prototype.getFps = function () {
  9842. return this.fps;
  9843. };
  9844. Engine.prototype.getDeltaTime = function () {
  9845. return this.deltaTime;
  9846. };
  9847. Engine.prototype._measureFps = function () {
  9848. this.previousFramesDuration.push(BABYLON.Tools.Now);
  9849. var length = this.previousFramesDuration.length;
  9850. if (length >= 2) {
  9851. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  9852. }
  9853. if (length >= this.fpsRange) {
  9854. if (length > this.fpsRange) {
  9855. this.previousFramesDuration.splice(0, 1);
  9856. length = this.previousFramesDuration.length;
  9857. }
  9858. var sum = 0;
  9859. for (var id = 0; id < length - 1; id++) {
  9860. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  9861. }
  9862. this.fps = 1000.0 / (sum / (length - 1));
  9863. }
  9864. };
  9865. Engine.prototype._canRenderToFloatFramebuffer = function () {
  9866. if (this._webGLVersion > 1) {
  9867. return this._caps.colorBufferFloat;
  9868. }
  9869. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  9870. };
  9871. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  9872. if (this._webGLVersion > 1) {
  9873. return this._caps.colorBufferFloat;
  9874. }
  9875. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  9876. };
  9877. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9878. Engine.prototype._canRenderToFramebuffer = function (type) {
  9879. var gl = this._gl;
  9880. //clear existing errors
  9881. while (gl.getError() !== gl.NO_ERROR) { }
  9882. var successful = true;
  9883. var texture = gl.createTexture();
  9884. gl.bindTexture(gl.TEXTURE_2D, texture);
  9885. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9886. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9887. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9888. var fb = gl.createFramebuffer();
  9889. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9890. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9891. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9892. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  9893. successful = successful && (gl.getError() === gl.NO_ERROR);
  9894. //try render by clearing frame buffer's color buffer
  9895. if (successful) {
  9896. gl.clear(gl.COLOR_BUFFER_BIT);
  9897. successful = successful && (gl.getError() === gl.NO_ERROR);
  9898. }
  9899. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  9900. if (successful) {
  9901. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  9902. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9903. var readFormat = gl.RGBA;
  9904. var readType = gl.UNSIGNED_BYTE;
  9905. var buffer = new Uint8Array(4);
  9906. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  9907. successful = successful && (gl.getError() === gl.NO_ERROR);
  9908. }
  9909. //clean up
  9910. gl.deleteTexture(texture);
  9911. gl.deleteFramebuffer(fb);
  9912. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9913. //clear accumulated errors
  9914. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  9915. return successful;
  9916. };
  9917. Engine.prototype._getWebGLTextureType = function (type) {
  9918. if (type === Engine.TEXTURETYPE_FLOAT) {
  9919. return this._gl.FLOAT;
  9920. }
  9921. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9922. // Add Half Float Constant.
  9923. return Engine.HALF_FLOAT_OES;
  9924. }
  9925. return this._gl.UNSIGNED_BYTE;
  9926. };
  9927. ;
  9928. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  9929. if (this._webGLVersion === 1) {
  9930. return this._gl.RGBA;
  9931. }
  9932. if (type === Engine.TEXTURETYPE_FLOAT) {
  9933. return Engine.RGBA32F;
  9934. }
  9935. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9936. return Engine.RGBA16F;
  9937. }
  9938. return this._gl.RGBA;
  9939. };
  9940. ;
  9941. // Statics
  9942. Engine.isSupported = function () {
  9943. try {
  9944. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  9945. if (navigator.isCocoonJS) {
  9946. return true;
  9947. }
  9948. var tempcanvas = document.createElement("canvas");
  9949. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  9950. return gl != null && !!window.WebGLRenderingContext;
  9951. }
  9952. catch (e) {
  9953. return false;
  9954. }
  9955. };
  9956. return Engine;
  9957. }());
  9958. Engine.Instances = new Array();
  9959. // Const statics
  9960. Engine._ALPHA_DISABLE = 0;
  9961. Engine._ALPHA_ADD = 1;
  9962. Engine._ALPHA_COMBINE = 2;
  9963. Engine._ALPHA_SUBTRACT = 3;
  9964. Engine._ALPHA_MULTIPLY = 4;
  9965. Engine._ALPHA_MAXIMIZED = 5;
  9966. Engine._ALPHA_ONEONE = 6;
  9967. Engine._ALPHA_PREMULTIPLIED = 7;
  9968. Engine._DELAYLOADSTATE_NONE = 0;
  9969. Engine._DELAYLOADSTATE_LOADED = 1;
  9970. Engine._DELAYLOADSTATE_LOADING = 2;
  9971. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9972. Engine._TEXTUREFORMAT_ALPHA = 0;
  9973. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9974. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9975. Engine._TEXTUREFORMAT_RGB = 4;
  9976. Engine._TEXTUREFORMAT_RGBA = 5;
  9977. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9978. Engine._TEXTURETYPE_FLOAT = 1;
  9979. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9980. // Depht or Stencil test Constants.
  9981. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9982. 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.
  9983. 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.
  9984. 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.
  9985. 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.
  9986. 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.
  9987. 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.
  9988. 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.
  9989. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9990. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9991. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9992. // Stencil Actions Constants.
  9993. Engine._KEEP = 0x1E00;
  9994. Engine._REPLACE = 0x1E01;
  9995. Engine._INCR = 0x1E02;
  9996. Engine._DECR = 0x1E03;
  9997. Engine._INVERT = 0x150A;
  9998. Engine._INCR_WRAP = 0x8507;
  9999. Engine._DECR_WRAP = 0x8508;
  10000. // Updatable statics so stick with vars here
  10001. Engine.CollisionsEpsilon = 0.001;
  10002. Engine.CodeRepository = "src/";
  10003. Engine.ShadersRepository = "src/Shaders/";
  10004. BABYLON.Engine = Engine;
  10005. })(BABYLON || (BABYLON = {}));
  10006. //# sourceMappingURL=babylon.engine.js.map
  10007. /// <reference path="Tools\babylon.decorators.ts" />
  10008. var BABYLON;
  10009. (function (BABYLON) {
  10010. /**
  10011. * Node is the basic class for all scene objects (Mesh, Light Camera).
  10012. */
  10013. var Node = (function () {
  10014. /**
  10015. * @constructor
  10016. * @param {string} name - the name and id to be given to this node
  10017. * @param {BABYLON.Scene} the scene this node will be added to
  10018. */
  10019. function Node(name, scene) {
  10020. this.state = "";
  10021. this.metadata = null;
  10022. this.doNotSerialize = false;
  10023. this.animations = new Array();
  10024. this._ranges = {};
  10025. this._childrenFlag = -1;
  10026. this._isEnabled = true;
  10027. this._isReady = true;
  10028. this._currentRenderId = -1;
  10029. this._parentRenderId = -1;
  10030. /**
  10031. * An event triggered when the mesh is disposed.
  10032. * @type {BABYLON.Observable}
  10033. */
  10034. this.onDisposeObservable = new BABYLON.Observable();
  10035. this.name = name;
  10036. this.id = name;
  10037. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10038. this._initCache();
  10039. }
  10040. Object.defineProperty(Node.prototype, "parent", {
  10041. get: function () {
  10042. return this._parentNode;
  10043. },
  10044. set: function (parent) {
  10045. if (this._parentNode === parent) {
  10046. return;
  10047. }
  10048. if (this._parentNode) {
  10049. var index = this._parentNode._children.indexOf(this);
  10050. if (index !== -1) {
  10051. this._parentNode._children.splice(index, 1);
  10052. }
  10053. }
  10054. this._parentNode = parent;
  10055. if (this._parentNode) {
  10056. if (!this._parentNode._children) {
  10057. this._parentNode._children = new Array();
  10058. }
  10059. this._parentNode._children.push(this);
  10060. }
  10061. },
  10062. enumerable: true,
  10063. configurable: true
  10064. });
  10065. Node.prototype.getClassName = function () {
  10066. return "Node";
  10067. };
  10068. Object.defineProperty(Node.prototype, "onDispose", {
  10069. set: function (callback) {
  10070. if (this._onDisposeObserver) {
  10071. this.onDisposeObservable.remove(this._onDisposeObserver);
  10072. }
  10073. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10074. },
  10075. enumerable: true,
  10076. configurable: true
  10077. });
  10078. Node.prototype.getScene = function () {
  10079. return this._scene;
  10080. };
  10081. Node.prototype.getEngine = function () {
  10082. return this._scene.getEngine();
  10083. };
  10084. // override it in derived class
  10085. Node.prototype.getWorldMatrix = function () {
  10086. return BABYLON.Matrix.Identity();
  10087. };
  10088. // override it in derived class if you add new variables to the cache
  10089. // and call the parent class method
  10090. Node.prototype._initCache = function () {
  10091. this._cache = {};
  10092. this._cache.parent = undefined;
  10093. };
  10094. Node.prototype.updateCache = function (force) {
  10095. if (!force && this.isSynchronized())
  10096. return;
  10097. this._cache.parent = this.parent;
  10098. this._updateCache();
  10099. };
  10100. // override it in derived class if you add new variables to the cache
  10101. // and call the parent class method if !ignoreParentClass
  10102. Node.prototype._updateCache = function (ignoreParentClass) {
  10103. };
  10104. // override it in derived class if you add new variables to the cache
  10105. Node.prototype._isSynchronized = function () {
  10106. return true;
  10107. };
  10108. Node.prototype._markSyncedWithParent = function () {
  10109. this._parentRenderId = this.parent._currentRenderId;
  10110. };
  10111. Node.prototype.isSynchronizedWithParent = function () {
  10112. if (!this.parent) {
  10113. return true;
  10114. }
  10115. if (this._parentRenderId !== this.parent._currentRenderId) {
  10116. return false;
  10117. }
  10118. return this.parent.isSynchronized();
  10119. };
  10120. Node.prototype.isSynchronized = function (updateCache) {
  10121. var check = this.hasNewParent();
  10122. check = check || !this.isSynchronizedWithParent();
  10123. check = check || !this._isSynchronized();
  10124. if (updateCache)
  10125. this.updateCache(true);
  10126. return !check;
  10127. };
  10128. Node.prototype.hasNewParent = function (update) {
  10129. if (this._cache.parent === this.parent)
  10130. return false;
  10131. if (update)
  10132. this._cache.parent = this.parent;
  10133. return true;
  10134. };
  10135. /**
  10136. * Is this node ready to be used/rendered
  10137. * @return {boolean} is it ready
  10138. */
  10139. Node.prototype.isReady = function () {
  10140. return this._isReady;
  10141. };
  10142. /**
  10143. * Is this node enabled.
  10144. * If the node has a parent and is enabled, the parent will be inspected as well.
  10145. * @return {boolean} whether this node (and its parent) is enabled.
  10146. * @see setEnabled
  10147. */
  10148. Node.prototype.isEnabled = function () {
  10149. if (!this._isEnabled) {
  10150. return false;
  10151. }
  10152. if (this.parent) {
  10153. return this.parent.isEnabled();
  10154. }
  10155. return true;
  10156. };
  10157. /**
  10158. * Set the enabled state of this node.
  10159. * @param {boolean} value - the new enabled state
  10160. * @see isEnabled
  10161. */
  10162. Node.prototype.setEnabled = function (value) {
  10163. this._isEnabled = value;
  10164. };
  10165. /**
  10166. * Is this node a descendant of the given node.
  10167. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10168. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10169. * @see parent
  10170. */
  10171. Node.prototype.isDescendantOf = function (ancestor) {
  10172. if (this.parent) {
  10173. if (this.parent === ancestor) {
  10174. return true;
  10175. }
  10176. return this.parent.isDescendantOf(ancestor);
  10177. }
  10178. return false;
  10179. };
  10180. /**
  10181. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10182. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10183. * @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.
  10184. * @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.
  10185. */
  10186. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10187. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10188. if (!this._children) {
  10189. return;
  10190. }
  10191. for (var index = 0; index < this._children.length; index++) {
  10192. var item = this._children[index];
  10193. if (!predicate || predicate(item)) {
  10194. results.push(item);
  10195. }
  10196. if (!directDescendantsOnly) {
  10197. item._getDescendants(results, false, predicate);
  10198. }
  10199. }
  10200. };
  10201. /**
  10202. * Will return all nodes that have this node as ascendant.
  10203. * @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.
  10204. * @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.
  10205. * @return {BABYLON.Node[]} all children nodes of all types.
  10206. */
  10207. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10208. var results = [];
  10209. this._getDescendants(results, directDescendantsOnly, predicate);
  10210. return results;
  10211. };
  10212. /**
  10213. * Get all child-meshes of this node.
  10214. */
  10215. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10216. var results = [];
  10217. this._getDescendants(results, directDecendantsOnly, function (node) {
  10218. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10219. });
  10220. return results;
  10221. };
  10222. /**
  10223. * Get all direct children of this node.
  10224. */
  10225. Node.prototype.getChildren = function (predicate) {
  10226. return this.getDescendants(true, predicate);
  10227. };
  10228. Node.prototype._setReady = function (state) {
  10229. if (state === this._isReady) {
  10230. return;
  10231. }
  10232. if (!state) {
  10233. this._isReady = false;
  10234. return;
  10235. }
  10236. this._isReady = true;
  10237. if (this.onReady) {
  10238. this.onReady(this);
  10239. }
  10240. };
  10241. Node.prototype.getAnimationByName = function (name) {
  10242. for (var i = 0; i < this.animations.length; i++) {
  10243. var animation = this.animations[i];
  10244. if (animation.name === name) {
  10245. return animation;
  10246. }
  10247. }
  10248. return null;
  10249. };
  10250. Node.prototype.createAnimationRange = function (name, from, to) {
  10251. // check name not already in use
  10252. if (!this._ranges[name]) {
  10253. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10254. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10255. if (this.animations[i]) {
  10256. this.animations[i].createRange(name, from, to);
  10257. }
  10258. }
  10259. }
  10260. };
  10261. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10262. if (deleteFrames === void 0) { deleteFrames = true; }
  10263. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10264. if (this.animations[i]) {
  10265. this.animations[i].deleteRange(name, deleteFrames);
  10266. }
  10267. }
  10268. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10269. };
  10270. Node.prototype.getAnimationRange = function (name) {
  10271. return this._ranges[name];
  10272. };
  10273. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10274. var range = this.getAnimationRange(name);
  10275. if (!range) {
  10276. return null;
  10277. }
  10278. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10279. };
  10280. Node.prototype.serializeAnimationRanges = function () {
  10281. var serializationRanges = [];
  10282. for (var name in this._ranges) {
  10283. var range = {};
  10284. range.name = name;
  10285. range.from = this._ranges[name].from;
  10286. range.to = this._ranges[name].to;
  10287. serializationRanges.push(range);
  10288. }
  10289. return serializationRanges;
  10290. };
  10291. Node.prototype.dispose = function () {
  10292. this.parent = null;
  10293. // Callback
  10294. this.onDisposeObservable.notifyObservers(this);
  10295. this.onDisposeObservable.clear();
  10296. };
  10297. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10298. if (parsedNode.ranges) {
  10299. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10300. var data = parsedNode.ranges[index];
  10301. node.createAnimationRange(data.name, data.from, data.to);
  10302. }
  10303. }
  10304. };
  10305. return Node;
  10306. }());
  10307. __decorate([
  10308. BABYLON.serialize()
  10309. ], Node.prototype, "name", void 0);
  10310. __decorate([
  10311. BABYLON.serialize()
  10312. ], Node.prototype, "id", void 0);
  10313. __decorate([
  10314. BABYLON.serialize()
  10315. ], Node.prototype, "uniqueId", void 0);
  10316. __decorate([
  10317. BABYLON.serialize()
  10318. ], Node.prototype, "state", void 0);
  10319. __decorate([
  10320. BABYLON.serialize()
  10321. ], Node.prototype, "metadata", void 0);
  10322. BABYLON.Node = Node;
  10323. })(BABYLON || (BABYLON = {}));
  10324. //# sourceMappingURL=babylon.node.js.map
  10325. var BABYLON;
  10326. (function (BABYLON) {
  10327. var BoundingSphere = (function () {
  10328. function BoundingSphere(minimum, maximum) {
  10329. this.minimum = minimum;
  10330. this.maximum = maximum;
  10331. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10332. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10333. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10334. this.radius = distance * 0.5;
  10335. this.centerWorld = BABYLON.Vector3.Zero();
  10336. this._update(BABYLON.Matrix.Identity());
  10337. }
  10338. // Methods
  10339. BoundingSphere.prototype._update = function (world) {
  10340. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10341. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10342. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10343. };
  10344. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10345. for (var i = 0; i < 6; i++) {
  10346. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10347. return false;
  10348. }
  10349. return true;
  10350. };
  10351. BoundingSphere.prototype.intersectsPoint = function (point) {
  10352. var x = this.centerWorld.x - point.x;
  10353. var y = this.centerWorld.y - point.y;
  10354. var z = this.centerWorld.z - point.z;
  10355. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10356. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10357. return false;
  10358. return true;
  10359. };
  10360. // Statics
  10361. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10362. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10363. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10364. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10365. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10366. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10367. return false;
  10368. return true;
  10369. };
  10370. return BoundingSphere;
  10371. }());
  10372. BABYLON.BoundingSphere = BoundingSphere;
  10373. })(BABYLON || (BABYLON = {}));
  10374. //# sourceMappingURL=babylon.boundingSphere.js.map
  10375. var BABYLON;
  10376. (function (BABYLON) {
  10377. var BoundingBox = (function () {
  10378. function BoundingBox(minimum, maximum) {
  10379. this.minimum = minimum;
  10380. this.maximum = maximum;
  10381. this.vectors = new Array();
  10382. this.vectorsWorld = new Array();
  10383. // Bounding vectors
  10384. this.vectors.push(this.minimum.clone());
  10385. this.vectors.push(this.maximum.clone());
  10386. this.vectors.push(this.minimum.clone());
  10387. this.vectors[2].x = this.maximum.x;
  10388. this.vectors.push(this.minimum.clone());
  10389. this.vectors[3].y = this.maximum.y;
  10390. this.vectors.push(this.minimum.clone());
  10391. this.vectors[4].z = this.maximum.z;
  10392. this.vectors.push(this.maximum.clone());
  10393. this.vectors[5].z = this.minimum.z;
  10394. this.vectors.push(this.maximum.clone());
  10395. this.vectors[6].x = this.minimum.x;
  10396. this.vectors.push(this.maximum.clone());
  10397. this.vectors[7].y = this.minimum.y;
  10398. // OBB
  10399. this.center = this.maximum.add(this.minimum).scale(0.5);
  10400. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10401. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10402. // World
  10403. for (var index = 0; index < this.vectors.length; index++) {
  10404. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10405. }
  10406. this.minimumWorld = BABYLON.Vector3.Zero();
  10407. this.maximumWorld = BABYLON.Vector3.Zero();
  10408. this.centerWorld = BABYLON.Vector3.Zero();
  10409. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10410. this._update(BABYLON.Matrix.Identity());
  10411. }
  10412. // Methods
  10413. BoundingBox.prototype.getWorldMatrix = function () {
  10414. return this._worldMatrix;
  10415. };
  10416. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10417. this._worldMatrix.copyFrom(matrix);
  10418. return this;
  10419. };
  10420. BoundingBox.prototype._update = function (world) {
  10421. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10422. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10423. for (var index = 0; index < this.vectors.length; index++) {
  10424. var v = this.vectorsWorld[index];
  10425. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10426. if (v.x < this.minimumWorld.x)
  10427. this.minimumWorld.x = v.x;
  10428. if (v.y < this.minimumWorld.y)
  10429. this.minimumWorld.y = v.y;
  10430. if (v.z < this.minimumWorld.z)
  10431. this.minimumWorld.z = v.z;
  10432. if (v.x > this.maximumWorld.x)
  10433. this.maximumWorld.x = v.x;
  10434. if (v.y > this.maximumWorld.y)
  10435. this.maximumWorld.y = v.y;
  10436. if (v.z > this.maximumWorld.z)
  10437. this.maximumWorld.z = v.z;
  10438. }
  10439. // Extend
  10440. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10441. this.extendSizeWorld.scaleInPlace(0.5);
  10442. // OBB
  10443. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10444. this.centerWorld.scaleInPlace(0.5);
  10445. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10446. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10447. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10448. this._worldMatrix = world;
  10449. };
  10450. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10451. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  10452. };
  10453. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10454. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  10455. };
  10456. BoundingBox.prototype.intersectsPoint = function (point) {
  10457. var delta = -BABYLON.Epsilon;
  10458. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  10459. return false;
  10460. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  10461. return false;
  10462. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  10463. return false;
  10464. return true;
  10465. };
  10466. BoundingBox.prototype.intersectsSphere = function (sphere) {
  10467. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  10468. };
  10469. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  10470. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  10471. return false;
  10472. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  10473. return false;
  10474. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  10475. return false;
  10476. return true;
  10477. };
  10478. // Statics
  10479. BoundingBox.Intersects = function (box0, box1) {
  10480. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  10481. return false;
  10482. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  10483. return false;
  10484. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  10485. return false;
  10486. return true;
  10487. };
  10488. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  10489. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  10490. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  10491. return (num <= (sphereRadius * sphereRadius));
  10492. };
  10493. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  10494. for (var p = 0; p < 6; p++) {
  10495. for (var i = 0; i < 8; i++) {
  10496. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10497. return false;
  10498. }
  10499. }
  10500. }
  10501. return true;
  10502. };
  10503. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  10504. for (var p = 0; p < 6; p++) {
  10505. var inCount = 8;
  10506. for (var i = 0; i < 8; i++) {
  10507. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10508. --inCount;
  10509. }
  10510. else {
  10511. break;
  10512. }
  10513. }
  10514. if (inCount === 0)
  10515. return false;
  10516. }
  10517. return true;
  10518. };
  10519. return BoundingBox;
  10520. }());
  10521. BABYLON.BoundingBox = BoundingBox;
  10522. })(BABYLON || (BABYLON = {}));
  10523. //# sourceMappingURL=babylon.boundingBox.js.map
  10524. var BABYLON;
  10525. (function (BABYLON) {
  10526. var computeBoxExtents = function (axis, box) {
  10527. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  10528. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  10529. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  10530. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  10531. var r = r0 + r1 + r2;
  10532. return {
  10533. min: p - r,
  10534. max: p + r
  10535. };
  10536. };
  10537. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  10538. var axisOverlap = function (axis, box0, box1) {
  10539. var result0 = computeBoxExtents(axis, box0);
  10540. var result1 = computeBoxExtents(axis, box1);
  10541. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  10542. };
  10543. var BoundingInfo = (function () {
  10544. function BoundingInfo(minimum, maximum) {
  10545. this.minimum = minimum;
  10546. this.maximum = maximum;
  10547. this._isLocked = false;
  10548. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  10549. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  10550. }
  10551. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  10552. get: function () {
  10553. return this._isLocked;
  10554. },
  10555. set: function (value) {
  10556. this._isLocked = value;
  10557. },
  10558. enumerable: true,
  10559. configurable: true
  10560. });
  10561. // Methods
  10562. BoundingInfo.prototype.update = function (world) {
  10563. if (this._isLocked) {
  10564. return;
  10565. }
  10566. this.boundingBox._update(world);
  10567. this.boundingSphere._update(world);
  10568. };
  10569. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  10570. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  10571. return false;
  10572. return this.boundingBox.isInFrustum(frustumPlanes);
  10573. };
  10574. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10575. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  10576. };
  10577. BoundingInfo.prototype._checkCollision = function (collider) {
  10578. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  10579. };
  10580. BoundingInfo.prototype.intersectsPoint = function (point) {
  10581. if (!this.boundingSphere.centerWorld) {
  10582. return false;
  10583. }
  10584. if (!this.boundingSphere.intersectsPoint(point)) {
  10585. return false;
  10586. }
  10587. if (!this.boundingBox.intersectsPoint(point)) {
  10588. return false;
  10589. }
  10590. return true;
  10591. };
  10592. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  10593. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  10594. return false;
  10595. }
  10596. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  10597. return false;
  10598. }
  10599. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  10600. return false;
  10601. }
  10602. if (!precise) {
  10603. return true;
  10604. }
  10605. var box0 = this.boundingBox;
  10606. var box1 = boundingInfo.boundingBox;
  10607. if (!axisOverlap(box0.directions[0], box0, box1))
  10608. return false;
  10609. if (!axisOverlap(box0.directions[1], box0, box1))
  10610. return false;
  10611. if (!axisOverlap(box0.directions[2], box0, box1))
  10612. return false;
  10613. if (!axisOverlap(box1.directions[0], box0, box1))
  10614. return false;
  10615. if (!axisOverlap(box1.directions[1], box0, box1))
  10616. return false;
  10617. if (!axisOverlap(box1.directions[2], box0, box1))
  10618. return false;
  10619. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  10620. return false;
  10621. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  10622. return false;
  10623. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  10624. return false;
  10625. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  10626. return false;
  10627. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  10628. return false;
  10629. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  10630. return false;
  10631. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  10632. return false;
  10633. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  10634. return false;
  10635. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  10636. return false;
  10637. return true;
  10638. };
  10639. return BoundingInfo;
  10640. }());
  10641. BABYLON.BoundingInfo = BoundingInfo;
  10642. })(BABYLON || (BABYLON = {}));
  10643. //# sourceMappingURL=babylon.boundingInfo.js.map
  10644. var BABYLON;
  10645. (function (BABYLON) {
  10646. var AbstractMesh = (function (_super) {
  10647. __extends(AbstractMesh, _super);
  10648. // Constructor
  10649. function AbstractMesh(name, scene) {
  10650. var _this = _super.call(this, name, scene) || this;
  10651. _this._facetNb = 0; // facet number
  10652. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  10653. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  10654. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  10655. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  10656. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  10657. _this._subDiv = {
  10658. max: 1,
  10659. X: 1,
  10660. Y: 1,
  10661. Z: 1
  10662. };
  10663. // Events
  10664. /**
  10665. * An event triggered when this mesh collides with another one
  10666. * @type {BABYLON.Observable}
  10667. */
  10668. _this.onCollideObservable = new BABYLON.Observable();
  10669. /**
  10670. * An event triggered when the collision's position changes
  10671. * @type {BABYLON.Observable}
  10672. */
  10673. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10674. /**
  10675. * An event triggered after the world matrix is updated
  10676. * @type {BABYLON.Observable}
  10677. */
  10678. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10679. // Properties
  10680. _this.definedFacingForward = true; // orientation for POV movement & rotation
  10681. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10682. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10683. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  10684. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10685. _this.visibility = 1.0;
  10686. _this.alphaIndex = Number.MAX_VALUE;
  10687. _this.infiniteDistance = false;
  10688. _this.isVisible = true;
  10689. _this.isPickable = true;
  10690. _this.showBoundingBox = false;
  10691. _this.showSubMeshesBoundingBox = false;
  10692. _this.isBlocker = false;
  10693. _this.renderingGroupId = 0;
  10694. _this._receiveShadows = false;
  10695. _this.renderOutline = false;
  10696. _this.outlineColor = BABYLON.Color3.Red();
  10697. _this.outlineWidth = 0.02;
  10698. _this.renderOverlay = false;
  10699. _this.overlayColor = BABYLON.Color3.Red();
  10700. _this.overlayAlpha = 0.5;
  10701. _this._hasVertexAlpha = false;
  10702. _this._useVertexColors = true;
  10703. _this._computeBonesUsingShaders = true;
  10704. _this._numBoneInfluencers = 4;
  10705. _this._applyFog = true;
  10706. _this.scalingDeterminant = 1;
  10707. _this.useOctreeForRenderingSelection = true;
  10708. _this.useOctreeForPicking = true;
  10709. _this.useOctreeForCollisions = true;
  10710. _this.layerMask = 0x0FFFFFFF;
  10711. /**
  10712. * True if the mesh must be rendered in any case.
  10713. */
  10714. _this.alwaysSelectAsActiveMesh = false;
  10715. // Collisions
  10716. _this._checkCollisions = false;
  10717. _this._collisionMask = -1;
  10718. _this._collisionGroup = -1;
  10719. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10720. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10721. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10722. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10723. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10724. // Edges
  10725. _this.edgesWidth = 1;
  10726. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10727. // Cache
  10728. _this._localWorld = BABYLON.Matrix.Zero();
  10729. _this._worldMatrix = BABYLON.Matrix.Zero();
  10730. _this._absolutePosition = BABYLON.Vector3.Zero();
  10731. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10732. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10733. _this._isDirty = false;
  10734. _this._pivotMatrix = BABYLON.Matrix.Identity();
  10735. _this._isDisposed = false;
  10736. _this._renderId = 0;
  10737. _this._intersectionsInProgress = new Array();
  10738. _this._isWorldMatrixFrozen = false;
  10739. _this._unIndexed = false;
  10740. _this._lightSources = new Array();
  10741. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10742. if (collidedMesh === void 0) { collidedMesh = null; }
  10743. //TODO move this to the collision coordinator!
  10744. if (_this.getScene().workerCollisions)
  10745. newPosition.multiplyInPlace(_this._collider.radius);
  10746. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10747. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10748. _this.position.addInPlace(_this._diffPositionForCollisions);
  10749. }
  10750. if (collidedMesh) {
  10751. _this.onCollideObservable.notifyObservers(collidedMesh);
  10752. }
  10753. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10754. };
  10755. _this.getScene().addMesh(_this);
  10756. _this._resyncLightSources();
  10757. return _this;
  10758. }
  10759. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10760. get: function () {
  10761. return AbstractMesh._BILLBOARDMODE_NONE;
  10762. },
  10763. enumerable: true,
  10764. configurable: true
  10765. });
  10766. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10767. get: function () {
  10768. return AbstractMesh._BILLBOARDMODE_X;
  10769. },
  10770. enumerable: true,
  10771. configurable: true
  10772. });
  10773. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10774. get: function () {
  10775. return AbstractMesh._BILLBOARDMODE_Y;
  10776. },
  10777. enumerable: true,
  10778. configurable: true
  10779. });
  10780. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10781. get: function () {
  10782. return AbstractMesh._BILLBOARDMODE_Z;
  10783. },
  10784. enumerable: true,
  10785. configurable: true
  10786. });
  10787. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10788. get: function () {
  10789. return AbstractMesh._BILLBOARDMODE_ALL;
  10790. },
  10791. enumerable: true,
  10792. configurable: true
  10793. });
  10794. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  10795. /**
  10796. * Read-only : the number of facets in the mesh
  10797. */
  10798. get: function () {
  10799. return this._facetNb;
  10800. },
  10801. enumerable: true,
  10802. configurable: true
  10803. });
  10804. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  10805. /**
  10806. * The number (integer) of subdivisions per axis in the partioning space
  10807. */
  10808. get: function () {
  10809. return this._partitioningSubdivisions;
  10810. },
  10811. set: function (nb) {
  10812. this._partitioningSubdivisions = nb;
  10813. },
  10814. enumerable: true,
  10815. configurable: true
  10816. });
  10817. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  10818. /**
  10819. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  10820. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  10821. */
  10822. get: function () {
  10823. return this._partitioningBBoxRatio;
  10824. },
  10825. set: function (ratio) {
  10826. this._partitioningBBoxRatio = ratio;
  10827. },
  10828. enumerable: true,
  10829. configurable: true
  10830. });
  10831. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  10832. /**
  10833. * Read-only boolean : is the feature facetData enabled ?
  10834. */
  10835. get: function () {
  10836. return this._facetDataEnabled;
  10837. },
  10838. enumerable: true,
  10839. configurable: true
  10840. });
  10841. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10842. set: function (callback) {
  10843. if (this._onCollideObserver) {
  10844. this.onCollideObservable.remove(this._onCollideObserver);
  10845. }
  10846. this._onCollideObserver = this.onCollideObservable.add(callback);
  10847. },
  10848. enumerable: true,
  10849. configurable: true
  10850. });
  10851. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10852. set: function (callback) {
  10853. if (this._onCollisionPositionChangeObserver) {
  10854. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10855. }
  10856. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10857. },
  10858. enumerable: true,
  10859. configurable: true
  10860. });
  10861. Object.defineProperty(AbstractMesh.prototype, "material", {
  10862. get: function () {
  10863. return this._material;
  10864. },
  10865. set: function (value) {
  10866. if (this._material === value) {
  10867. return;
  10868. }
  10869. this._material = value;
  10870. if (!this.subMeshes) {
  10871. return;
  10872. }
  10873. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  10874. var subMesh = _a[_i];
  10875. subMesh.setEffect(null);
  10876. }
  10877. },
  10878. enumerable: true,
  10879. configurable: true
  10880. });
  10881. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  10882. get: function () {
  10883. return this._receiveShadows;
  10884. },
  10885. set: function (value) {
  10886. if (this._receiveShadows === value) {
  10887. return;
  10888. }
  10889. this._receiveShadows = value;
  10890. this._markSubMeshesAsLightDirty();
  10891. },
  10892. enumerable: true,
  10893. configurable: true
  10894. });
  10895. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  10896. get: function () {
  10897. return this._hasVertexAlpha;
  10898. },
  10899. set: function (value) {
  10900. if (this._hasVertexAlpha === value) {
  10901. return;
  10902. }
  10903. this._hasVertexAlpha = value;
  10904. this._markSubMeshesAsAttributesDirty();
  10905. },
  10906. enumerable: true,
  10907. configurable: true
  10908. });
  10909. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  10910. get: function () {
  10911. return this._useVertexColors;
  10912. },
  10913. set: function (value) {
  10914. if (this._useVertexColors === value) {
  10915. return;
  10916. }
  10917. this._useVertexColors = value;
  10918. this._markSubMeshesAsAttributesDirty();
  10919. },
  10920. enumerable: true,
  10921. configurable: true
  10922. });
  10923. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  10924. get: function () {
  10925. return this._computeBonesUsingShaders;
  10926. },
  10927. set: function (value) {
  10928. if (this._computeBonesUsingShaders === value) {
  10929. return;
  10930. }
  10931. this._computeBonesUsingShaders = value;
  10932. this._markSubMeshesAsAttributesDirty();
  10933. },
  10934. enumerable: true,
  10935. configurable: true
  10936. });
  10937. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  10938. get: function () {
  10939. return this._numBoneInfluencers;
  10940. },
  10941. set: function (value) {
  10942. if (this._numBoneInfluencers === value) {
  10943. return;
  10944. }
  10945. this._numBoneInfluencers = value;
  10946. this._markSubMeshesAsAttributesDirty();
  10947. },
  10948. enumerable: true,
  10949. configurable: true
  10950. });
  10951. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  10952. get: function () {
  10953. return this._applyFog;
  10954. },
  10955. set: function (value) {
  10956. if (this._applyFog === value) {
  10957. return;
  10958. }
  10959. this._applyFog = value;
  10960. this._markSubMeshesAsMiscDirty();
  10961. },
  10962. enumerable: true,
  10963. configurable: true
  10964. });
  10965. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  10966. get: function () {
  10967. return this._collisionMask;
  10968. },
  10969. set: function (mask) {
  10970. this._collisionMask = !isNaN(mask) ? mask : -1;
  10971. },
  10972. enumerable: true,
  10973. configurable: true
  10974. });
  10975. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  10976. get: function () {
  10977. return this._collisionGroup;
  10978. },
  10979. set: function (mask) {
  10980. this._collisionGroup = !isNaN(mask) ? mask : -1;
  10981. },
  10982. enumerable: true,
  10983. configurable: true
  10984. });
  10985. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10986. get: function () {
  10987. return this._skeleton;
  10988. },
  10989. set: function (value) {
  10990. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10991. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10992. }
  10993. if (value && value.needInitialSkinMatrix) {
  10994. value._registerMeshWithPoseMatrix(this);
  10995. }
  10996. this._skeleton = value;
  10997. if (!this._skeleton) {
  10998. this._bonesTransformMatrices = null;
  10999. }
  11000. this._markSubMeshesAsAttributesDirty();
  11001. },
  11002. enumerable: true,
  11003. configurable: true
  11004. });
  11005. /**
  11006. * Returns the string "AbstractMesh"
  11007. */
  11008. AbstractMesh.prototype.getClassName = function () {
  11009. return "AbstractMesh";
  11010. };
  11011. /**
  11012. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11013. */
  11014. AbstractMesh.prototype.toString = function (fullDetails) {
  11015. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  11016. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  11017. if (this._skeleton) {
  11018. ret += ", skeleton: " + this._skeleton.name;
  11019. }
  11020. if (fullDetails) {
  11021. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  11022. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  11023. }
  11024. return ret;
  11025. };
  11026. AbstractMesh.prototype._resyncLightSources = function () {
  11027. this._lightSources.length = 0;
  11028. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  11029. var light = _a[_i];
  11030. if (!light.isEnabled()) {
  11031. continue;
  11032. }
  11033. if (light.canAffectMesh(this)) {
  11034. this._lightSources.push(light);
  11035. }
  11036. }
  11037. this._markSubMeshesAsLightDirty();
  11038. };
  11039. AbstractMesh.prototype._resyncLighSource = function (light) {
  11040. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11041. var index = this._lightSources.indexOf(light);
  11042. if (index === -1) {
  11043. if (!isIn) {
  11044. return;
  11045. }
  11046. this._lightSources.push(light);
  11047. }
  11048. else {
  11049. if (isIn) {
  11050. return;
  11051. }
  11052. this._lightSources.splice(index, 1);
  11053. }
  11054. this._markSubMeshesAsLightDirty();
  11055. };
  11056. AbstractMesh.prototype._removeLightSource = function (light) {
  11057. var index = this._lightSources.indexOf(light);
  11058. if (index === -1) {
  11059. return;
  11060. }
  11061. this._lightSources.splice(index, 1);
  11062. };
  11063. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11064. if (!this.subMeshes) {
  11065. return;
  11066. }
  11067. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11068. var subMesh = _a[_i];
  11069. if (subMesh._materialDefines) {
  11070. func(subMesh._materialDefines);
  11071. }
  11072. }
  11073. };
  11074. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11075. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11076. };
  11077. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11078. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11079. };
  11080. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11081. if (!this.subMeshes) {
  11082. return;
  11083. }
  11084. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11085. var subMesh = _a[_i];
  11086. var material = subMesh.getMaterial();
  11087. if (material) {
  11088. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11089. }
  11090. }
  11091. };
  11092. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11093. /**
  11094. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11095. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11096. * Default : (0.0, 0.0, 0.0)
  11097. */
  11098. get: function () {
  11099. return this._rotation;
  11100. },
  11101. set: function (newRotation) {
  11102. this._rotation = newRotation;
  11103. },
  11104. enumerable: true,
  11105. configurable: true
  11106. });
  11107. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11108. /**
  11109. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11110. * Default : (1.0, 1.0, 1.0)
  11111. */
  11112. get: function () {
  11113. return this._scaling;
  11114. },
  11115. set: function (newScaling) {
  11116. this._scaling = newScaling;
  11117. if (this.physicsImpostor) {
  11118. this.physicsImpostor.forceUpdate();
  11119. }
  11120. },
  11121. enumerable: true,
  11122. configurable: true
  11123. });
  11124. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11125. /**
  11126. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11127. * It's null by default.
  11128. * 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)
  11129. */
  11130. get: function () {
  11131. return this._rotationQuaternion;
  11132. },
  11133. set: function (quaternion) {
  11134. this._rotationQuaternion = quaternion;
  11135. //reset the rotation vector.
  11136. if (quaternion && this.rotation.length()) {
  11137. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11138. }
  11139. },
  11140. enumerable: true,
  11141. configurable: true
  11142. });
  11143. // Methods
  11144. /**
  11145. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11146. * Returns the AbstractMesh.
  11147. */
  11148. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11149. this._poseMatrix.copyFrom(matrix);
  11150. return this;
  11151. };
  11152. /**
  11153. * Returns the mesh Pose matrix.
  11154. * Returned object : Matrix
  11155. */
  11156. AbstractMesh.prototype.getPoseMatrix = function () {
  11157. return this._poseMatrix;
  11158. };
  11159. /**
  11160. * Disables the mesh edger rendering mode.
  11161. * Returns the AbstractMesh.
  11162. */
  11163. AbstractMesh.prototype.disableEdgesRendering = function () {
  11164. if (this._edgesRenderer !== undefined) {
  11165. this._edgesRenderer.dispose();
  11166. this._edgesRenderer = undefined;
  11167. }
  11168. return this;
  11169. };
  11170. /**
  11171. * Enables the edge rendering mode on the mesh.
  11172. * This mode makes the mesh edges visible.
  11173. * Returns the AbstractMesh.
  11174. */
  11175. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11176. if (epsilon === void 0) { epsilon = 0.95; }
  11177. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11178. this.disableEdgesRendering();
  11179. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11180. return this;
  11181. };
  11182. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11183. /**
  11184. * Returns true if the mesh is blocked. Used by the class Mesh.
  11185. * Returns the boolean `false` by default.
  11186. */
  11187. get: function () {
  11188. return false;
  11189. },
  11190. enumerable: true,
  11191. configurable: true
  11192. });
  11193. /**
  11194. * Returns the mesh itself by default, used by the class Mesh.
  11195. * Returned type : AbstractMesh
  11196. */
  11197. AbstractMesh.prototype.getLOD = function (camera) {
  11198. return this;
  11199. };
  11200. /**
  11201. * Returns 0 by default, used by the class Mesh.
  11202. * Returns an integer.
  11203. */
  11204. AbstractMesh.prototype.getTotalVertices = function () {
  11205. return 0;
  11206. };
  11207. /**
  11208. * Returns null by default, used by the class Mesh.
  11209. * Returned type : integer array
  11210. */
  11211. AbstractMesh.prototype.getIndices = function () {
  11212. return null;
  11213. };
  11214. /**
  11215. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11216. * Returned type : float array or Float32Array
  11217. */
  11218. AbstractMesh.prototype.getVerticesData = function (kind) {
  11219. return null;
  11220. };
  11221. /**
  11222. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11223. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11224. * The `data` are either a numeric array either a Float32Array.
  11225. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11226. * 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).
  11227. * Note that a new underlying VertexBuffer object is created each call.
  11228. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11229. *
  11230. * Possible `kind` values :
  11231. * - BABYLON.VertexBuffer.PositionKind
  11232. * - BABYLON.VertexBuffer.UVKind
  11233. * - BABYLON.VertexBuffer.UV2Kind
  11234. * - BABYLON.VertexBuffer.UV3Kind
  11235. * - BABYLON.VertexBuffer.UV4Kind
  11236. * - BABYLON.VertexBuffer.UV5Kind
  11237. * - BABYLON.VertexBuffer.UV6Kind
  11238. * - BABYLON.VertexBuffer.ColorKind
  11239. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11240. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11241. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11242. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11243. *
  11244. * Returns the Mesh.
  11245. */
  11246. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11247. return null;
  11248. };
  11249. /**
  11250. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11251. * If the mesh has no geometry, it is simply returned as it is.
  11252. * The `data` are either a numeric array either a Float32Array.
  11253. * No new underlying VertexBuffer object is created.
  11254. * 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.
  11255. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11256. *
  11257. * Possible `kind` values :
  11258. * - BABYLON.VertexBuffer.PositionKind
  11259. * - BABYLON.VertexBuffer.UVKind
  11260. * - BABYLON.VertexBuffer.UV2Kind
  11261. * - BABYLON.VertexBuffer.UV3Kind
  11262. * - BABYLON.VertexBuffer.UV4Kind
  11263. * - BABYLON.VertexBuffer.UV5Kind
  11264. * - BABYLON.VertexBuffer.UV6Kind
  11265. * - BABYLON.VertexBuffer.ColorKind
  11266. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11267. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11268. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11269. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11270. *
  11271. * Returns the Mesh.
  11272. */
  11273. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11274. return null;
  11275. };
  11276. /**
  11277. * Sets the mesh indices.
  11278. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11279. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11280. * This method creates a new index buffer each call.
  11281. * Returns the Mesh.
  11282. */
  11283. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11284. return null;
  11285. };
  11286. /** Returns false by default, used by the class Mesh.
  11287. * Returns a boolean
  11288. */
  11289. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11290. return false;
  11291. };
  11292. /**
  11293. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11294. * Returns a BoundingInfo
  11295. */
  11296. AbstractMesh.prototype.getBoundingInfo = function () {
  11297. if (this._masterMesh) {
  11298. return this._masterMesh.getBoundingInfo();
  11299. }
  11300. if (!this._boundingInfo) {
  11301. this._updateBoundingInfo();
  11302. }
  11303. return this._boundingInfo;
  11304. };
  11305. /**
  11306. * Sets a mesh new object BoundingInfo.
  11307. * Returns the AbstractMesh.
  11308. */
  11309. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11310. this._boundingInfo = boundingInfo;
  11311. return this;
  11312. };
  11313. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11314. get: function () {
  11315. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11316. },
  11317. enumerable: true,
  11318. configurable: true
  11319. });
  11320. AbstractMesh.prototype._preActivate = function () {
  11321. };
  11322. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11323. };
  11324. AbstractMesh.prototype._activate = function (renderId) {
  11325. this._renderId = renderId;
  11326. };
  11327. /**
  11328. * Returns the last update of the World matrix
  11329. * Returns a Matrix.
  11330. */
  11331. AbstractMesh.prototype.getWorldMatrix = function () {
  11332. if (this._masterMesh) {
  11333. return this._masterMesh.getWorldMatrix();
  11334. }
  11335. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11336. this.computeWorldMatrix();
  11337. }
  11338. return this._worldMatrix;
  11339. };
  11340. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11341. /**
  11342. * Returns directly the last state of the mesh World matrix.
  11343. * A Matrix is returned.
  11344. */
  11345. get: function () {
  11346. return this._worldMatrix;
  11347. },
  11348. enumerable: true,
  11349. configurable: true
  11350. });
  11351. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11352. /**
  11353. * Returns the current mesh absolute position.
  11354. * Retuns a Vector3.
  11355. */
  11356. get: function () {
  11357. return this._absolutePosition;
  11358. },
  11359. enumerable: true,
  11360. configurable: true
  11361. });
  11362. /**
  11363. * Prevents the World matrix to be computed any longer.
  11364. * Returns the AbstractMesh.
  11365. */
  11366. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11367. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11368. this.computeWorldMatrix(true);
  11369. this._isWorldMatrixFrozen = true;
  11370. return this;
  11371. };
  11372. /**
  11373. * Allows back the World matrix computation.
  11374. * Returns the AbstractMesh.
  11375. */
  11376. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11377. this._isWorldMatrixFrozen = false;
  11378. this.computeWorldMatrix(true);
  11379. return this;
  11380. };
  11381. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11382. /**
  11383. * True if the World matrix has been frozen.
  11384. * Returns a boolean.
  11385. */
  11386. get: function () {
  11387. return this._isWorldMatrixFrozen;
  11388. },
  11389. enumerable: true,
  11390. configurable: true
  11391. });
  11392. /**
  11393. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11394. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11395. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11396. * The passed axis is also normalized.
  11397. * Returns the AbstractMesh.
  11398. */
  11399. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11400. axis.normalize();
  11401. if (!this.rotationQuaternion) {
  11402. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11403. this.rotation = BABYLON.Vector3.Zero();
  11404. }
  11405. var rotationQuaternion;
  11406. if (!space || space === BABYLON.Space.LOCAL) {
  11407. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11408. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11409. }
  11410. else {
  11411. if (this.parent) {
  11412. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11413. invertParentWorldMatrix.invert();
  11414. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11415. }
  11416. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11417. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11418. }
  11419. return this;
  11420. };
  11421. /**
  11422. * Translates the mesh along the axis vector for the passed distance in the given space.
  11423. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11424. * Returns the AbstractMesh.
  11425. */
  11426. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11427. var displacementVector = axis.scale(distance);
  11428. if (!space || space === BABYLON.Space.LOCAL) {
  11429. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11430. this.setPositionWithLocalVector(tempV3);
  11431. }
  11432. else {
  11433. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11434. }
  11435. return this;
  11436. };
  11437. /**
  11438. * Adds a rotation step to the mesh current rotation.
  11439. * x, y, z are Euler angles expressed in radians.
  11440. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11441. * This means this rotation is made in the mesh local space only.
  11442. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11443. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11444. * ```javascript
  11445. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11446. * ```
  11447. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11448. * 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.
  11449. * Returns the AbstractMesh.
  11450. */
  11451. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11452. var rotationQuaternion;
  11453. if (this.rotationQuaternion) {
  11454. rotationQuaternion = this.rotationQuaternion;
  11455. }
  11456. else {
  11457. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11458. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11459. }
  11460. var accumulation = BABYLON.Tmp.Quaternion[0];
  11461. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11462. rotationQuaternion.multiplyInPlace(accumulation);
  11463. if (!this.rotationQuaternion) {
  11464. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11465. }
  11466. return this;
  11467. };
  11468. /**
  11469. * Retuns the mesh absolute position in the World.
  11470. * Returns a Vector3.
  11471. */
  11472. AbstractMesh.prototype.getAbsolutePosition = function () {
  11473. this.computeWorldMatrix();
  11474. return this._absolutePosition;
  11475. };
  11476. /**
  11477. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11478. * Returns the AbstractMesh.
  11479. */
  11480. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11481. if (!absolutePosition) {
  11482. return;
  11483. }
  11484. var absolutePositionX;
  11485. var absolutePositionY;
  11486. var absolutePositionZ;
  11487. if (absolutePosition.x === undefined) {
  11488. if (arguments.length < 3) {
  11489. return;
  11490. }
  11491. absolutePositionX = arguments[0];
  11492. absolutePositionY = arguments[1];
  11493. absolutePositionZ = arguments[2];
  11494. }
  11495. else {
  11496. absolutePositionX = absolutePosition.x;
  11497. absolutePositionY = absolutePosition.y;
  11498. absolutePositionZ = absolutePosition.z;
  11499. }
  11500. if (this.parent) {
  11501. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11502. invertParentWorldMatrix.invert();
  11503. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  11504. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  11505. }
  11506. else {
  11507. this.position.x = absolutePositionX;
  11508. this.position.y = absolutePositionY;
  11509. this.position.z = absolutePositionZ;
  11510. }
  11511. return this;
  11512. };
  11513. // ================================== Point of View Movement =================================
  11514. /**
  11515. * Perform relative position change from the point of view of behind the front of the mesh.
  11516. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11517. * Supports definition of mesh facing forward or backward.
  11518. * @param {number} amountRight
  11519. * @param {number} amountUp
  11520. * @param {number} amountForward
  11521. *
  11522. * Returns the AbstractMesh.
  11523. */
  11524. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  11525. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  11526. return this;
  11527. };
  11528. /**
  11529. * Calculate relative position change from the point of view of behind the front of the mesh.
  11530. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11531. * Supports definition of mesh facing forward or backward.
  11532. * @param {number} amountRight
  11533. * @param {number} amountUp
  11534. * @param {number} amountForward
  11535. *
  11536. * Returns a new Vector3.
  11537. */
  11538. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  11539. var rotMatrix = new BABYLON.Matrix();
  11540. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11541. rotQuaternion.toRotationMatrix(rotMatrix);
  11542. var translationDelta = BABYLON.Vector3.Zero();
  11543. var defForwardMult = this.definedFacingForward ? -1 : 1;
  11544. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  11545. return translationDelta;
  11546. };
  11547. // ================================== Point of View Rotation =================================
  11548. /**
  11549. * Perform relative rotation change from the point of view of behind the front of the mesh.
  11550. * Supports definition of mesh facing forward or backward.
  11551. * @param {number} flipBack
  11552. * @param {number} twirlClockwise
  11553. * @param {number} tiltRight
  11554. *
  11555. * Returns the AbstractMesh.
  11556. */
  11557. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11558. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  11559. return this;
  11560. };
  11561. /**
  11562. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  11563. * Supports definition of mesh facing forward or backward.
  11564. * @param {number} flipBack
  11565. * @param {number} twirlClockwise
  11566. * @param {number} tiltRight
  11567. *
  11568. * Returns a new Vector3.
  11569. */
  11570. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11571. var defForwardMult = this.definedFacingForward ? 1 : -1;
  11572. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  11573. };
  11574. /**
  11575. * Sets a new pivot matrix to the mesh.
  11576. * Returns the AbstractMesh.
  11577. */
  11578. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  11579. this._pivotMatrix = matrix;
  11580. this._cache.pivotMatrixUpdated = true;
  11581. return this;
  11582. };
  11583. /**
  11584. * Returns the mesh pivot matrix.
  11585. * Default : Identity.
  11586. * A Matrix is returned.
  11587. */
  11588. AbstractMesh.prototype.getPivotMatrix = function () {
  11589. return this._pivotMatrix;
  11590. };
  11591. AbstractMesh.prototype._isSynchronized = function () {
  11592. if (this._isDirty) {
  11593. return false;
  11594. }
  11595. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  11596. return false;
  11597. if (this._cache.pivotMatrixUpdated) {
  11598. return false;
  11599. }
  11600. if (this.infiniteDistance) {
  11601. return false;
  11602. }
  11603. if (!this._cache.position.equals(this.position))
  11604. return false;
  11605. if (this.rotationQuaternion) {
  11606. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  11607. return false;
  11608. }
  11609. if (!this._cache.rotation.equals(this.rotation))
  11610. return false;
  11611. if (!this._cache.scaling.equals(this.scaling))
  11612. return false;
  11613. return true;
  11614. };
  11615. AbstractMesh.prototype._initCache = function () {
  11616. _super.prototype._initCache.call(this);
  11617. this._cache.localMatrixUpdated = false;
  11618. this._cache.position = BABYLON.Vector3.Zero();
  11619. this._cache.scaling = BABYLON.Vector3.Zero();
  11620. this._cache.rotation = BABYLON.Vector3.Zero();
  11621. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  11622. this._cache.billboardMode = -1;
  11623. };
  11624. AbstractMesh.prototype.markAsDirty = function (property) {
  11625. if (property === "rotation") {
  11626. this.rotationQuaternion = null;
  11627. }
  11628. this._currentRenderId = Number.MAX_VALUE;
  11629. this._isDirty = true;
  11630. return this;
  11631. };
  11632. /**
  11633. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  11634. * Returns the AbstractMesh.
  11635. */
  11636. AbstractMesh.prototype._updateBoundingInfo = function () {
  11637. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  11638. this._boundingInfo.update(this.worldMatrixFromCache);
  11639. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11640. return this;
  11641. };
  11642. /**
  11643. * Update a mesh's children BoundingInfo objects only.
  11644. * Returns the AbstractMesh.
  11645. */
  11646. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  11647. if (!this.subMeshes) {
  11648. return;
  11649. }
  11650. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  11651. var subMesh = this.subMeshes[subIndex];
  11652. if (!subMesh.IsGlobal) {
  11653. subMesh.updateBoundingInfo(matrix);
  11654. }
  11655. }
  11656. return this;
  11657. };
  11658. /**
  11659. * Computes the mesh World matrix and returns it.
  11660. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  11661. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  11662. * If the parameter `force`is set to `true`, the actual computation is done.
  11663. * Returns the mesh World Matrix.
  11664. */
  11665. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  11666. if (this._isWorldMatrixFrozen) {
  11667. return this._worldMatrix;
  11668. }
  11669. if (!force && this.isSynchronized(true)) {
  11670. this._currentRenderId = this.getScene().getRenderId();
  11671. return this._worldMatrix;
  11672. }
  11673. this._cache.position.copyFrom(this.position);
  11674. this._cache.scaling.copyFrom(this.scaling);
  11675. this._cache.pivotMatrixUpdated = false;
  11676. this._cache.billboardMode = this.billboardMode;
  11677. this._currentRenderId = this.getScene().getRenderId();
  11678. this._isDirty = false;
  11679. // Scaling
  11680. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  11681. // Rotation
  11682. //rotate, if quaternion is set and rotation was used
  11683. if (this.rotationQuaternion) {
  11684. var len = this.rotation.length();
  11685. if (len) {
  11686. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  11687. this.rotation.copyFromFloats(0, 0, 0);
  11688. }
  11689. }
  11690. if (this.rotationQuaternion) {
  11691. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  11692. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  11693. }
  11694. else {
  11695. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  11696. this._cache.rotation.copyFrom(this.rotation);
  11697. }
  11698. // Translation
  11699. if (this.infiniteDistance && !this.parent) {
  11700. var camera = this.getScene().activeCamera;
  11701. if (camera) {
  11702. var cameraWorldMatrix = camera.getWorldMatrix();
  11703. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  11704. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  11705. }
  11706. }
  11707. else {
  11708. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  11709. }
  11710. // Composing transformations
  11711. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  11712. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11713. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  11714. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  11715. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  11716. // Need to decompose each rotation here
  11717. var currentPosition = BABYLON.Tmp.Vector3[3];
  11718. if (this.parent && this.parent.getWorldMatrix) {
  11719. if (this._meshToBoneReferal) {
  11720. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11721. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  11722. }
  11723. else {
  11724. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  11725. }
  11726. }
  11727. else {
  11728. currentPosition.copyFrom(this.position);
  11729. }
  11730. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  11731. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  11732. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  11733. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  11734. }
  11735. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  11736. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  11737. }
  11738. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  11739. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  11740. }
  11741. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  11742. }
  11743. else {
  11744. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  11745. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  11746. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  11747. }
  11748. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  11749. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11750. }
  11751. // Local world
  11752. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  11753. // Parent
  11754. if (this.parent && this.parent.getWorldMatrix) {
  11755. this._markSyncedWithParent();
  11756. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  11757. if (this._meshToBoneReferal) {
  11758. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11759. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  11760. }
  11761. else {
  11762. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  11763. }
  11764. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  11765. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  11766. this._worldMatrix.copyFrom(this._localWorld);
  11767. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  11768. }
  11769. else {
  11770. if (this._meshToBoneReferal) {
  11771. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11772. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  11773. }
  11774. else {
  11775. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  11776. }
  11777. }
  11778. }
  11779. else {
  11780. this._worldMatrix.copyFrom(this._localWorld);
  11781. }
  11782. // Bounding info
  11783. this._updateBoundingInfo();
  11784. // Absolute position
  11785. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  11786. // Callbacks
  11787. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  11788. if (!this._poseMatrix) {
  11789. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  11790. }
  11791. return this._worldMatrix;
  11792. };
  11793. /**
  11794. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  11795. * @param func: callback function to add
  11796. *
  11797. * Returns the AbstractMesh.
  11798. */
  11799. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  11800. this.onAfterWorldMatrixUpdateObservable.add(func);
  11801. return this;
  11802. };
  11803. /**
  11804. * Removes a registered callback function.
  11805. * Returns the AbstractMesh.
  11806. */
  11807. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  11808. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  11809. return this;
  11810. };
  11811. /**
  11812. * Sets the mesh position in its local space.
  11813. * Returns the AbstractMesh.
  11814. */
  11815. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  11816. this.computeWorldMatrix();
  11817. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  11818. return this;
  11819. };
  11820. /**
  11821. * Returns the mesh position in the local space from the current World matrix values.
  11822. * Returns a new Vector3.
  11823. */
  11824. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  11825. this.computeWorldMatrix();
  11826. var invLocalWorldMatrix = this._localWorld.clone();
  11827. invLocalWorldMatrix.invert();
  11828. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  11829. };
  11830. /**
  11831. * Translates the mesh along the passed Vector3 in its local space.
  11832. * Returns the AbstractMesh.
  11833. */
  11834. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  11835. this.computeWorldMatrix(true);
  11836. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  11837. return this;
  11838. };
  11839. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  11840. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  11841. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  11842. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  11843. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  11844. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  11845. /// <returns>Mesh oriented towards targetMesh</returns>
  11846. if (yawCor === void 0) { yawCor = 0; }
  11847. if (pitchCor === void 0) { pitchCor = 0; }
  11848. if (rollCor === void 0) { rollCor = 0; }
  11849. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11850. var dv = AbstractMesh._lookAtVectorCache;
  11851. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  11852. targetPoint.subtractToRef(pos, dv);
  11853. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  11854. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  11855. var pitch = Math.atan2(dv.y, len);
  11856. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  11857. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  11858. return this;
  11859. };
  11860. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  11861. this._meshToBoneReferal = affectedMesh;
  11862. this.parent = bone;
  11863. if (bone.getWorldMatrix().determinant() < 0) {
  11864. this.scalingDeterminant *= -1;
  11865. }
  11866. return this;
  11867. };
  11868. AbstractMesh.prototype.detachFromBone = function () {
  11869. if (this.parent.getWorldMatrix().determinant() < 0) {
  11870. this.scalingDeterminant *= -1;
  11871. }
  11872. this._meshToBoneReferal = null;
  11873. this.parent = null;
  11874. return this;
  11875. };
  11876. /**
  11877. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  11878. * A mesh is in the frustum if its bounding box intersects the frustum.
  11879. * Boolean returned.
  11880. */
  11881. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11882. return this._boundingInfo.isInFrustum(frustumPlanes);
  11883. };
  11884. /**
  11885. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  11886. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  11887. * Boolean returned.
  11888. */
  11889. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11890. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11891. ;
  11892. };
  11893. /**
  11894. * True if the mesh intersects another mesh or a SolidParticle object.
  11895. * 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)
  11896. * Returns a boolean.
  11897. */
  11898. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11899. if (!this._boundingInfo || !mesh._boundingInfo) {
  11900. return false;
  11901. }
  11902. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11903. };
  11904. /**
  11905. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  11906. * Returns a boolean.
  11907. */
  11908. AbstractMesh.prototype.intersectsPoint = function (point) {
  11909. if (!this._boundingInfo) {
  11910. return false;
  11911. }
  11912. return this._boundingInfo.intersectsPoint(point);
  11913. };
  11914. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11915. return this.physicsImpostor;
  11916. };
  11917. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11918. if (!camera) {
  11919. camera = this.getScene().activeCamera;
  11920. }
  11921. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11922. };
  11923. /**
  11924. * Returns the distance from the mesh to the active camera.
  11925. * Returns a float.
  11926. */
  11927. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11928. if (!camera) {
  11929. camera = this.getScene().activeCamera;
  11930. }
  11931. return this.absolutePosition.subtract(camera.position).length();
  11932. };
  11933. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11934. if (!this.physicsImpostor) {
  11935. return;
  11936. }
  11937. this.physicsImpostor.applyImpulse(force, contactPoint);
  11938. return this;
  11939. };
  11940. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  11941. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  11942. return;
  11943. }
  11944. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  11945. mainPivot: pivot1,
  11946. connectedPivot: pivot2,
  11947. nativeParams: options
  11948. });
  11949. return this;
  11950. };
  11951. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  11952. // Collisions
  11953. /**
  11954. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  11955. * Default `false`.
  11956. */
  11957. get: function () {
  11958. return this._checkCollisions;
  11959. },
  11960. set: function (collisionEnabled) {
  11961. this._checkCollisions = collisionEnabled;
  11962. if (this.getScene().workerCollisions) {
  11963. this.getScene().collisionCoordinator.onMeshUpdated(this);
  11964. }
  11965. },
  11966. enumerable: true,
  11967. configurable: true
  11968. });
  11969. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  11970. var globalPosition = this.getAbsolutePosition();
  11971. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  11972. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  11973. if (!this._collider) {
  11974. this._collider = new BABYLON.Collider();
  11975. }
  11976. this._collider.radius = this.ellipsoid;
  11977. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  11978. return this;
  11979. };
  11980. // Submeshes octree
  11981. /**
  11982. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  11983. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  11984. * Returns an Octree of submeshes.
  11985. */
  11986. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11987. if (maxCapacity === void 0) { maxCapacity = 64; }
  11988. if (maxDepth === void 0) { maxDepth = 2; }
  11989. if (!this._submeshesOctree) {
  11990. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11991. }
  11992. this.computeWorldMatrix(true);
  11993. // Update octree
  11994. var bbox = this.getBoundingInfo().boundingBox;
  11995. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11996. return this._submeshesOctree;
  11997. };
  11998. // Collisions
  11999. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  12000. this._generatePointsArray();
  12001. // Transformation
  12002. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  12003. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  12004. subMesh._lastColliderWorldVertices = [];
  12005. subMesh._trianglePlanes = [];
  12006. var start = subMesh.verticesStart;
  12007. var end = (subMesh.verticesStart + subMesh.verticesCount);
  12008. for (var i = start; i < end; i++) {
  12009. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  12010. }
  12011. }
  12012. // Collide
  12013. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  12014. if (collider.collisionFound) {
  12015. collider.collidedMesh = this;
  12016. }
  12017. return this;
  12018. };
  12019. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  12020. var subMeshes;
  12021. var len;
  12022. // Octrees
  12023. if (this._submeshesOctree && this.useOctreeForCollisions) {
  12024. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  12025. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  12026. len = intersections.length;
  12027. subMeshes = intersections.data;
  12028. }
  12029. else {
  12030. subMeshes = this.subMeshes;
  12031. len = subMeshes.length;
  12032. }
  12033. for (var index = 0; index < len; index++) {
  12034. var subMesh = subMeshes[index];
  12035. // Bounding test
  12036. if (len > 1 && !subMesh._checkCollision(collider))
  12037. continue;
  12038. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12039. }
  12040. return this;
  12041. };
  12042. AbstractMesh.prototype._checkCollision = function (collider) {
  12043. // Bounding box test
  12044. if (!this._boundingInfo._checkCollision(collider))
  12045. return this;
  12046. // Transformation matrix
  12047. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12048. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12049. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12050. return this;
  12051. };
  12052. // Picking
  12053. AbstractMesh.prototype._generatePointsArray = function () {
  12054. return false;
  12055. };
  12056. /**
  12057. * Checks if the passed Ray intersects with the mesh.
  12058. * Returns an object PickingInfo.
  12059. */
  12060. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12061. var pickingInfo = new BABYLON.PickingInfo();
  12062. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12063. return pickingInfo;
  12064. }
  12065. if (!this._generatePointsArray()) {
  12066. return pickingInfo;
  12067. }
  12068. var intersectInfo = null;
  12069. // Octrees
  12070. var subMeshes;
  12071. var len;
  12072. if (this._submeshesOctree && this.useOctreeForPicking) {
  12073. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12074. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12075. len = intersections.length;
  12076. subMeshes = intersections.data;
  12077. }
  12078. else {
  12079. subMeshes = this.subMeshes;
  12080. len = subMeshes.length;
  12081. }
  12082. for (var index = 0; index < len; index++) {
  12083. var subMesh = subMeshes[index];
  12084. // Bounding test
  12085. if (len > 1 && !subMesh.canIntersects(ray))
  12086. continue;
  12087. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12088. if (currentIntersectInfo) {
  12089. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12090. intersectInfo = currentIntersectInfo;
  12091. intersectInfo.subMeshId = index;
  12092. if (fastCheck) {
  12093. break;
  12094. }
  12095. }
  12096. }
  12097. }
  12098. if (intersectInfo) {
  12099. // Get picked point
  12100. var world = this.getWorldMatrix();
  12101. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12102. var direction = ray.direction.clone();
  12103. direction = direction.scale(intersectInfo.distance);
  12104. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12105. var pickedPoint = worldOrigin.add(worldDirection);
  12106. // Return result
  12107. pickingInfo.hit = true;
  12108. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12109. pickingInfo.pickedPoint = pickedPoint;
  12110. pickingInfo.pickedMesh = this;
  12111. pickingInfo.bu = intersectInfo.bu;
  12112. pickingInfo.bv = intersectInfo.bv;
  12113. pickingInfo.faceId = intersectInfo.faceId;
  12114. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12115. return pickingInfo;
  12116. }
  12117. return pickingInfo;
  12118. };
  12119. /**
  12120. * Clones the mesh, used by the class Mesh.
  12121. * Just returns `null` for an AbstractMesh.
  12122. */
  12123. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12124. return null;
  12125. };
  12126. /**
  12127. * Disposes all the mesh submeshes.
  12128. * Returns the AbstractMesh.
  12129. */
  12130. AbstractMesh.prototype.releaseSubMeshes = function () {
  12131. if (this.subMeshes) {
  12132. while (this.subMeshes.length) {
  12133. this.subMeshes[0].dispose();
  12134. }
  12135. }
  12136. else {
  12137. this.subMeshes = new Array();
  12138. }
  12139. return this;
  12140. };
  12141. /**
  12142. * Disposes the AbstractMesh.
  12143. * Some internal references are kept for further use.
  12144. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12145. * Returns nothing.
  12146. */
  12147. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12148. var _this = this;
  12149. var index;
  12150. // Action manager
  12151. if (this.actionManager) {
  12152. this.actionManager.dispose();
  12153. this.actionManager = null;
  12154. }
  12155. // Skeleton
  12156. this.skeleton = null;
  12157. // Animations
  12158. this.getScene().stopAnimation(this);
  12159. // Physics
  12160. if (this.physicsImpostor) {
  12161. this.physicsImpostor.dispose();
  12162. }
  12163. // Intersections in progress
  12164. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12165. var other = this._intersectionsInProgress[index];
  12166. var pos = other._intersectionsInProgress.indexOf(this);
  12167. other._intersectionsInProgress.splice(pos, 1);
  12168. }
  12169. this._intersectionsInProgress = [];
  12170. // Lights
  12171. var lights = this.getScene().lights;
  12172. lights.forEach(function (light) {
  12173. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12174. if (meshIndex !== -1) {
  12175. light.includedOnlyMeshes.splice(meshIndex, 1);
  12176. }
  12177. meshIndex = light.excludedMeshes.indexOf(_this);
  12178. if (meshIndex !== -1) {
  12179. light.excludedMeshes.splice(meshIndex, 1);
  12180. }
  12181. // Shadow generators
  12182. var generator = light.getShadowGenerator();
  12183. if (generator) {
  12184. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  12185. if (meshIndex !== -1) {
  12186. generator.getShadowMap().renderList.splice(meshIndex, 1);
  12187. }
  12188. }
  12189. });
  12190. // Edges
  12191. if (this._edgesRenderer) {
  12192. this._edgesRenderer.dispose();
  12193. this._edgesRenderer = null;
  12194. }
  12195. // SubMeshes
  12196. if (this.getClassName() !== "InstancedMesh") {
  12197. this.releaseSubMeshes();
  12198. }
  12199. // Octree
  12200. var sceneOctree = this.getScene().selectionOctree;
  12201. if (sceneOctree) {
  12202. var index = sceneOctree.dynamicContent.indexOf(this);
  12203. if (index !== -1) {
  12204. sceneOctree.dynamicContent.splice(index, 1);
  12205. }
  12206. }
  12207. // Engine
  12208. this.getScene().getEngine().wipeCaches();
  12209. // Remove from scene
  12210. this.getScene().removeMesh(this);
  12211. if (!doNotRecurse) {
  12212. // Particles
  12213. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12214. if (this.getScene().particleSystems[index].emitter === this) {
  12215. this.getScene().particleSystems[index].dispose();
  12216. index--;
  12217. }
  12218. }
  12219. // Children
  12220. var objects = this.getDescendants(true);
  12221. for (index = 0; index < objects.length; index++) {
  12222. objects[index].dispose();
  12223. }
  12224. }
  12225. else {
  12226. var childMeshes = this.getChildMeshes(true);
  12227. for (index = 0; index < childMeshes.length; index++) {
  12228. var child = childMeshes[index];
  12229. child.parent = null;
  12230. child.computeWorldMatrix(true);
  12231. }
  12232. }
  12233. // facet data
  12234. if (this._facetDataEnabled) {
  12235. this.disableFacetData();
  12236. }
  12237. this.onAfterWorldMatrixUpdateObservable.clear();
  12238. this.onCollideObservable.clear();
  12239. this.onCollisionPositionChangeObservable.clear();
  12240. this._isDisposed = true;
  12241. _super.prototype.dispose.call(this);
  12242. };
  12243. /**
  12244. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12245. * This Vector3 is expressed in the World space.
  12246. */
  12247. AbstractMesh.prototype.getDirection = function (localAxis) {
  12248. var result = BABYLON.Vector3.Zero();
  12249. this.getDirectionToRef(localAxis, result);
  12250. return result;
  12251. };
  12252. /**
  12253. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12254. * localAxis is expressed in the mesh local space.
  12255. * result is computed in the Wordl space from the mesh World matrix.
  12256. * Returns the AbstractMesh.
  12257. */
  12258. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12259. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12260. return this;
  12261. };
  12262. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12263. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12264. if (this.getScene().getRenderId() == 0) {
  12265. this.computeWorldMatrix(true);
  12266. }
  12267. var wm = this.getWorldMatrix();
  12268. if (space == BABYLON.Space.WORLD) {
  12269. var tmat = BABYLON.Tmp.Matrix[0];
  12270. wm.invertToRef(tmat);
  12271. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12272. }
  12273. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12274. this._pivotMatrix.m[12] = -point.x;
  12275. this._pivotMatrix.m[13] = -point.y;
  12276. this._pivotMatrix.m[14] = -point.z;
  12277. this._cache.pivotMatrixUpdated = true;
  12278. return this;
  12279. };
  12280. /**
  12281. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12282. */
  12283. AbstractMesh.prototype.getPivotPoint = function () {
  12284. var point = BABYLON.Vector3.Zero();
  12285. this.getPivotPointToRef(point);
  12286. return point;
  12287. };
  12288. /**
  12289. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12290. * Returns the AbstractMesh.
  12291. */
  12292. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12293. result.x = -this._pivotMatrix.m[12];
  12294. result.y = -this._pivotMatrix.m[13];
  12295. result.z = -this._pivotMatrix.m[14];
  12296. return this;
  12297. };
  12298. /**
  12299. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12300. */
  12301. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12302. var point = BABYLON.Vector3.Zero();
  12303. this.getAbsolutePivotPointToRef(point);
  12304. return point;
  12305. };
  12306. /**
  12307. * Defines the passed mesh as the parent of the current mesh.
  12308. * Returns the AbstractMesh.
  12309. */
  12310. AbstractMesh.prototype.setParent = function (mesh) {
  12311. var child = this;
  12312. var parent = mesh;
  12313. if (mesh == null) {
  12314. var rotation = BABYLON.Tmp.Quaternion[0];
  12315. var position = BABYLON.Tmp.Vector3[0];
  12316. var scale = BABYLON.Tmp.Vector3[1];
  12317. child.getWorldMatrix().decompose(scale, rotation, position);
  12318. if (child.rotationQuaternion) {
  12319. child.rotationQuaternion.copyFrom(rotation);
  12320. }
  12321. else {
  12322. rotation.toEulerAnglesToRef(child.rotation);
  12323. }
  12324. child.position.x = position.x;
  12325. child.position.y = position.y;
  12326. child.position.z = position.z;
  12327. }
  12328. else {
  12329. var rotation = BABYLON.Tmp.Quaternion[0];
  12330. var position = BABYLON.Tmp.Vector3[0];
  12331. var scale = BABYLON.Tmp.Vector3[1];
  12332. var m1 = BABYLON.Tmp.Matrix[0];
  12333. var m2 = BABYLON.Tmp.Matrix[1];
  12334. parent.getWorldMatrix().decompose(scale, rotation, position);
  12335. rotation.toRotationMatrix(m1);
  12336. m2.setTranslation(position);
  12337. m2.multiplyToRef(m1, m1);
  12338. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12339. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12340. m.decompose(scale, rotation, position);
  12341. if (child.rotationQuaternion) {
  12342. child.rotationQuaternion.copyFrom(rotation);
  12343. }
  12344. else {
  12345. rotation.toEulerAnglesToRef(child.rotation);
  12346. }
  12347. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12348. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12349. m.decompose(scale, rotation, position);
  12350. child.position.x = position.x;
  12351. child.position.y = position.y;
  12352. child.position.z = position.z;
  12353. }
  12354. child.parent = parent;
  12355. return this;
  12356. };
  12357. /**
  12358. * Adds the passed mesh as a child to the current mesh.
  12359. * Returns the AbstractMesh.
  12360. */
  12361. AbstractMesh.prototype.addChild = function (mesh) {
  12362. mesh.setParent(this);
  12363. return this;
  12364. };
  12365. /**
  12366. * Removes the passed mesh from the current mesh children list.
  12367. * Returns the AbstractMesh.
  12368. */
  12369. AbstractMesh.prototype.removeChild = function (mesh) {
  12370. mesh.setParent(null);
  12371. return this;
  12372. };
  12373. /**
  12374. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12375. * Returns the AbstractMesh.
  12376. */
  12377. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12378. result.x = this._pivotMatrix.m[12];
  12379. result.y = this._pivotMatrix.m[13];
  12380. result.z = this._pivotMatrix.m[14];
  12381. this.getPivotPointToRef(result);
  12382. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12383. return this;
  12384. };
  12385. // Facet data
  12386. /**
  12387. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12388. * Returns the AbstractMesh.
  12389. */
  12390. AbstractMesh.prototype._initFacetData = function () {
  12391. if (!this._facetNormals) {
  12392. this._facetNormals = new Array();
  12393. }
  12394. if (!this._facetPositions) {
  12395. this._facetPositions = new Array();
  12396. }
  12397. if (!this._facetPartitioning) {
  12398. this._facetPartitioning = new Array();
  12399. }
  12400. this._facetNb = this.getIndices().length / 3;
  12401. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12402. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12403. for (var f = 0; f < this._facetNb; f++) {
  12404. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12405. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12406. }
  12407. this._facetDataEnabled = true;
  12408. return this;
  12409. };
  12410. /**
  12411. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12412. * This method can be called within the render loop.
  12413. * 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.
  12414. * Returns the AbstractMesh.
  12415. */
  12416. AbstractMesh.prototype.updateFacetData = function () {
  12417. if (!this._facetDataEnabled) {
  12418. this._initFacetData();
  12419. }
  12420. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12421. var indices = this.getIndices();
  12422. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12423. var bInfo = this.getBoundingInfo();
  12424. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12425. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12426. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12427. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12428. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12429. this._subDiv.max = this._partitioningSubdivisions;
  12430. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12431. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12432. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12433. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12434. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12435. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12436. // set the parameters for ComputeNormals()
  12437. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12438. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12439. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12440. this._facetParameters.bInfo = bInfo;
  12441. this._facetParameters.bbSize = this._bbSize;
  12442. this._facetParameters.subDiv = this._subDiv;
  12443. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12444. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12445. return this;
  12446. };
  12447. /**
  12448. * Returns the facetLocalNormals array.
  12449. * The normals are expressed in the mesh local space.
  12450. */
  12451. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12452. if (!this._facetNormals) {
  12453. this.updateFacetData();
  12454. }
  12455. return this._facetNormals;
  12456. };
  12457. /**
  12458. * Returns the facetLocalPositions array.
  12459. * The facet positions are expressed in the mesh local space.
  12460. */
  12461. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12462. if (!this._facetPositions) {
  12463. this.updateFacetData();
  12464. }
  12465. return this._facetPositions;
  12466. };
  12467. /**
  12468. * Returns the facetLocalPartioning array.
  12469. */
  12470. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12471. if (!this._facetPartitioning) {
  12472. this.updateFacetData();
  12473. }
  12474. return this._facetPartitioning;
  12475. };
  12476. /**
  12477. * Returns the i-th facet position in the world system.
  12478. * This method allocates a new Vector3 per call.
  12479. */
  12480. AbstractMesh.prototype.getFacetPosition = function (i) {
  12481. var pos = BABYLON.Vector3.Zero();
  12482. this.getFacetPositionToRef(i, pos);
  12483. return pos;
  12484. };
  12485. /**
  12486. * Sets the reference Vector3 with the i-th facet position in the world system.
  12487. * Returns the AbstractMesh.
  12488. */
  12489. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  12490. var localPos = (this.getFacetLocalPositions())[i];
  12491. var world = this.getWorldMatrix();
  12492. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  12493. return this;
  12494. };
  12495. /**
  12496. * Returns the i-th facet normal in the world system.
  12497. * This method allocates a new Vector3 per call.
  12498. */
  12499. AbstractMesh.prototype.getFacetNormal = function (i) {
  12500. var norm = BABYLON.Vector3.Zero();
  12501. this.getFacetNormalToRef(i, norm);
  12502. return norm;
  12503. };
  12504. /**
  12505. * Sets the reference Vector3 with the i-th facet normal in the world system.
  12506. * Returns the AbstractMesh.
  12507. */
  12508. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  12509. var localNorm = (this.getFacetLocalNormals())[i];
  12510. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  12511. return this;
  12512. };
  12513. /**
  12514. * 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).
  12515. */
  12516. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  12517. var bInfo = this.getBoundingInfo();
  12518. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  12519. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  12520. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  12521. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  12522. return null;
  12523. }
  12524. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  12525. };
  12526. /**
  12527. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  12528. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  12529. * 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.
  12530. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12531. * 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.
  12532. */
  12533. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  12534. if (checkFace === void 0) { checkFace = false; }
  12535. if (facing === void 0) { facing = true; }
  12536. var world = this.getWorldMatrix();
  12537. var invMat = BABYLON.Tmp.Matrix[5];
  12538. world.invertToRef(invMat);
  12539. var invVect = BABYLON.Tmp.Vector3[8];
  12540. var closest = null;
  12541. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  12542. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  12543. if (projected) {
  12544. // tranform the local computed projected vector to world coordinates
  12545. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  12546. }
  12547. return closest;
  12548. };
  12549. /**
  12550. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  12551. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  12552. * 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.
  12553. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12554. * 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.
  12555. */
  12556. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  12557. if (checkFace === void 0) { checkFace = false; }
  12558. if (facing === void 0) { facing = true; }
  12559. var closest = null;
  12560. var tmpx = 0.0;
  12561. var tmpy = 0.0;
  12562. var tmpz = 0.0;
  12563. var d = 0.0; // tmp dot facet normal * facet position
  12564. var t0 = 0.0;
  12565. var projx = 0.0;
  12566. var projy = 0.0;
  12567. var projz = 0.0;
  12568. // Get all the facets in the same partitioning block than (x, y, z)
  12569. var facetPositions = this.getFacetLocalPositions();
  12570. var facetNormals = this.getFacetLocalNormals();
  12571. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  12572. if (!facetsInBlock) {
  12573. return null;
  12574. }
  12575. // Get the closest facet to (x, y, z)
  12576. var shortest = Number.MAX_VALUE; // init distance vars
  12577. var tmpDistance = shortest;
  12578. var fib; // current facet in the block
  12579. var norm; // current facet normal
  12580. var p0; // current facet barycenter position
  12581. // loop on all the facets in the current partitioning block
  12582. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  12583. fib = facetsInBlock[idx];
  12584. norm = facetNormals[fib];
  12585. p0 = facetPositions[fib];
  12586. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  12587. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  12588. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  12589. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  12590. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  12591. projx = x + norm.x * t0;
  12592. projy = y + norm.y * t0;
  12593. projz = z + norm.z * t0;
  12594. tmpx = projx - x;
  12595. tmpy = projy - y;
  12596. tmpz = projz - z;
  12597. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  12598. if (tmpDistance < shortest) {
  12599. shortest = tmpDistance;
  12600. closest = fib;
  12601. if (projected) {
  12602. projected.x = projx;
  12603. projected.y = projy;
  12604. projected.z = projz;
  12605. }
  12606. }
  12607. }
  12608. }
  12609. return closest;
  12610. };
  12611. /**
  12612. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  12613. */
  12614. AbstractMesh.prototype.getFacetDataParameters = function () {
  12615. return this._facetParameters;
  12616. };
  12617. /**
  12618. * Disables the feature FacetData and frees the related memory.
  12619. * Returns the AbstractMesh.
  12620. */
  12621. AbstractMesh.prototype.disableFacetData = function () {
  12622. if (this._facetDataEnabled) {
  12623. this._facetDataEnabled = false;
  12624. this._facetPositions = null;
  12625. this._facetNormals = null;
  12626. this._facetPartitioning = null;
  12627. this._facetParameters = null;
  12628. }
  12629. return this;
  12630. };
  12631. /**
  12632. * Creates new normals data for the mesh.
  12633. * @param updatable.
  12634. */
  12635. AbstractMesh.prototype.createNormals = function (updatable) {
  12636. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12637. var indices = this.getIndices();
  12638. var normals;
  12639. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12640. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12641. }
  12642. else {
  12643. normals = [];
  12644. }
  12645. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  12646. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  12647. };
  12648. return AbstractMesh;
  12649. }(BABYLON.Node));
  12650. // Statics
  12651. AbstractMesh._BILLBOARDMODE_NONE = 0;
  12652. AbstractMesh._BILLBOARDMODE_X = 1;
  12653. AbstractMesh._BILLBOARDMODE_Y = 2;
  12654. AbstractMesh._BILLBOARDMODE_Z = 4;
  12655. AbstractMesh._BILLBOARDMODE_ALL = 7;
  12656. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  12657. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  12658. BABYLON.AbstractMesh = AbstractMesh;
  12659. })(BABYLON || (BABYLON = {}));
  12660. //# sourceMappingURL=babylon.abstractMesh.js.map
  12661. var BABYLON;
  12662. (function (BABYLON) {
  12663. var Light = (function (_super) {
  12664. __extends(Light, _super);
  12665. /**
  12666. * Creates a Light object in the scene.
  12667. * Documentation : http://doc.babylonjs.com/tutorials/lights
  12668. */
  12669. function Light(name, scene) {
  12670. var _this = _super.call(this, name, scene) || this;
  12671. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  12672. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  12673. _this.intensity = 1.0;
  12674. _this.range = Number.MAX_VALUE;
  12675. _this._excludeWithLayerMask = 0;
  12676. _this._includeOnlyWithLayerMask = 0;
  12677. _this._lightmapMode = 0;
  12678. // PBR Properties.
  12679. _this.radius = 0.00001;
  12680. _this._excludedMeshesIds = new Array();
  12681. _this._includedOnlyMeshesIds = new Array();
  12682. _this.getScene().addLight(_this);
  12683. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  12684. _this._buildUniformLayout();
  12685. _this.includedOnlyMeshes = new Array();
  12686. _this.excludedMeshes = new Array();
  12687. _this._resyncMeshes();
  12688. return _this;
  12689. }
  12690. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  12691. /**
  12692. * If every light affecting the material is in this lightmapMode,
  12693. * material.lightmapTexture adds or multiplies
  12694. * (depends on material.useLightmapAsShadowmap)
  12695. * after every other light calculations.
  12696. */
  12697. get: function () {
  12698. return Light._LIGHTMAP_DEFAULT;
  12699. },
  12700. enumerable: true,
  12701. configurable: true
  12702. });
  12703. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  12704. /**
  12705. * material.lightmapTexture as only diffuse lighting from this light
  12706. * adds pnly specular lighting from this light
  12707. * adds dynamic shadows
  12708. */
  12709. get: function () {
  12710. return Light._LIGHTMAP_SPECULAR;
  12711. },
  12712. enumerable: true,
  12713. configurable: true
  12714. });
  12715. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  12716. /**
  12717. * material.lightmapTexture as only lighting
  12718. * no light calculation from this light
  12719. * only adds dynamic shadows from this light
  12720. */
  12721. get: function () {
  12722. return Light._LIGHTMAP_SHADOWSONLY;
  12723. },
  12724. enumerable: true,
  12725. configurable: true
  12726. });
  12727. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  12728. get: function () {
  12729. return this._includedOnlyMeshes;
  12730. },
  12731. set: function (value) {
  12732. this._includedOnlyMeshes = value;
  12733. this._hookArrayForIncludedOnly(value);
  12734. },
  12735. enumerable: true,
  12736. configurable: true
  12737. });
  12738. Object.defineProperty(Light.prototype, "excludedMeshes", {
  12739. get: function () {
  12740. return this._excludedMeshes;
  12741. },
  12742. set: function (value) {
  12743. this._excludedMeshes = value;
  12744. this._hookArrayForExcluded(value);
  12745. },
  12746. enumerable: true,
  12747. configurable: true
  12748. });
  12749. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  12750. get: function () {
  12751. return this._excludeWithLayerMask;
  12752. },
  12753. set: function (value) {
  12754. this._excludeWithLayerMask = value;
  12755. this._resyncMeshes();
  12756. },
  12757. enumerable: true,
  12758. configurable: true
  12759. });
  12760. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  12761. get: function () {
  12762. return this._includeOnlyWithLayerMask;
  12763. },
  12764. set: function (value) {
  12765. this._includeOnlyWithLayerMask = value;
  12766. this._resyncMeshes();
  12767. },
  12768. enumerable: true,
  12769. configurable: true
  12770. });
  12771. Object.defineProperty(Light.prototype, "lightmapMode", {
  12772. get: function () {
  12773. return this._lightmapMode;
  12774. },
  12775. set: function (value) {
  12776. if (this._lightmapMode === value) {
  12777. return;
  12778. }
  12779. this._lightmapMode = value;
  12780. this._markMeshesAsLightDirty();
  12781. },
  12782. enumerable: true,
  12783. configurable: true
  12784. });
  12785. Light.prototype._buildUniformLayout = function () {
  12786. // Overridden
  12787. };
  12788. /**
  12789. * Returns the string "Light".
  12790. */
  12791. Light.prototype.getClassName = function () {
  12792. return "Light";
  12793. };
  12794. /**
  12795. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12796. */
  12797. Light.prototype.toString = function (fullDetails) {
  12798. var ret = "Name: " + this.name;
  12799. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  12800. if (this.animations) {
  12801. for (var i = 0; i < this.animations.length; i++) {
  12802. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12803. }
  12804. }
  12805. if (fullDetails) {
  12806. }
  12807. return ret;
  12808. };
  12809. /**
  12810. * Set the enabled state of this node.
  12811. * @param {boolean} value - the new enabled state
  12812. * @see isEnabled
  12813. */
  12814. Light.prototype.setEnabled = function (value) {
  12815. _super.prototype.setEnabled.call(this, value);
  12816. this._resyncMeshes();
  12817. };
  12818. /**
  12819. * Returns the Light associated shadow generator.
  12820. */
  12821. Light.prototype.getShadowGenerator = function () {
  12822. return this._shadowGenerator;
  12823. };
  12824. /**
  12825. * Returns a Vector3, the absolute light position in the World.
  12826. */
  12827. Light.prototype.getAbsolutePosition = function () {
  12828. return BABYLON.Vector3.Zero();
  12829. };
  12830. Light.prototype.transferToEffect = function (effect, lightIndex) {
  12831. };
  12832. Light.prototype._getWorldMatrix = function () {
  12833. return BABYLON.Matrix.Identity();
  12834. };
  12835. /**
  12836. * Boolean : True if the light will affect the passed mesh.
  12837. */
  12838. Light.prototype.canAffectMesh = function (mesh) {
  12839. if (!mesh) {
  12840. return true;
  12841. }
  12842. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  12843. return false;
  12844. }
  12845. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  12846. return false;
  12847. }
  12848. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  12849. return false;
  12850. }
  12851. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  12852. return false;
  12853. }
  12854. return true;
  12855. };
  12856. /**
  12857. * Returns the light World matrix.
  12858. */
  12859. Light.prototype.getWorldMatrix = function () {
  12860. this._currentRenderId = this.getScene().getRenderId();
  12861. var worldMatrix = this._getWorldMatrix();
  12862. if (this.parent && this.parent.getWorldMatrix) {
  12863. if (!this._parentedWorldMatrix) {
  12864. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  12865. }
  12866. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  12867. this._markSyncedWithParent();
  12868. return this._parentedWorldMatrix;
  12869. }
  12870. return worldMatrix;
  12871. };
  12872. /**
  12873. * Disposes the light.
  12874. */
  12875. Light.prototype.dispose = function () {
  12876. if (this._shadowGenerator) {
  12877. this._shadowGenerator.dispose();
  12878. this._shadowGenerator = null;
  12879. }
  12880. // Animations
  12881. this.getScene().stopAnimation(this);
  12882. // Remove from meshes
  12883. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  12884. var mesh = _a[_i];
  12885. mesh._removeLightSource(this);
  12886. }
  12887. this._uniformBuffer.dispose();
  12888. // Remove from scene
  12889. this.getScene().removeLight(this);
  12890. _super.prototype.dispose.call(this);
  12891. };
  12892. /**
  12893. * Returns the light type ID (integer).
  12894. */
  12895. Light.prototype.getTypeID = function () {
  12896. return 0;
  12897. };
  12898. /**
  12899. * Returns a new Light object, named "name", from the current one.
  12900. */
  12901. Light.prototype.clone = function (name) {
  12902. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  12903. };
  12904. /**
  12905. * Serializes the current light into a Serialization object.
  12906. * Returns the serialized object.
  12907. */
  12908. Light.prototype.serialize = function () {
  12909. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12910. // Type
  12911. serializationObject.type = this.getTypeID();
  12912. // Parent
  12913. if (this.parent) {
  12914. serializationObject.parentId = this.parent.id;
  12915. }
  12916. // Inclusion / exclusions
  12917. if (this.excludedMeshes.length > 0) {
  12918. serializationObject.excludedMeshesIds = [];
  12919. this.excludedMeshes.forEach(function (mesh) {
  12920. serializationObject.excludedMeshesIds.push(mesh.id);
  12921. });
  12922. }
  12923. if (this.includedOnlyMeshes.length > 0) {
  12924. serializationObject.includedOnlyMeshesIds = [];
  12925. this.includedOnlyMeshes.forEach(function (mesh) {
  12926. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  12927. });
  12928. }
  12929. // Animations
  12930. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12931. serializationObject.ranges = this.serializeAnimationRanges();
  12932. return serializationObject;
  12933. };
  12934. /**
  12935. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  12936. * This new light is named "name" and added to the passed scene.
  12937. */
  12938. Light.GetConstructorFromName = function (type, name, scene) {
  12939. switch (type) {
  12940. case 0:
  12941. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  12942. case 1:
  12943. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  12944. case 2:
  12945. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  12946. case 3:
  12947. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  12948. }
  12949. };
  12950. /**
  12951. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  12952. */
  12953. Light.Parse = function (parsedLight, scene) {
  12954. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  12955. // Inclusion / exclusions
  12956. if (parsedLight.excludedMeshesIds) {
  12957. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  12958. }
  12959. if (parsedLight.includedOnlyMeshesIds) {
  12960. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  12961. }
  12962. // Parent
  12963. if (parsedLight.parentId) {
  12964. light._waitingParentId = parsedLight.parentId;
  12965. }
  12966. // Animations
  12967. if (parsedLight.animations) {
  12968. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  12969. var parsedAnimation = parsedLight.animations[animationIndex];
  12970. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12971. }
  12972. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  12973. }
  12974. if (parsedLight.autoAnimate) {
  12975. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  12976. }
  12977. return light;
  12978. };
  12979. Light.prototype._hookArrayForExcluded = function (array) {
  12980. var _this = this;
  12981. var oldPush = array.push;
  12982. array.push = function () {
  12983. var items = [];
  12984. for (var _i = 0; _i < arguments.length; _i++) {
  12985. items[_i] = arguments[_i];
  12986. }
  12987. var result = oldPush.apply(array, items);
  12988. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  12989. var item = items_1[_a];
  12990. item._resyncLighSource(_this);
  12991. }
  12992. return result;
  12993. };
  12994. var oldSplice = array.splice;
  12995. array.splice = function (index, deleteCount) {
  12996. var deleted = oldSplice.apply(array, [index, deleteCount]);
  12997. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  12998. var item = deleted_1[_i];
  12999. item._resyncLighSource(_this);
  13000. }
  13001. return deleted;
  13002. };
  13003. };
  13004. Light.prototype._hookArrayForIncludedOnly = function (array) {
  13005. var _this = this;
  13006. var oldPush = array.push;
  13007. array.push = function () {
  13008. var items = [];
  13009. for (var _i = 0; _i < arguments.length; _i++) {
  13010. items[_i] = arguments[_i];
  13011. }
  13012. var result = oldPush.apply(array, items);
  13013. _this._resyncMeshes();
  13014. return result;
  13015. };
  13016. var oldSplice = array.splice;
  13017. array.splice = function (index, deleteCount) {
  13018. var deleted = oldSplice.apply(array, [index, deleteCount]);
  13019. _this._resyncMeshes();
  13020. return deleted;
  13021. };
  13022. };
  13023. Light.prototype._resyncMeshes = function () {
  13024. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13025. var mesh = _a[_i];
  13026. mesh._resyncLighSource(this);
  13027. }
  13028. };
  13029. Light.prototype._markMeshesAsLightDirty = function () {
  13030. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  13031. var mesh = _a[_i];
  13032. if (mesh._lightSources.indexOf(this) !== -1) {
  13033. mesh._markSubMeshesAsLightDirty();
  13034. }
  13035. }
  13036. };
  13037. return Light;
  13038. }(BABYLON.Node));
  13039. //lightmapMode Consts
  13040. Light._LIGHTMAP_DEFAULT = 0;
  13041. Light._LIGHTMAP_SPECULAR = 1;
  13042. Light._LIGHTMAP_SHADOWSONLY = 2;
  13043. __decorate([
  13044. BABYLON.serializeAsColor3()
  13045. ], Light.prototype, "diffuse", void 0);
  13046. __decorate([
  13047. BABYLON.serializeAsColor3()
  13048. ], Light.prototype, "specular", void 0);
  13049. __decorate([
  13050. BABYLON.serialize()
  13051. ], Light.prototype, "intensity", void 0);
  13052. __decorate([
  13053. BABYLON.serialize()
  13054. ], Light.prototype, "range", void 0);
  13055. __decorate([
  13056. BABYLON.serialize("excludeWithLayerMask")
  13057. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13058. __decorate([
  13059. BABYLON.serialize("includeOnlyWithLayerMask")
  13060. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13061. __decorate([
  13062. BABYLON.serialize("lightmapMode")
  13063. ], Light.prototype, "_lightmapMode", void 0);
  13064. __decorate([
  13065. BABYLON.serialize()
  13066. ], Light.prototype, "radius", void 0);
  13067. BABYLON.Light = Light;
  13068. })(BABYLON || (BABYLON = {}));
  13069. //# sourceMappingURL=babylon.light.js.map
  13070. var BABYLON;
  13071. (function (BABYLON) {
  13072. var Camera = (function (_super) {
  13073. __extends(Camera, _super);
  13074. function Camera(name, position, scene) {
  13075. var _this = _super.call(this, name, scene) || this;
  13076. _this.upVector = BABYLON.Vector3.Up();
  13077. _this.orthoLeft = null;
  13078. _this.orthoRight = null;
  13079. _this.orthoBottom = null;
  13080. _this.orthoTop = null;
  13081. _this.fov = 0.8;
  13082. _this.minZ = 1.0;
  13083. _this.maxZ = 10000.0;
  13084. _this.inertia = 0.9;
  13085. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13086. _this.isIntermediate = false;
  13087. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13088. _this.layerMask = 0x0FFFFFFF;
  13089. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13090. // Camera rig members
  13091. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13092. _this._rigCameras = new Array();
  13093. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13094. // Cache
  13095. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13096. _this._projectionMatrix = new BABYLON.Matrix();
  13097. _this._doNotComputeProjectionMatrix = false;
  13098. _this._postProcesses = new Array();
  13099. _this._transformMatrix = BABYLON.Matrix.Zero();
  13100. _this._activeMeshes = new BABYLON.SmartArray(256);
  13101. _this._globalPosition = BABYLON.Vector3.Zero();
  13102. _this._refreshFrustumPlanes = true;
  13103. _this.getScene().addCamera(_this);
  13104. if (!_this.getScene().activeCamera) {
  13105. _this.getScene().activeCamera = _this;
  13106. }
  13107. _this.position = position;
  13108. return _this;
  13109. }
  13110. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13111. get: function () {
  13112. return Camera._PERSPECTIVE_CAMERA;
  13113. },
  13114. enumerable: true,
  13115. configurable: true
  13116. });
  13117. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13118. get: function () {
  13119. return Camera._ORTHOGRAPHIC_CAMERA;
  13120. },
  13121. enumerable: true,
  13122. configurable: true
  13123. });
  13124. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13125. get: function () {
  13126. return Camera._FOVMODE_VERTICAL_FIXED;
  13127. },
  13128. enumerable: true,
  13129. configurable: true
  13130. });
  13131. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13132. get: function () {
  13133. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13134. },
  13135. enumerable: true,
  13136. configurable: true
  13137. });
  13138. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13139. get: function () {
  13140. return Camera._RIG_MODE_NONE;
  13141. },
  13142. enumerable: true,
  13143. configurable: true
  13144. });
  13145. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13146. get: function () {
  13147. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13148. },
  13149. enumerable: true,
  13150. configurable: true
  13151. });
  13152. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13153. get: function () {
  13154. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13155. },
  13156. enumerable: true,
  13157. configurable: true
  13158. });
  13159. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13160. get: function () {
  13161. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13162. },
  13163. enumerable: true,
  13164. configurable: true
  13165. });
  13166. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13167. get: function () {
  13168. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13169. },
  13170. enumerable: true,
  13171. configurable: true
  13172. });
  13173. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13174. get: function () {
  13175. return Camera._RIG_MODE_VR;
  13176. },
  13177. enumerable: true,
  13178. configurable: true
  13179. });
  13180. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13181. get: function () {
  13182. return Camera._RIG_MODE_WEBVR;
  13183. },
  13184. enumerable: true,
  13185. configurable: true
  13186. });
  13187. Camera.prototype.getClassName = function () {
  13188. return "Camera";
  13189. };
  13190. /**
  13191. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13192. */
  13193. Camera.prototype.toString = function (fullDetails) {
  13194. var ret = "Name: " + this.name;
  13195. ret += ", type: " + this.getClassName();
  13196. if (this.animations) {
  13197. for (var i = 0; i < this.animations.length; i++) {
  13198. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13199. }
  13200. }
  13201. if (fullDetails) {
  13202. }
  13203. return ret;
  13204. };
  13205. Object.defineProperty(Camera.prototype, "globalPosition", {
  13206. get: function () {
  13207. return this._globalPosition;
  13208. },
  13209. enumerable: true,
  13210. configurable: true
  13211. });
  13212. Camera.prototype.getActiveMeshes = function () {
  13213. return this._activeMeshes;
  13214. };
  13215. Camera.prototype.isActiveMesh = function (mesh) {
  13216. return (this._activeMeshes.indexOf(mesh) !== -1);
  13217. };
  13218. //Cache
  13219. Camera.prototype._initCache = function () {
  13220. _super.prototype._initCache.call(this);
  13221. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13222. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13223. this._cache.mode = undefined;
  13224. this._cache.minZ = undefined;
  13225. this._cache.maxZ = undefined;
  13226. this._cache.fov = undefined;
  13227. this._cache.fovMode = undefined;
  13228. this._cache.aspectRatio = undefined;
  13229. this._cache.orthoLeft = undefined;
  13230. this._cache.orthoRight = undefined;
  13231. this._cache.orthoBottom = undefined;
  13232. this._cache.orthoTop = undefined;
  13233. this._cache.renderWidth = undefined;
  13234. this._cache.renderHeight = undefined;
  13235. };
  13236. Camera.prototype._updateCache = function (ignoreParentClass) {
  13237. if (!ignoreParentClass) {
  13238. _super.prototype._updateCache.call(this);
  13239. }
  13240. var engine = this.getEngine();
  13241. this._cache.position.copyFrom(this.position);
  13242. this._cache.upVector.copyFrom(this.upVector);
  13243. this._cache.mode = this.mode;
  13244. this._cache.minZ = this.minZ;
  13245. this._cache.maxZ = this.maxZ;
  13246. this._cache.fov = this.fov;
  13247. this._cache.fovMode = this.fovMode;
  13248. this._cache.aspectRatio = engine.getAspectRatio(this);
  13249. this._cache.orthoLeft = this.orthoLeft;
  13250. this._cache.orthoRight = this.orthoRight;
  13251. this._cache.orthoBottom = this.orthoBottom;
  13252. this._cache.orthoTop = this.orthoTop;
  13253. this._cache.renderWidth = engine.getRenderWidth();
  13254. this._cache.renderHeight = engine.getRenderHeight();
  13255. };
  13256. Camera.prototype._updateFromScene = function () {
  13257. this.updateCache();
  13258. this.update();
  13259. };
  13260. // Synchronized
  13261. Camera.prototype._isSynchronized = function () {
  13262. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13263. };
  13264. Camera.prototype._isSynchronizedViewMatrix = function () {
  13265. if (!_super.prototype._isSynchronized.call(this))
  13266. return false;
  13267. return this._cache.position.equals(this.position)
  13268. && this._cache.upVector.equals(this.upVector)
  13269. && this.isSynchronizedWithParent();
  13270. };
  13271. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13272. var check = this._cache.mode === this.mode
  13273. && this._cache.minZ === this.minZ
  13274. && this._cache.maxZ === this.maxZ;
  13275. if (!check) {
  13276. return false;
  13277. }
  13278. var engine = this.getEngine();
  13279. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13280. check = this._cache.fov === this.fov
  13281. && this._cache.fovMode === this.fovMode
  13282. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13283. }
  13284. else {
  13285. check = this._cache.orthoLeft === this.orthoLeft
  13286. && this._cache.orthoRight === this.orthoRight
  13287. && this._cache.orthoBottom === this.orthoBottom
  13288. && this._cache.orthoTop === this.orthoTop
  13289. && this._cache.renderWidth === engine.getRenderWidth()
  13290. && this._cache.renderHeight === engine.getRenderHeight();
  13291. }
  13292. return check;
  13293. };
  13294. // Controls
  13295. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13296. };
  13297. Camera.prototype.detachControl = function (element) {
  13298. };
  13299. Camera.prototype.update = function () {
  13300. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13301. this._updateRigCameras();
  13302. }
  13303. this._checkInputs();
  13304. };
  13305. Camera.prototype._checkInputs = function () {
  13306. };
  13307. Object.defineProperty(Camera.prototype, "rigCameras", {
  13308. get: function () {
  13309. return this._rigCameras;
  13310. },
  13311. enumerable: true,
  13312. configurable: true
  13313. });
  13314. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  13315. get: function () {
  13316. return this._rigPostProcess;
  13317. },
  13318. enumerable: true,
  13319. configurable: true
  13320. });
  13321. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13322. // invalidate framebuffer
  13323. if (this._postProcesses.length > 0) {
  13324. this._postProcesses[0].markTextureDirty();
  13325. }
  13326. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13327. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13328. var cam = this._rigCameras[i];
  13329. var rigPostProcess = cam._rigPostProcess;
  13330. // for VR rig, there does not have to be a post process
  13331. if (rigPostProcess) {
  13332. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13333. if (isPass) {
  13334. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13335. cam.isIntermediate = this._postProcesses.length === 0;
  13336. }
  13337. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13338. rigPostProcess.markTextureDirty();
  13339. }
  13340. else {
  13341. cam._postProcesses = this._postProcesses.slice(0);
  13342. }
  13343. }
  13344. };
  13345. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13346. if (insertAt === void 0) { insertAt = null; }
  13347. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13348. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13349. return 0;
  13350. }
  13351. if (insertAt == null || insertAt < 0) {
  13352. this._postProcesses.push(postProcess);
  13353. }
  13354. else {
  13355. this._postProcesses.splice(insertAt, 0, postProcess);
  13356. }
  13357. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13358. return this._postProcesses.indexOf(postProcess);
  13359. };
  13360. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13361. if (atIndices === void 0) { atIndices = null; }
  13362. var result = [];
  13363. var i;
  13364. var index;
  13365. if (!atIndices) {
  13366. var idx = this._postProcesses.indexOf(postProcess);
  13367. if (idx !== -1) {
  13368. this._postProcesses.splice(idx, 1);
  13369. }
  13370. }
  13371. else {
  13372. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13373. // iterate descending, so can just splice as we go
  13374. for (i = atIndices.length - 1; i >= 0; i--) {
  13375. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13376. result.push(i);
  13377. continue;
  13378. }
  13379. index = atIndices[i];
  13380. this._postProcesses.splice(index, 1);
  13381. }
  13382. }
  13383. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13384. return result;
  13385. };
  13386. Camera.prototype.getWorldMatrix = function () {
  13387. if (!this._worldMatrix) {
  13388. this._worldMatrix = BABYLON.Matrix.Identity();
  13389. }
  13390. var viewMatrix = this.getViewMatrix();
  13391. viewMatrix.invertToRef(this._worldMatrix);
  13392. return this._worldMatrix;
  13393. };
  13394. Camera.prototype._getViewMatrix = function () {
  13395. return BABYLON.Matrix.Identity();
  13396. };
  13397. Camera.prototype.getViewMatrix = function (force) {
  13398. this._computedViewMatrix = this._computeViewMatrix(force);
  13399. if (!force && this._isSynchronizedViewMatrix()) {
  13400. return this._computedViewMatrix;
  13401. }
  13402. this._refreshFrustumPlanes = true;
  13403. if (!this.parent || !this.parent.getWorldMatrix) {
  13404. this._globalPosition.copyFrom(this.position);
  13405. }
  13406. else {
  13407. if (!this._worldMatrix) {
  13408. this._worldMatrix = BABYLON.Matrix.Identity();
  13409. }
  13410. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13411. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13412. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13413. this._computedViewMatrix.invert();
  13414. this._markSyncedWithParent();
  13415. }
  13416. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  13417. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  13418. }
  13419. this._currentRenderId = this.getScene().getRenderId();
  13420. return this._computedViewMatrix;
  13421. };
  13422. Camera.prototype._computeViewMatrix = function (force) {
  13423. if (!force && this._isSynchronizedViewMatrix()) {
  13424. return this._computedViewMatrix;
  13425. }
  13426. this._computedViewMatrix = this._getViewMatrix();
  13427. this._currentRenderId = this.getScene().getRenderId();
  13428. return this._computedViewMatrix;
  13429. };
  13430. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13431. this._doNotComputeProjectionMatrix = true;
  13432. if (projection !== undefined) {
  13433. this._projectionMatrix = projection;
  13434. }
  13435. };
  13436. ;
  13437. Camera.prototype.unfreezeProjectionMatrix = function () {
  13438. this._doNotComputeProjectionMatrix = false;
  13439. };
  13440. ;
  13441. Camera.prototype.getProjectionMatrix = function (force) {
  13442. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13443. return this._projectionMatrix;
  13444. }
  13445. this._refreshFrustumPlanes = true;
  13446. var engine = this.getEngine();
  13447. var scene = this.getScene();
  13448. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13449. if (this.minZ <= 0) {
  13450. this.minZ = 0.1;
  13451. }
  13452. if (scene.useRightHandedSystem) {
  13453. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13454. }
  13455. else {
  13456. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13457. }
  13458. return this._projectionMatrix;
  13459. }
  13460. var halfWidth = engine.getRenderWidth() / 2.0;
  13461. var halfHeight = engine.getRenderHeight() / 2.0;
  13462. if (scene.useRightHandedSystem) {
  13463. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13464. }
  13465. else {
  13466. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13467. }
  13468. return this._projectionMatrix;
  13469. };
  13470. Camera.prototype.getTranformationMatrix = function () {
  13471. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13472. return this._transformMatrix;
  13473. };
  13474. Camera.prototype.updateFrustumPlanes = function () {
  13475. if (!this._refreshFrustumPlanes) {
  13476. return;
  13477. }
  13478. this.getTranformationMatrix();
  13479. if (!this._frustumPlanes) {
  13480. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13481. }
  13482. else {
  13483. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13484. }
  13485. this._refreshFrustumPlanes = false;
  13486. };
  13487. Camera.prototype.isInFrustum = function (target) {
  13488. this.updateFrustumPlanes();
  13489. return target.isInFrustum(this._frustumPlanes);
  13490. };
  13491. Camera.prototype.isCompletelyInFrustum = function (target) {
  13492. this.updateFrustumPlanes();
  13493. return target.isCompletelyInFrustum(this._frustumPlanes);
  13494. };
  13495. Camera.prototype.getForwardRay = function (length, transform, origin) {
  13496. if (length === void 0) { length = 100; }
  13497. if (!transform) {
  13498. transform = this.getWorldMatrix();
  13499. }
  13500. if (!origin) {
  13501. origin = this.position;
  13502. }
  13503. var forward = new BABYLON.Vector3(0, 0, 1);
  13504. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  13505. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  13506. return new BABYLON.Ray(origin, direction, length);
  13507. };
  13508. Camera.prototype.dispose = function () {
  13509. // Animations
  13510. this.getScene().stopAnimation(this);
  13511. // Remove from scene
  13512. this.getScene().removeCamera(this);
  13513. while (this._rigCameras.length > 0) {
  13514. this._rigCameras.pop().dispose();
  13515. }
  13516. // Postprocesses
  13517. var i = this._postProcesses.length;
  13518. while (--i >= 0) {
  13519. this._postProcesses[i].dispose(this);
  13520. }
  13521. _super.prototype.dispose.call(this);
  13522. };
  13523. Object.defineProperty(Camera.prototype, "leftCamera", {
  13524. // ---- Camera rigs section ----
  13525. get: function () {
  13526. if (this._rigCameras.length < 1) {
  13527. return undefined;
  13528. }
  13529. return this._rigCameras[0];
  13530. },
  13531. enumerable: true,
  13532. configurable: true
  13533. });
  13534. Object.defineProperty(Camera.prototype, "rightCamera", {
  13535. get: function () {
  13536. if (this._rigCameras.length < 2) {
  13537. return undefined;
  13538. }
  13539. return this._rigCameras[1];
  13540. },
  13541. enumerable: true,
  13542. configurable: true
  13543. });
  13544. Camera.prototype.getLeftTarget = function () {
  13545. if (this._rigCameras.length < 1) {
  13546. return undefined;
  13547. }
  13548. return this._rigCameras[0].getTarget();
  13549. };
  13550. Camera.prototype.getRightTarget = function () {
  13551. if (this._rigCameras.length < 2) {
  13552. return undefined;
  13553. }
  13554. return this._rigCameras[1].getTarget();
  13555. };
  13556. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13557. while (this._rigCameras.length > 0) {
  13558. this._rigCameras.pop().dispose();
  13559. }
  13560. this.cameraRigMode = mode;
  13561. this._cameraRigParams = {};
  13562. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13563. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13564. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13565. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13566. // create the rig cameras, unless none
  13567. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13568. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13569. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13570. }
  13571. switch (this.cameraRigMode) {
  13572. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13573. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13574. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13575. break;
  13576. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13577. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13578. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13579. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13580. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13581. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13582. break;
  13583. case Camera.RIG_MODE_VR:
  13584. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13585. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13586. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13587. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13588. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13589. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13590. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13591. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13592. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13593. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13594. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13595. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13596. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13597. if (metrics.compensateDistortion) {
  13598. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13599. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13600. }
  13601. break;
  13602. case Camera.RIG_MODE_WEBVR:
  13603. if (rigParams.vrDisplay) {
  13604. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13605. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13606. //Left eye
  13607. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13608. this._rigCameras[0].setCameraRigParameter("left", true);
  13609. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  13610. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  13611. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13612. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  13613. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13614. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13615. this._rigCameras[0].parent = this;
  13616. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13617. //Right eye
  13618. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13619. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  13620. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  13621. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13622. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  13623. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13624. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13625. this._rigCameras[1].parent = this;
  13626. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  13627. }
  13628. break;
  13629. }
  13630. this._cascadePostProcessesToRigCams();
  13631. this.
  13632. update();
  13633. };
  13634. Camera.prototype._getVRProjectionMatrix = function () {
  13635. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13636. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13637. return this._projectionMatrix;
  13638. };
  13639. Camera.prototype._updateCameraRotationMatrix = function () {
  13640. //Here for WebVR
  13641. };
  13642. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  13643. //Here for WebVR
  13644. };
  13645. /**
  13646. * This function MUST be overwritten by the different WebVR cameras available.
  13647. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  13648. */
  13649. Camera.prototype._getWebVRProjectionMatrix = function () {
  13650. return BABYLON.Matrix.Identity();
  13651. };
  13652. /**
  13653. * This function MUST be overwritten by the different WebVR cameras available.
  13654. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  13655. */
  13656. Camera.prototype._getWebVRViewMatrix = function () {
  13657. return BABYLON.Matrix.Identity();
  13658. };
  13659. Camera.prototype.setCameraRigParameter = function (name, value) {
  13660. if (!this._cameraRigParams) {
  13661. this._cameraRigParams = {};
  13662. }
  13663. this._cameraRigParams[name] = value;
  13664. //provisionnally:
  13665. if (name === "interaxialDistance") {
  13666. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13667. }
  13668. };
  13669. /**
  13670. * needs to be overridden by children so sub has required properties to be copied
  13671. */
  13672. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13673. return null;
  13674. };
  13675. /**
  13676. * May need to be overridden by children
  13677. */
  13678. Camera.prototype._updateRigCameras = function () {
  13679. for (var i = 0; i < this._rigCameras.length; i++) {
  13680. this._rigCameras[i].minZ = this.minZ;
  13681. this._rigCameras[i].maxZ = this.maxZ;
  13682. this._rigCameras[i].fov = this.fov;
  13683. }
  13684. // only update viewport when ANAGLYPH
  13685. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13686. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13687. }
  13688. };
  13689. Camera.prototype._setupInputs = function () {
  13690. };
  13691. Camera.prototype.serialize = function () {
  13692. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13693. // Type
  13694. serializationObject.type = this.getClassName();
  13695. // Parent
  13696. if (this.parent) {
  13697. serializationObject.parentId = this.parent.id;
  13698. }
  13699. if (this.inputs) {
  13700. this.inputs.serialize(serializationObject);
  13701. }
  13702. // Animations
  13703. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13704. serializationObject.ranges = this.serializeAnimationRanges();
  13705. return serializationObject;
  13706. };
  13707. Camera.prototype.clone = function (name) {
  13708. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13709. };
  13710. Camera.prototype.getDirection = function (localAxis) {
  13711. var result = BABYLON.Vector3.Zero();
  13712. this.getDirectionToRef(localAxis, result);
  13713. return result;
  13714. };
  13715. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  13716. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13717. };
  13718. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13719. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13720. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13721. switch (type) {
  13722. case "ArcRotateCamera":
  13723. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13724. case "DeviceOrientationCamera":
  13725. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13726. case "FollowCamera":
  13727. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13728. case "ArcFollowCamera":
  13729. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13730. case "GamepadCamera":
  13731. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13732. case "TouchCamera":
  13733. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13734. case "VirtualJoysticksCamera":
  13735. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13736. case "WebVRFreeCamera":
  13737. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13738. case "WebVRGamepadCamera":
  13739. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13740. case "VRDeviceOrientationFreeCamera":
  13741. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13742. case "VRDeviceOrientationGamepadCamera":
  13743. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13744. case "AnaglyphArcRotateCamera":
  13745. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13746. case "AnaglyphFreeCamera":
  13747. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13748. case "AnaglyphGamepadCamera":
  13749. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13750. case "AnaglyphUniversalCamera":
  13751. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13752. case "StereoscopicArcRotateCamera":
  13753. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13754. case "StereoscopicFreeCamera":
  13755. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13756. case "StereoscopicGamepadCamera":
  13757. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13758. case "StereoscopicUniversalCamera":
  13759. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13760. case "FreeCamera":
  13761. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13762. default:
  13763. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13764. }
  13765. };
  13766. Camera.Parse = function (parsedCamera, scene) {
  13767. var type = parsedCamera.type;
  13768. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13769. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13770. // Parent
  13771. if (parsedCamera.parentId) {
  13772. camera._waitingParentId = parsedCamera.parentId;
  13773. }
  13774. //If camera has an input manager, let it parse inputs settings
  13775. if (camera.inputs) {
  13776. camera.inputs.parse(parsedCamera);
  13777. camera._setupInputs();
  13778. }
  13779. // Target
  13780. if (parsedCamera.target) {
  13781. if (camera.setTarget) {
  13782. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13783. }
  13784. }
  13785. // Apply 3d rig, when found
  13786. if (parsedCamera.cameraRigMode) {
  13787. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13788. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13789. }
  13790. // Animations
  13791. if (parsedCamera.animations) {
  13792. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13793. var parsedAnimation = parsedCamera.animations[animationIndex];
  13794. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13795. }
  13796. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13797. }
  13798. if (parsedCamera.autoAnimate) {
  13799. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13800. }
  13801. return camera;
  13802. };
  13803. return Camera;
  13804. }(BABYLON.Node));
  13805. // Statics
  13806. Camera._PERSPECTIVE_CAMERA = 0;
  13807. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13808. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13809. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13810. Camera._RIG_MODE_NONE = 0;
  13811. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13812. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13813. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13814. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13815. Camera._RIG_MODE_VR = 20;
  13816. Camera._RIG_MODE_WEBVR = 21;
  13817. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13818. __decorate([
  13819. BABYLON.serializeAsVector3()
  13820. ], Camera.prototype, "position", void 0);
  13821. __decorate([
  13822. BABYLON.serializeAsVector3()
  13823. ], Camera.prototype, "upVector", void 0);
  13824. __decorate([
  13825. BABYLON.serialize()
  13826. ], Camera.prototype, "orthoLeft", void 0);
  13827. __decorate([
  13828. BABYLON.serialize()
  13829. ], Camera.prototype, "orthoRight", void 0);
  13830. __decorate([
  13831. BABYLON.serialize()
  13832. ], Camera.prototype, "orthoBottom", void 0);
  13833. __decorate([
  13834. BABYLON.serialize()
  13835. ], Camera.prototype, "orthoTop", void 0);
  13836. __decorate([
  13837. BABYLON.serialize()
  13838. ], Camera.prototype, "fov", void 0);
  13839. __decorate([
  13840. BABYLON.serialize()
  13841. ], Camera.prototype, "minZ", void 0);
  13842. __decorate([
  13843. BABYLON.serialize()
  13844. ], Camera.prototype, "maxZ", void 0);
  13845. __decorate([
  13846. BABYLON.serialize()
  13847. ], Camera.prototype, "inertia", void 0);
  13848. __decorate([
  13849. BABYLON.serialize()
  13850. ], Camera.prototype, "mode", void 0);
  13851. __decorate([
  13852. BABYLON.serialize()
  13853. ], Camera.prototype, "layerMask", void 0);
  13854. __decorate([
  13855. BABYLON.serialize()
  13856. ], Camera.prototype, "fovMode", void 0);
  13857. __decorate([
  13858. BABYLON.serialize()
  13859. ], Camera.prototype, "cameraRigMode", void 0);
  13860. __decorate([
  13861. BABYLON.serialize()
  13862. ], Camera.prototype, "interaxialDistance", void 0);
  13863. __decorate([
  13864. BABYLON.serialize()
  13865. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13866. BABYLON.Camera = Camera;
  13867. })(BABYLON || (BABYLON = {}));
  13868. //# sourceMappingURL=babylon.camera.js.map
  13869. var BABYLON;
  13870. (function (BABYLON) {
  13871. var RenderingManager = (function () {
  13872. function RenderingManager(scene) {
  13873. this._renderingGroups = new Array();
  13874. this._autoClearDepthStencil = {};
  13875. this._customOpaqueSortCompareFn = {};
  13876. this._customAlphaTestSortCompareFn = {};
  13877. this._customTransparentSortCompareFn = {};
  13878. this._renderinGroupInfo = null;
  13879. this._scene = scene;
  13880. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  13881. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  13882. }
  13883. }
  13884. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  13885. if (depth === void 0) { depth = true; }
  13886. if (stencil === void 0) { stencil = true; }
  13887. if (this._depthStencilBufferAlreadyCleaned) {
  13888. return;
  13889. }
  13890. this._scene.getEngine().clear(null, false, depth, stencil);
  13891. this._depthStencilBufferAlreadyCleaned = true;
  13892. };
  13893. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13894. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  13895. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  13896. var info = null;
  13897. if (observable) {
  13898. if (!this._renderinGroupInfo) {
  13899. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  13900. }
  13901. info = this._renderinGroupInfo;
  13902. info.scene = this._scene;
  13903. info.camera = this._scene.activeCamera;
  13904. }
  13905. // Dispatch sprites
  13906. if (renderSprites) {
  13907. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  13908. var manager = this._scene.spriteManagers[index];
  13909. this.dispatchSprites(manager);
  13910. }
  13911. }
  13912. // Render
  13913. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13914. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  13915. var renderingGroup = this._renderingGroups[index];
  13916. if (!renderingGroup && !observable)
  13917. continue;
  13918. this._currentIndex = index;
  13919. var renderingGroupMask = 0;
  13920. // Fire PRECLEAR stage
  13921. if (observable) {
  13922. renderingGroupMask = Math.pow(2, index);
  13923. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  13924. info.renderingGroupId = index;
  13925. observable.notifyObservers(info, renderingGroupMask);
  13926. }
  13927. // Clear depth/stencil if needed
  13928. var autoClear = this._autoClearDepthStencil[index];
  13929. if (autoClear && autoClear.autoClear) {
  13930. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  13931. }
  13932. if (observable) {
  13933. // Fire PREOPAQUE stage
  13934. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  13935. observable.notifyObservers(info, renderingGroupMask);
  13936. // Fire PRETRANSPARENT stage
  13937. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  13938. observable.notifyObservers(info, renderingGroupMask);
  13939. }
  13940. if (renderingGroup)
  13941. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  13942. // Fire POSTTRANSPARENT stage
  13943. if (observable) {
  13944. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  13945. observable.notifyObservers(info, renderingGroupMask);
  13946. }
  13947. }
  13948. };
  13949. RenderingManager.prototype.reset = function () {
  13950. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13951. var renderingGroup = this._renderingGroups[index];
  13952. if (renderingGroup) {
  13953. renderingGroup.prepare();
  13954. }
  13955. }
  13956. };
  13957. RenderingManager.prototype.dispose = function () {
  13958. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13959. var renderingGroup = this._renderingGroups[index];
  13960. if (renderingGroup) {
  13961. renderingGroup.dispose();
  13962. }
  13963. }
  13964. this._renderingGroups.length = 0;
  13965. };
  13966. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  13967. if (!this._renderingGroups[renderingGroupId]) {
  13968. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  13969. }
  13970. };
  13971. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  13972. var renderingGroupId = spriteManager.renderingGroupId || 0;
  13973. this._prepareRenderingGroup(renderingGroupId);
  13974. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  13975. };
  13976. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  13977. var renderingGroupId = particleSystem.renderingGroupId || 0;
  13978. this._prepareRenderingGroup(renderingGroupId);
  13979. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  13980. };
  13981. RenderingManager.prototype.dispatch = function (subMesh) {
  13982. var mesh = subMesh.getMesh();
  13983. var renderingGroupId = mesh.renderingGroupId || 0;
  13984. this._prepareRenderingGroup(renderingGroupId);
  13985. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13986. };
  13987. /**
  13988. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  13989. * This allowed control for front to back rendering or reversly depending of the special needs.
  13990. *
  13991. * @param renderingGroupId The rendering group id corresponding to its index
  13992. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  13993. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  13994. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  13995. */
  13996. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  13997. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  13998. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  13999. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14000. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  14001. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  14002. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  14003. if (this._renderingGroups[renderingGroupId]) {
  14004. var group = this._renderingGroups[renderingGroupId];
  14005. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  14006. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  14007. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  14008. }
  14009. };
  14010. /**
  14011. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  14012. *
  14013. * @param renderingGroupId The rendering group id corresponding to its index
  14014. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  14015. * @param depth Automatically clears depth between groups if true and autoClear is true.
  14016. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  14017. */
  14018. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  14019. if (depth === void 0) { depth = true; }
  14020. if (stencil === void 0) { stencil = true; }
  14021. this._autoClearDepthStencil[renderingGroupId] = {
  14022. autoClear: autoClearDepthStencil,
  14023. depth: depth,
  14024. stencil: stencil
  14025. };
  14026. };
  14027. return RenderingManager;
  14028. }());
  14029. /**
  14030. * The max id used for rendering groups (not included)
  14031. */
  14032. RenderingManager.MAX_RENDERINGGROUPS = 4;
  14033. /**
  14034. * The min id used for rendering groups (included)
  14035. */
  14036. RenderingManager.MIN_RENDERINGGROUPS = 0;
  14037. BABYLON.RenderingManager = RenderingManager;
  14038. })(BABYLON || (BABYLON = {}));
  14039. //# sourceMappingURL=babylon.renderingManager.js.map
  14040. var BABYLON;
  14041. (function (BABYLON) {
  14042. var RenderingGroup = (function () {
  14043. /**
  14044. * Creates a new rendering group.
  14045. * @param index The rendering group index
  14046. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  14047. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  14048. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  14049. */
  14050. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  14051. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  14052. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  14053. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  14054. this.index = index;
  14055. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  14056. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  14057. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  14058. this._particleSystems = new BABYLON.SmartArray(256);
  14059. this._spriteManagers = new BABYLON.SmartArray(256);
  14060. this._scene = scene;
  14061. this.opaqueSortCompareFn = opaqueSortCompareFn;
  14062. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  14063. this.transparentSortCompareFn = transparentSortCompareFn;
  14064. }
  14065. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  14066. /**
  14067. * Set the opaque sort comparison function.
  14068. * If null the sub meshes will be render in the order they were created
  14069. */
  14070. set: function (value) {
  14071. this._opaqueSortCompareFn = value;
  14072. if (value) {
  14073. this._renderOpaque = this.renderOpaqueSorted;
  14074. }
  14075. else {
  14076. this._renderOpaque = RenderingGroup.renderUnsorted;
  14077. }
  14078. },
  14079. enumerable: true,
  14080. configurable: true
  14081. });
  14082. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14083. /**
  14084. * Set the alpha test sort comparison function.
  14085. * If null the sub meshes will be render in the order they were created
  14086. */
  14087. set: function (value) {
  14088. this._alphaTestSortCompareFn = value;
  14089. if (value) {
  14090. this._renderAlphaTest = this.renderAlphaTestSorted;
  14091. }
  14092. else {
  14093. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14094. }
  14095. },
  14096. enumerable: true,
  14097. configurable: true
  14098. });
  14099. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14100. /**
  14101. * Set the transparent sort comparison function.
  14102. * If null the sub meshes will be render in the order they were created
  14103. */
  14104. set: function (value) {
  14105. if (value) {
  14106. this._transparentSortCompareFn = value;
  14107. }
  14108. else {
  14109. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14110. }
  14111. this._renderTransparent = this.renderTransparentSorted;
  14112. },
  14113. enumerable: true,
  14114. configurable: true
  14115. });
  14116. /**
  14117. * Render all the sub meshes contained in the group.
  14118. * @param customRenderFunction Used to override the default render behaviour of the group.
  14119. * @returns true if rendered some submeshes.
  14120. */
  14121. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14122. if (customRenderFunction) {
  14123. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14124. return;
  14125. }
  14126. var engine = this._scene.getEngine();
  14127. // Opaque
  14128. if (this._opaqueSubMeshes.length !== 0) {
  14129. this._renderOpaque(this._opaqueSubMeshes);
  14130. }
  14131. // Alpha test
  14132. if (this._alphaTestSubMeshes.length !== 0) {
  14133. engine.setAlphaTesting(true);
  14134. this._renderAlphaTest(this._alphaTestSubMeshes);
  14135. engine.setAlphaTesting(false);
  14136. }
  14137. var stencilState = engine.getStencilBuffer();
  14138. engine.setStencilBuffer(false);
  14139. // Sprites
  14140. if (renderSprites) {
  14141. this._renderSprites();
  14142. }
  14143. // Particles
  14144. if (renderParticles) {
  14145. this._renderParticles(activeMeshes);
  14146. }
  14147. if (this.onBeforeTransparentRendering) {
  14148. this.onBeforeTransparentRendering();
  14149. }
  14150. // Transparent
  14151. if (this._transparentSubMeshes.length !== 0) {
  14152. this._renderTransparent(this._transparentSubMeshes);
  14153. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14154. }
  14155. engine.setStencilBuffer(stencilState);
  14156. };
  14157. /**
  14158. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  14159. * @param subMeshes The submeshes to render
  14160. */
  14161. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  14162. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14163. };
  14164. /**
  14165. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  14166. * @param subMeshes The submeshes to render
  14167. */
  14168. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  14169. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14170. };
  14171. /**
  14172. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  14173. * @param subMeshes The submeshes to render
  14174. */
  14175. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  14176. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  14177. };
  14178. /**
  14179. * Renders the submeshes in a specified order.
  14180. * @param subMeshes The submeshes to sort before render
  14181. * @param sortCompareFn The comparison function use to sort
  14182. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  14183. * @param transparent Specifies to activate blending if true
  14184. */
  14185. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  14186. var subIndex = 0;
  14187. var subMesh;
  14188. for (; subIndex < subMeshes.length; subIndex++) {
  14189. subMesh = subMeshes.data[subIndex];
  14190. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  14191. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  14192. }
  14193. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  14194. sortedArray.sort(sortCompareFn);
  14195. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14196. subMesh = sortedArray[subIndex];
  14197. subMesh.render(transparent);
  14198. }
  14199. };
  14200. /**
  14201. * Renders the submeshes in the order they were dispatched (no sort applied).
  14202. * @param subMeshes The submeshes to render
  14203. */
  14204. RenderingGroup.renderUnsorted = function (subMeshes) {
  14205. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  14206. var submesh = subMeshes.data[subIndex];
  14207. submesh.render(false);
  14208. }
  14209. };
  14210. /**
  14211. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14212. * are rendered back to front if in the same alpha index.
  14213. *
  14214. * @param a The first submesh
  14215. * @param b The second submesh
  14216. * @returns The result of the comparison
  14217. */
  14218. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  14219. // Alpha index first
  14220. if (a._alphaIndex > b._alphaIndex) {
  14221. return 1;
  14222. }
  14223. if (a._alphaIndex < b._alphaIndex) {
  14224. return -1;
  14225. }
  14226. // Then distance to camera
  14227. return RenderingGroup.backToFrontSortCompare(a, b);
  14228. };
  14229. /**
  14230. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14231. * are rendered back to front.
  14232. *
  14233. * @param a The first submesh
  14234. * @param b The second submesh
  14235. * @returns The result of the comparison
  14236. */
  14237. RenderingGroup.backToFrontSortCompare = function (a, b) {
  14238. // Then distance to camera
  14239. if (a._distanceToCamera < b._distanceToCamera) {
  14240. return 1;
  14241. }
  14242. if (a._distanceToCamera > b._distanceToCamera) {
  14243. return -1;
  14244. }
  14245. return 0;
  14246. };
  14247. /**
  14248. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14249. * are rendered front to back (prevent overdraw).
  14250. *
  14251. * @param a The first submesh
  14252. * @param b The second submesh
  14253. * @returns The result of the comparison
  14254. */
  14255. RenderingGroup.frontToBackSortCompare = function (a, b) {
  14256. // Then distance to camera
  14257. if (a._distanceToCamera < b._distanceToCamera) {
  14258. return -1;
  14259. }
  14260. if (a._distanceToCamera > b._distanceToCamera) {
  14261. return 1;
  14262. }
  14263. return 0;
  14264. };
  14265. /**
  14266. * Resets the different lists of submeshes to prepare a new frame.
  14267. */
  14268. RenderingGroup.prototype.prepare = function () {
  14269. this._opaqueSubMeshes.reset();
  14270. this._transparentSubMeshes.reset();
  14271. this._alphaTestSubMeshes.reset();
  14272. this._particleSystems.reset();
  14273. this._spriteManagers.reset();
  14274. };
  14275. RenderingGroup.prototype.dispose = function () {
  14276. this._opaqueSubMeshes.dispose();
  14277. this._transparentSubMeshes.dispose();
  14278. this._alphaTestSubMeshes.dispose();
  14279. this._particleSystems.dispose();
  14280. this._spriteManagers.dispose();
  14281. };
  14282. /**
  14283. * Inserts the submesh in its correct queue depending on its material.
  14284. * @param subMesh The submesh to dispatch
  14285. */
  14286. RenderingGroup.prototype.dispatch = function (subMesh) {
  14287. var material = subMesh.getMaterial();
  14288. var mesh = subMesh.getMesh();
  14289. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14290. this._transparentSubMeshes.push(subMesh);
  14291. }
  14292. else if (material.needAlphaTesting()) {
  14293. this._alphaTestSubMeshes.push(subMesh);
  14294. }
  14295. else {
  14296. this._opaqueSubMeshes.push(subMesh); // Opaque
  14297. }
  14298. };
  14299. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  14300. this._spriteManagers.push(spriteManager);
  14301. };
  14302. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  14303. this._particleSystems.push(particleSystem);
  14304. };
  14305. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  14306. if (this._particleSystems.length === 0) {
  14307. return;
  14308. }
  14309. // Particles
  14310. var activeCamera = this._scene.activeCamera;
  14311. this._scene._particlesDuration.beginMonitoring();
  14312. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14313. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14314. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14315. continue;
  14316. }
  14317. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14318. this._scene._activeParticles.addCount(particleSystem.render(), false);
  14319. }
  14320. }
  14321. this._scene._particlesDuration.endMonitoring(false);
  14322. };
  14323. RenderingGroup.prototype._renderSprites = function () {
  14324. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  14325. return;
  14326. }
  14327. // Sprites
  14328. var activeCamera = this._scene.activeCamera;
  14329. this._scene._spritesDuration.beginMonitoring();
  14330. for (var id = 0; id < this._spriteManagers.length; id++) {
  14331. var spriteManager = this._spriteManagers.data[id];
  14332. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14333. spriteManager.render();
  14334. }
  14335. }
  14336. this._scene._spritesDuration.endMonitoring(false);
  14337. };
  14338. return RenderingGroup;
  14339. }());
  14340. BABYLON.RenderingGroup = RenderingGroup;
  14341. })(BABYLON || (BABYLON = {}));
  14342. //# sourceMappingURL=babylon.renderingGroup.js.map
  14343. var BABYLON;
  14344. (function (BABYLON) {
  14345. var ClickInfo = (function () {
  14346. function ClickInfo() {
  14347. this._singleClick = false;
  14348. this._doubleClick = false;
  14349. this._hasSwiped = false;
  14350. this._ignore = false;
  14351. }
  14352. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  14353. get: function () {
  14354. return this._singleClick;
  14355. },
  14356. set: function (b) {
  14357. this._singleClick = b;
  14358. },
  14359. enumerable: true,
  14360. configurable: true
  14361. });
  14362. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  14363. get: function () {
  14364. return this._doubleClick;
  14365. },
  14366. set: function (b) {
  14367. this._doubleClick = b;
  14368. },
  14369. enumerable: true,
  14370. configurable: true
  14371. });
  14372. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  14373. get: function () {
  14374. return this._hasSwiped;
  14375. },
  14376. set: function (b) {
  14377. this._hasSwiped = b;
  14378. },
  14379. enumerable: true,
  14380. configurable: true
  14381. });
  14382. Object.defineProperty(ClickInfo.prototype, "ignore", {
  14383. get: function () {
  14384. return this._ignore;
  14385. },
  14386. set: function (b) {
  14387. this._ignore = b;
  14388. },
  14389. enumerable: true,
  14390. configurable: true
  14391. });
  14392. return ClickInfo;
  14393. }());
  14394. var PointerEventTypes = (function () {
  14395. function PointerEventTypes() {
  14396. }
  14397. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14398. get: function () {
  14399. return PointerEventTypes._POINTERDOWN;
  14400. },
  14401. enumerable: true,
  14402. configurable: true
  14403. });
  14404. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14405. get: function () {
  14406. return PointerEventTypes._POINTERUP;
  14407. },
  14408. enumerable: true,
  14409. configurable: true
  14410. });
  14411. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14412. get: function () {
  14413. return PointerEventTypes._POINTERMOVE;
  14414. },
  14415. enumerable: true,
  14416. configurable: true
  14417. });
  14418. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14419. get: function () {
  14420. return PointerEventTypes._POINTERWHEEL;
  14421. },
  14422. enumerable: true,
  14423. configurable: true
  14424. });
  14425. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14426. get: function () {
  14427. return PointerEventTypes._POINTERPICK;
  14428. },
  14429. enumerable: true,
  14430. configurable: true
  14431. });
  14432. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  14433. get: function () {
  14434. return PointerEventTypes._POINTERTAP;
  14435. },
  14436. enumerable: true,
  14437. configurable: true
  14438. });
  14439. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  14440. get: function () {
  14441. return PointerEventTypes._POINTERDOUBLETAP;
  14442. },
  14443. enumerable: true,
  14444. configurable: true
  14445. });
  14446. return PointerEventTypes;
  14447. }());
  14448. PointerEventTypes._POINTERDOWN = 0x01;
  14449. PointerEventTypes._POINTERUP = 0x02;
  14450. PointerEventTypes._POINTERMOVE = 0x04;
  14451. PointerEventTypes._POINTERWHEEL = 0x08;
  14452. PointerEventTypes._POINTERPICK = 0x10;
  14453. PointerEventTypes._POINTERTAP = 0x20;
  14454. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  14455. BABYLON.PointerEventTypes = PointerEventTypes;
  14456. var PointerInfoBase = (function () {
  14457. function PointerInfoBase(type, event) {
  14458. this.type = type;
  14459. this.event = event;
  14460. }
  14461. return PointerInfoBase;
  14462. }());
  14463. BABYLON.PointerInfoBase = PointerInfoBase;
  14464. /**
  14465. * This class is used to store pointer related info for the onPrePointerObservable event.
  14466. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  14467. */
  14468. var PointerInfoPre = (function (_super) {
  14469. __extends(PointerInfoPre, _super);
  14470. function PointerInfoPre(type, event, localX, localY) {
  14471. var _this = _super.call(this, type, event) || this;
  14472. _this.skipOnPointerObservable = false;
  14473. _this.localPosition = new BABYLON.Vector2(localX, localY);
  14474. return _this;
  14475. }
  14476. return PointerInfoPre;
  14477. }(PointerInfoBase));
  14478. BABYLON.PointerInfoPre = PointerInfoPre;
  14479. /**
  14480. * This type contains all the data related to a pointer event in Babylon.js.
  14481. * 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.
  14482. */
  14483. var PointerInfo = (function (_super) {
  14484. __extends(PointerInfo, _super);
  14485. function PointerInfo(type, event, pickInfo) {
  14486. var _this = _super.call(this, type, event) || this;
  14487. _this.pickInfo = pickInfo;
  14488. return _this;
  14489. }
  14490. return PointerInfo;
  14491. }(PointerInfoBase));
  14492. BABYLON.PointerInfo = PointerInfo;
  14493. /**
  14494. * This class is used by the onRenderingGroupObservable
  14495. */
  14496. var RenderingGroupInfo = (function () {
  14497. function RenderingGroupInfo() {
  14498. }
  14499. return RenderingGroupInfo;
  14500. }());
  14501. /**
  14502. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  14503. * This stage will be fired no matter what
  14504. */
  14505. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  14506. /**
  14507. * Called before opaque object are rendered.
  14508. * This stage will be fired only if there's 3D Opaque content to render
  14509. */
  14510. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  14511. /**
  14512. * Called after the opaque objects are rendered and before the transparent ones
  14513. * This stage will be fired only if there's 3D transparent content to render
  14514. */
  14515. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  14516. /**
  14517. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  14518. * This stage will be fired no matter what
  14519. */
  14520. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  14521. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  14522. /**
  14523. * Represents a scene to be rendered by the engine.
  14524. * @see http://doc.babylonjs.com/page.php?p=21911
  14525. */
  14526. var Scene = (function () {
  14527. /**
  14528. * @constructor
  14529. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14530. */
  14531. function Scene(engine) {
  14532. // Members
  14533. this.autoClear = true;
  14534. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  14535. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14536. this.forceWireframe = false;
  14537. this._forcePointsCloud = false;
  14538. this.forceShowBoundingBoxes = false;
  14539. this.animationsEnabled = true;
  14540. this.constantlyUpdateMeshUnderPointer = false;
  14541. this.useRightHandedSystem = false;
  14542. this.hoverCursor = "pointer";
  14543. // Metadata
  14544. this.metadata = null;
  14545. // Events
  14546. /**
  14547. * An event triggered when the scene is disposed.
  14548. * @type {BABYLON.Observable}
  14549. */
  14550. this.onDisposeObservable = new BABYLON.Observable();
  14551. /**
  14552. * An event triggered before rendering the scene
  14553. * @type {BABYLON.Observable}
  14554. */
  14555. this.onBeforeRenderObservable = new BABYLON.Observable();
  14556. /**
  14557. * An event triggered after rendering the scene
  14558. * @type {BABYLON.Observable}
  14559. */
  14560. this.onAfterRenderObservable = new BABYLON.Observable();
  14561. /**
  14562. * An event triggered when the scene is ready
  14563. * @type {BABYLON.Observable}
  14564. */
  14565. this.onReadyObservable = new BABYLON.Observable();
  14566. /**
  14567. * An event triggered before rendering a camera
  14568. * @type {BABYLON.Observable}
  14569. */
  14570. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14571. /**
  14572. * An event triggered after rendering a camera
  14573. * @type {BABYLON.Observable}
  14574. */
  14575. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14576. /**
  14577. * An event triggered when a camera is created
  14578. * @type {BABYLON.Observable}
  14579. */
  14580. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14581. /**
  14582. * An event triggered when a camera is removed
  14583. * @type {BABYLON.Observable}
  14584. */
  14585. this.onCameraRemovedObservable = new BABYLON.Observable();
  14586. /**
  14587. * An event triggered when a light is created
  14588. * @type {BABYLON.Observable}
  14589. */
  14590. this.onNewLightAddedObservable = new BABYLON.Observable();
  14591. /**
  14592. * An event triggered when a light is removed
  14593. * @type {BABYLON.Observable}
  14594. */
  14595. this.onLightRemovedObservable = new BABYLON.Observable();
  14596. /**
  14597. * An event triggered when a geometry is created
  14598. * @type {BABYLON.Observable}
  14599. */
  14600. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14601. /**
  14602. * An event triggered when a geometry is removed
  14603. * @type {BABYLON.Observable}
  14604. */
  14605. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14606. /**
  14607. * An event triggered when a mesh is created
  14608. * @type {BABYLON.Observable}
  14609. */
  14610. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14611. /**
  14612. * An event triggered when a mesh is removed
  14613. * @type {BABYLON.Observable}
  14614. */
  14615. this.onMeshRemovedObservable = new BABYLON.Observable();
  14616. /**
  14617. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  14618. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  14619. * 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)
  14620. */
  14621. this.onRenderingGroupObservable = new BABYLON.Observable();
  14622. // Animations
  14623. this.animations = [];
  14624. /**
  14625. * 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).
  14626. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  14627. */
  14628. this.onPrePointerObservable = new BABYLON.Observable();
  14629. /**
  14630. * Observable event triggered each time an input event is received from the rendering canvas
  14631. */
  14632. this.onPointerObservable = new BABYLON.Observable();
  14633. this._meshPickProceed = false;
  14634. this._previousHasSwiped = false;
  14635. this._currentPickResult = null;
  14636. this._previousPickResult = null;
  14637. this._isButtonPressed = false;
  14638. this._doubleClickOccured = false;
  14639. 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
  14640. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14641. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  14642. this._startingPointerTime = 0;
  14643. this._previousStartingPointerTime = 0;
  14644. // Fog
  14645. /**
  14646. * is fog enabled on this scene.
  14647. * @type {boolean}
  14648. */
  14649. this._fogEnabled = true;
  14650. this._fogMode = Scene.FOGMODE_NONE;
  14651. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14652. this.fogDensity = 0.1;
  14653. this.fogStart = 0;
  14654. this.fogEnd = 1000.0;
  14655. // Lights
  14656. /**
  14657. * is shadow enabled on this scene.
  14658. * @type {boolean}
  14659. */
  14660. this._shadowsEnabled = true;
  14661. /**
  14662. * is light enabled on this scene.
  14663. * @type {boolean}
  14664. */
  14665. this._lightsEnabled = true;
  14666. /**
  14667. * All of the lights added to this scene.
  14668. * @see BABYLON.Light
  14669. * @type {BABYLON.Light[]}
  14670. */
  14671. this.lights = new Array();
  14672. // Cameras
  14673. /**
  14674. * All of the cameras added to this scene.
  14675. * @see BABYLON.Camera
  14676. * @type {BABYLON.Camera[]}
  14677. */
  14678. this.cameras = new Array();
  14679. this.activeCameras = new Array();
  14680. // Meshes
  14681. /**
  14682. * All of the (abstract) meshes added to this scene.
  14683. * @see BABYLON.AbstractMesh
  14684. * @type {BABYLON.AbstractMesh[]}
  14685. */
  14686. this.meshes = new Array();
  14687. // Geometries
  14688. this._geometries = new Array();
  14689. this.materials = new Array();
  14690. this.multiMaterials = new Array();
  14691. // Textures
  14692. this._texturesEnabled = true;
  14693. this.textures = new Array();
  14694. // Particles
  14695. this.particlesEnabled = true;
  14696. this.particleSystems = new Array();
  14697. // Sprites
  14698. this.spritesEnabled = true;
  14699. this.spriteManagers = new Array();
  14700. // Layers
  14701. this.layers = new Array();
  14702. this.highlightLayers = new Array();
  14703. // Skeletons
  14704. this._skeletonsEnabled = true;
  14705. this.skeletons = new Array();
  14706. // Morph targets
  14707. this.morphTargetManagers = new Array();
  14708. // Lens flares
  14709. this.lensFlaresEnabled = true;
  14710. this.lensFlareSystems = new Array();
  14711. // Collisions
  14712. this.collisionsEnabled = true;
  14713. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14714. // Postprocesses
  14715. this.postProcessesEnabled = true;
  14716. // Customs render targets
  14717. this.renderTargetsEnabled = true;
  14718. this.dumpNextRenderTargets = false;
  14719. this.customRenderTargets = new Array();
  14720. // Imported meshes
  14721. this.importedMeshesFiles = new Array();
  14722. // Probes
  14723. this.probesEnabled = true;
  14724. this.reflectionProbes = new Array();
  14725. this._actionManagers = new Array();
  14726. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14727. // Procedural textures
  14728. this.proceduralTexturesEnabled = true;
  14729. this._proceduralTextures = new Array();
  14730. this.soundTracks = new Array();
  14731. this._audioEnabled = true;
  14732. this._headphone = false;
  14733. // Performance counters
  14734. this._totalMeshesCounter = new BABYLON.PerfCounter();
  14735. this._totalLightsCounter = new BABYLON.PerfCounter();
  14736. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  14737. this._totalTexturesCounter = new BABYLON.PerfCounter();
  14738. this._totalVertices = new BABYLON.PerfCounter();
  14739. this._activeIndices = new BABYLON.PerfCounter();
  14740. this._activeParticles = new BABYLON.PerfCounter();
  14741. this._lastFrameDuration = new BABYLON.PerfCounter();
  14742. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  14743. this._renderTargetsDuration = new BABYLON.PerfCounter();
  14744. this._particlesDuration = new BABYLON.PerfCounter();
  14745. this._renderDuration = new BABYLON.PerfCounter();
  14746. this._spritesDuration = new BABYLON.PerfCounter();
  14747. this._activeBones = new BABYLON.PerfCounter();
  14748. this._animationTime = 0;
  14749. this.animationTimeScale = 1;
  14750. this._renderId = 0;
  14751. this._executeWhenReadyTimeoutId = -1;
  14752. this._intermediateRendering = false;
  14753. this._viewUpdateFlag = -1;
  14754. this._projectionUpdateFlag = -1;
  14755. this._toBeDisposed = new BABYLON.SmartArray(256);
  14756. this._pendingData = []; //ANY
  14757. this._activeMeshes = new BABYLON.SmartArray(256);
  14758. this._processedMaterials = new BABYLON.SmartArray(256);
  14759. this._renderTargets = new BABYLON.SmartArray(256);
  14760. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14761. this._activeSkeletons = new BABYLON.SmartArray(32);
  14762. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14763. this._activeAnimatables = new Array();
  14764. this._transformMatrix = BABYLON.Matrix.Zero();
  14765. this._edgesRenderers = new BABYLON.SmartArray(16);
  14766. this._uniqueIdCounter = 0;
  14767. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  14768. this._engine.scenes.push(this);
  14769. this._uid = null;
  14770. this._renderingManager = new BABYLON.RenderingManager(this);
  14771. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14772. if (BABYLON.OutlineRenderer) {
  14773. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14774. }
  14775. this.attachControl();
  14776. if (BABYLON.SoundTrack) {
  14777. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14778. }
  14779. //simplification queue
  14780. if (BABYLON.SimplificationQueue) {
  14781. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14782. }
  14783. //collision coordinator initialization. For now legacy per default.
  14784. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14785. // Uniform Buffer
  14786. this._createUbo();
  14787. }
  14788. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14789. get: function () {
  14790. return Scene._FOGMODE_NONE;
  14791. },
  14792. enumerable: true,
  14793. configurable: true
  14794. });
  14795. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14796. get: function () {
  14797. return Scene._FOGMODE_EXP;
  14798. },
  14799. enumerable: true,
  14800. configurable: true
  14801. });
  14802. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14803. get: function () {
  14804. return Scene._FOGMODE_EXP2;
  14805. },
  14806. enumerable: true,
  14807. configurable: true
  14808. });
  14809. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14810. get: function () {
  14811. return Scene._FOGMODE_LINEAR;
  14812. },
  14813. enumerable: true,
  14814. configurable: true
  14815. });
  14816. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  14817. get: function () {
  14818. return this._forcePointsCloud;
  14819. },
  14820. set: function (value) {
  14821. if (this._forcePointsCloud === value) {
  14822. return;
  14823. }
  14824. this._forcePointsCloud = value;
  14825. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14826. },
  14827. enumerable: true,
  14828. configurable: true
  14829. });
  14830. Object.defineProperty(Scene.prototype, "onDispose", {
  14831. set: function (callback) {
  14832. if (this._onDisposeObserver) {
  14833. this.onDisposeObservable.remove(this._onDisposeObserver);
  14834. }
  14835. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14836. },
  14837. enumerable: true,
  14838. configurable: true
  14839. });
  14840. Object.defineProperty(Scene.prototype, "beforeRender", {
  14841. set: function (callback) {
  14842. if (this._onBeforeRenderObserver) {
  14843. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14844. }
  14845. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14846. },
  14847. enumerable: true,
  14848. configurable: true
  14849. });
  14850. Object.defineProperty(Scene.prototype, "afterRender", {
  14851. set: function (callback) {
  14852. if (this._onAfterRenderObserver) {
  14853. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14854. }
  14855. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14856. },
  14857. enumerable: true,
  14858. configurable: true
  14859. });
  14860. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14861. set: function (callback) {
  14862. if (this._onBeforeCameraRenderObserver) {
  14863. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14864. }
  14865. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14866. },
  14867. enumerable: true,
  14868. configurable: true
  14869. });
  14870. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14871. set: function (callback) {
  14872. if (this._onAfterCameraRenderObserver) {
  14873. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14874. }
  14875. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14876. },
  14877. enumerable: true,
  14878. configurable: true
  14879. });
  14880. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  14881. get: function () {
  14882. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  14883. },
  14884. enumerable: true,
  14885. configurable: true
  14886. });
  14887. Object.defineProperty(Scene.prototype, "fogEnabled", {
  14888. get: function () {
  14889. return this._fogEnabled;
  14890. },
  14891. set: function (value) {
  14892. if (this._fogEnabled === value) {
  14893. return;
  14894. }
  14895. this._fogEnabled = value;
  14896. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14897. },
  14898. enumerable: true,
  14899. configurable: true
  14900. });
  14901. Object.defineProperty(Scene.prototype, "fogMode", {
  14902. get: function () {
  14903. return this._fogMode;
  14904. },
  14905. set: function (value) {
  14906. if (this._fogMode === value) {
  14907. return;
  14908. }
  14909. this._fogMode = value;
  14910. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14911. },
  14912. enumerable: true,
  14913. configurable: true
  14914. });
  14915. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  14916. get: function () {
  14917. return this._shadowsEnabled;
  14918. },
  14919. set: function (value) {
  14920. if (this._shadowsEnabled === value) {
  14921. return;
  14922. }
  14923. this._shadowsEnabled = value;
  14924. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  14925. },
  14926. enumerable: true,
  14927. configurable: true
  14928. });
  14929. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  14930. get: function () {
  14931. return this._lightsEnabled;
  14932. },
  14933. set: function (value) {
  14934. if (this._lightsEnabled === value) {
  14935. return;
  14936. }
  14937. this._lightsEnabled = value;
  14938. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  14939. },
  14940. enumerable: true,
  14941. configurable: true
  14942. });
  14943. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  14944. get: function () {
  14945. if (!this._defaultMaterial) {
  14946. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14947. }
  14948. return this._defaultMaterial;
  14949. },
  14950. enumerable: true,
  14951. configurable: true
  14952. });
  14953. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  14954. get: function () {
  14955. return this._texturesEnabled;
  14956. },
  14957. set: function (value) {
  14958. if (this._texturesEnabled === value) {
  14959. return;
  14960. }
  14961. this._texturesEnabled = value;
  14962. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  14963. },
  14964. enumerable: true,
  14965. configurable: true
  14966. });
  14967. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  14968. get: function () {
  14969. return this._skeletonsEnabled;
  14970. },
  14971. set: function (value) {
  14972. if (this._skeletonsEnabled === value) {
  14973. return;
  14974. }
  14975. this._skeletonsEnabled = value;
  14976. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  14977. },
  14978. enumerable: true,
  14979. configurable: true
  14980. });
  14981. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  14982. get: function () {
  14983. if (!this._postProcessRenderPipelineManager) {
  14984. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14985. }
  14986. return this._postProcessRenderPipelineManager;
  14987. },
  14988. enumerable: true,
  14989. configurable: true
  14990. });
  14991. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  14992. get: function () {
  14993. return this._frustumPlanes;
  14994. },
  14995. enumerable: true,
  14996. configurable: true
  14997. });
  14998. Object.defineProperty(Scene.prototype, "debugLayer", {
  14999. // Properties
  15000. get: function () {
  15001. if (!this._debugLayer) {
  15002. this._debugLayer = new BABYLON.DebugLayer(this);
  15003. }
  15004. return this._debugLayer;
  15005. },
  15006. enumerable: true,
  15007. configurable: true
  15008. });
  15009. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15010. get: function () {
  15011. return this._workerCollisions;
  15012. },
  15013. set: function (enabled) {
  15014. if (!BABYLON.CollisionCoordinatorLegacy) {
  15015. return;
  15016. }
  15017. enabled = (enabled && !!Worker);
  15018. this._workerCollisions = enabled;
  15019. if (this.collisionCoordinator) {
  15020. this.collisionCoordinator.destroy();
  15021. }
  15022. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15023. this.collisionCoordinator.init(this);
  15024. },
  15025. enumerable: true,
  15026. configurable: true
  15027. });
  15028. Object.defineProperty(Scene.prototype, "selectionOctree", {
  15029. get: function () {
  15030. return this._selectionOctree;
  15031. },
  15032. enumerable: true,
  15033. configurable: true
  15034. });
  15035. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15036. /**
  15037. * The mesh that is currently under the pointer.
  15038. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15039. */
  15040. get: function () {
  15041. return this._pointerOverMesh;
  15042. },
  15043. enumerable: true,
  15044. configurable: true
  15045. });
  15046. Object.defineProperty(Scene.prototype, "pointerX", {
  15047. /**
  15048. * Current on-screen X position of the pointer
  15049. * @return {number} X position of the pointer
  15050. */
  15051. get: function () {
  15052. return this._pointerX;
  15053. },
  15054. enumerable: true,
  15055. configurable: true
  15056. });
  15057. Object.defineProperty(Scene.prototype, "pointerY", {
  15058. /**
  15059. * Current on-screen Y position of the pointer
  15060. * @return {number} Y position of the pointer
  15061. */
  15062. get: function () {
  15063. return this._pointerY;
  15064. },
  15065. enumerable: true,
  15066. configurable: true
  15067. });
  15068. Scene.prototype.getCachedMaterial = function () {
  15069. return this._cachedMaterial;
  15070. };
  15071. Scene.prototype.getCachedEffect = function () {
  15072. return this._cachedEffect;
  15073. };
  15074. Scene.prototype.getCachedVisibility = function () {
  15075. return this._cachedVisibility;
  15076. };
  15077. Scene.prototype.isCachedMaterialValid = function (material, effect, visibility) {
  15078. if (visibility === void 0) { visibility = 0; }
  15079. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  15080. };
  15081. Scene.prototype.getBoundingBoxRenderer = function () {
  15082. if (!this._boundingBoxRenderer) {
  15083. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15084. }
  15085. return this._boundingBoxRenderer;
  15086. };
  15087. Scene.prototype.getOutlineRenderer = function () {
  15088. return this._outlineRenderer;
  15089. };
  15090. Scene.prototype.getEngine = function () {
  15091. return this._engine;
  15092. };
  15093. Scene.prototype.getTotalVertices = function () {
  15094. return this._totalVertices.current;
  15095. };
  15096. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15097. get: function () {
  15098. return this._totalVertices;
  15099. },
  15100. enumerable: true,
  15101. configurable: true
  15102. });
  15103. Scene.prototype.getActiveIndices = function () {
  15104. return this._activeIndices.current;
  15105. };
  15106. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15107. get: function () {
  15108. return this._activeIndices;
  15109. },
  15110. enumerable: true,
  15111. configurable: true
  15112. });
  15113. Scene.prototype.getActiveParticles = function () {
  15114. return this._activeParticles.current;
  15115. };
  15116. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15117. get: function () {
  15118. return this._activeParticles;
  15119. },
  15120. enumerable: true,
  15121. configurable: true
  15122. });
  15123. Scene.prototype.getActiveBones = function () {
  15124. return this._activeBones.current;
  15125. };
  15126. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15127. get: function () {
  15128. return this._activeBones;
  15129. },
  15130. enumerable: true,
  15131. configurable: true
  15132. });
  15133. // Stats
  15134. Scene.prototype.getLastFrameDuration = function () {
  15135. return this._lastFrameDuration.current;
  15136. };
  15137. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15138. get: function () {
  15139. return this._lastFrameDuration;
  15140. },
  15141. enumerable: true,
  15142. configurable: true
  15143. });
  15144. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15145. return this._evaluateActiveMeshesDuration.current;
  15146. };
  15147. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15148. get: function () {
  15149. return this._evaluateActiveMeshesDuration;
  15150. },
  15151. enumerable: true,
  15152. configurable: true
  15153. });
  15154. Scene.prototype.getActiveMeshes = function () {
  15155. return this._activeMeshes;
  15156. };
  15157. Scene.prototype.getRenderTargetsDuration = function () {
  15158. return this._renderTargetsDuration.current;
  15159. };
  15160. Scene.prototype.getRenderDuration = function () {
  15161. return this._renderDuration.current;
  15162. };
  15163. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15164. get: function () {
  15165. return this._renderDuration;
  15166. },
  15167. enumerable: true,
  15168. configurable: true
  15169. });
  15170. Scene.prototype.getParticlesDuration = function () {
  15171. return this._particlesDuration.current;
  15172. };
  15173. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15174. get: function () {
  15175. return this._particlesDuration;
  15176. },
  15177. enumerable: true,
  15178. configurable: true
  15179. });
  15180. Scene.prototype.getSpritesDuration = function () {
  15181. return this._spritesDuration.current;
  15182. };
  15183. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15184. get: function () {
  15185. return this._spritesDuration;
  15186. },
  15187. enumerable: true,
  15188. configurable: true
  15189. });
  15190. Scene.prototype.getAnimationRatio = function () {
  15191. return this._animationRatio;
  15192. };
  15193. Scene.prototype.getRenderId = function () {
  15194. return this._renderId;
  15195. };
  15196. Scene.prototype.incrementRenderId = function () {
  15197. this._renderId++;
  15198. };
  15199. Scene.prototype._updatePointerPosition = function (evt) {
  15200. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15201. this._pointerX = evt.clientX - canvasRect.left;
  15202. this._pointerY = evt.clientY - canvasRect.top;
  15203. this._unTranslatedPointerX = this._pointerX;
  15204. this._unTranslatedPointerY = this._pointerY;
  15205. if (this.cameraToUseForPointers) {
  15206. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15207. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15208. }
  15209. };
  15210. Scene.prototype._createUbo = function () {
  15211. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  15212. this._sceneUbo.addUniform("viewProjection", 16);
  15213. this._sceneUbo.addUniform("view", 16);
  15214. };
  15215. // Pointers handling
  15216. /**
  15217. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15218. * @param attachUp defines if you want to attach events to pointerup
  15219. * @param attachDown defines if you want to attach events to pointerdown
  15220. * @param attachMove defines if you want to attach events to pointermove
  15221. */
  15222. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15223. var _this = this;
  15224. if (attachUp === void 0) { attachUp = true; }
  15225. if (attachDown === void 0) { attachDown = true; }
  15226. if (attachMove === void 0) { attachMove = true; }
  15227. this._initActionManager = function (act, clickInfo) {
  15228. if (!_this._meshPickProceed) {
  15229. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15230. _this._currentPickResult = pickResult;
  15231. if (pickResult) {
  15232. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  15233. }
  15234. _this._meshPickProceed = true;
  15235. }
  15236. return act;
  15237. };
  15238. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  15239. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  15240. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  15241. btn !== _this._previousButtonPressed) {
  15242. _this._doubleClickOccured = false;
  15243. clickInfo.singleClick = true;
  15244. clickInfo.ignore = false;
  15245. cb(clickInfo, _this._currentPickResult);
  15246. }
  15247. };
  15248. this._initClickEvent = function (obs1, obs2, evt, cb) {
  15249. var clickInfo = new ClickInfo();
  15250. _this._currentPickResult = null;
  15251. var act;
  15252. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  15253. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  15254. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15255. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  15256. act = _this._initActionManager(act, clickInfo);
  15257. if (act)
  15258. checkPicking = act.hasPickTriggers;
  15259. }
  15260. if (checkPicking) {
  15261. var btn = evt.button;
  15262. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  15263. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  15264. if (!clickInfo.hasSwiped) {
  15265. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  15266. if (!checkSingleClickImmediately) {
  15267. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  15268. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15269. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15270. act = _this._initActionManager(act, clickInfo);
  15271. if (act)
  15272. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  15273. }
  15274. }
  15275. if (checkSingleClickImmediately) {
  15276. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  15277. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  15278. btn !== _this._previousButtonPressed) {
  15279. clickInfo.singleClick = true;
  15280. cb(clickInfo, _this._currentPickResult);
  15281. }
  15282. }
  15283. else {
  15284. // wait that no double click has been raised during the double click delay
  15285. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15286. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  15287. }
  15288. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  15289. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15290. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15291. act = _this._initActionManager(act, clickInfo);
  15292. if (act)
  15293. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  15294. }
  15295. if (checkDoubleClick) {
  15296. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  15297. if (btn === _this._previousButtonPressed &&
  15298. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  15299. !_this._doubleClickOccured) {
  15300. // pointer has not moved for 2 clicks, it's a double click
  15301. if (!clickInfo.hasSwiped &&
  15302. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  15303. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  15304. _this._previousStartingPointerTime = 0;
  15305. _this._doubleClickOccured = true;
  15306. clickInfo.doubleClick = true;
  15307. clickInfo.ignore = false;
  15308. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  15309. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  15310. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15311. cb(clickInfo, _this._currentPickResult);
  15312. }
  15313. else {
  15314. _this._doubleClickOccured = false;
  15315. _this._previousStartingPointerTime = _this._startingPointerTime;
  15316. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  15317. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  15318. _this._previousButtonPressed = btn;
  15319. _this._previousHasSwiped = clickInfo.hasSwiped;
  15320. if (Scene.ExclusiveDoubleClickMode) {
  15321. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  15322. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  15323. }
  15324. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15325. cb(clickInfo, _this._previousPickResult);
  15326. }
  15327. else {
  15328. cb(clickInfo, _this._currentPickResult);
  15329. }
  15330. }
  15331. }
  15332. else {
  15333. _this._doubleClickOccured = false;
  15334. _this._previousStartingPointerTime = _this._startingPointerTime;
  15335. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  15336. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  15337. _this._previousButtonPressed = btn;
  15338. _this._previousHasSwiped = clickInfo.hasSwiped;
  15339. }
  15340. }
  15341. }
  15342. }
  15343. clickInfo.ignore = true;
  15344. cb(clickInfo, _this._currentPickResult);
  15345. };
  15346. var spritePredicate = function (sprite) {
  15347. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  15348. };
  15349. this._onPointerMove = function (evt) {
  15350. _this._updatePointerPosition(evt);
  15351. // PreObservable support
  15352. if (_this.onPrePointerObservable.hasObservers()) {
  15353. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15354. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15355. _this.onPrePointerObservable.notifyObservers(pi, type);
  15356. if (pi.skipOnPointerObservable) {
  15357. return;
  15358. }
  15359. }
  15360. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15361. return;
  15362. }
  15363. var canvas = _this._engine.getRenderingCanvas();
  15364. if (!_this.pointerMovePredicate) {
  15365. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  15366. }
  15367. // Meshes
  15368. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  15369. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15370. _this.setPointerOverSprite(null);
  15371. _this.setPointerOverMesh(pickResult.pickedMesh);
  15372. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  15373. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  15374. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  15375. }
  15376. else {
  15377. canvas.style.cursor = _this.hoverCursor;
  15378. }
  15379. }
  15380. else {
  15381. canvas.style.cursor = "";
  15382. }
  15383. }
  15384. else {
  15385. _this.setPointerOverMesh(null);
  15386. // Sprites
  15387. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15388. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  15389. _this.setPointerOverSprite(pickResult.pickedSprite);
  15390. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  15391. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  15392. }
  15393. else {
  15394. canvas.style.cursor = _this.hoverCursor;
  15395. }
  15396. }
  15397. else {
  15398. _this.setPointerOverSprite(null);
  15399. // Restore pointer
  15400. canvas.style.cursor = "";
  15401. }
  15402. }
  15403. if (_this.onPointerMove) {
  15404. _this.onPointerMove(evt, pickResult);
  15405. }
  15406. if (_this.onPointerObservable.hasObservers()) {
  15407. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15408. var pi = new PointerInfo(type, evt, pickResult);
  15409. _this.onPointerObservable.notifyObservers(pi, type);
  15410. }
  15411. };
  15412. this._onPointerDown = function (evt) {
  15413. _this._isButtonPressed = true;
  15414. _this._pickedDownMesh = null;
  15415. _this._meshPickProceed = false;
  15416. _this._updatePointerPosition(evt);
  15417. // PreObservable support
  15418. if (_this.onPrePointerObservable.hasObservers()) {
  15419. var type = PointerEventTypes.POINTERDOWN;
  15420. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15421. _this.onPrePointerObservable.notifyObservers(pi, type);
  15422. if (pi.skipOnPointerObservable) {
  15423. return;
  15424. }
  15425. }
  15426. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15427. return;
  15428. }
  15429. _this._startingPointerPosition.x = _this._pointerX;
  15430. _this._startingPointerPosition.y = _this._pointerY;
  15431. _this._startingPointerTime = new Date().getTime();
  15432. if (!_this.pointerDownPredicate) {
  15433. _this.pointerDownPredicate = function (mesh) {
  15434. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  15435. };
  15436. }
  15437. // Meshes
  15438. _this._pickedDownMesh = null;
  15439. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15440. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15441. _this._pickedDownMesh = pickResult.pickedMesh;
  15442. var actionManager = pickResult.pickedMesh.actionManager;
  15443. if (actionManager) {
  15444. if (actionManager.hasPickTriggers) {
  15445. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15446. switch (evt.button) {
  15447. case 0:
  15448. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15449. break;
  15450. case 1:
  15451. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15452. break;
  15453. case 2:
  15454. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15455. break;
  15456. }
  15457. }
  15458. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15459. window.setTimeout((function () {
  15460. var _this = this;
  15461. 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);
  15462. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15463. if (this._isButtonPressed &&
  15464. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  15465. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  15466. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  15467. this._startingPointerTime = 0;
  15468. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15469. }
  15470. }
  15471. }).bind(_this), Scene.LongPressDelay);
  15472. }
  15473. }
  15474. }
  15475. if (_this.onPointerDown) {
  15476. _this.onPointerDown(evt, pickResult);
  15477. }
  15478. if (_this.onPointerObservable.hasObservers()) {
  15479. var type = PointerEventTypes.POINTERDOWN;
  15480. var pi = new PointerInfo(type, evt, pickResult);
  15481. _this.onPointerObservable.notifyObservers(pi, type);
  15482. }
  15483. // Sprites
  15484. _this._pickedDownSprite = null;
  15485. if (_this.spriteManagers.length > 0) {
  15486. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15487. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  15488. if (pickResult.pickedSprite.actionManager) {
  15489. _this._pickedDownSprite = pickResult.pickedSprite;
  15490. switch (evt.button) {
  15491. case 0:
  15492. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15493. break;
  15494. case 1:
  15495. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15496. break;
  15497. case 2:
  15498. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15499. break;
  15500. }
  15501. if (pickResult.pickedSprite.actionManager) {
  15502. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15503. }
  15504. }
  15505. }
  15506. }
  15507. };
  15508. this._onPointerUp = function (evt) {
  15509. _this._isButtonPressed = false;
  15510. _this._pickedUpMesh = null;
  15511. _this._meshPickProceed = false;
  15512. _this._updatePointerPosition(evt);
  15513. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  15514. // PreObservable support
  15515. if (this.onPrePointerObservable.hasObservers()) {
  15516. if (!clickInfo.ignore) {
  15517. if (!clickInfo.hasSwiped) {
  15518. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  15519. var type = PointerEventTypes.POINTERTAP;
  15520. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15521. this.onPrePointerObservable.notifyObservers(pi, type);
  15522. if (pi.skipOnPointerObservable) {
  15523. return;
  15524. }
  15525. }
  15526. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  15527. var type = PointerEventTypes.POINTERDOUBLETAP;
  15528. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15529. this.onPrePointerObservable.notifyObservers(pi, type);
  15530. if (pi.skipOnPointerObservable) {
  15531. return;
  15532. }
  15533. }
  15534. }
  15535. }
  15536. else {
  15537. var type = PointerEventTypes.POINTERUP;
  15538. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15539. this.onPrePointerObservable.notifyObservers(pi, type);
  15540. if (pi.skipOnPointerObservable) {
  15541. return;
  15542. }
  15543. }
  15544. }
  15545. if (!this.cameraToUseForPointers && !this.activeCamera) {
  15546. return;
  15547. }
  15548. if (!this.pointerUpPredicate) {
  15549. this.pointerUpPredicate = function (mesh) {
  15550. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  15551. };
  15552. }
  15553. // Meshes
  15554. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  15555. this._initActionManager(null, clickInfo);
  15556. }
  15557. if (!pickResult) {
  15558. pickResult = this._currentPickResult;
  15559. }
  15560. if (pickResult && pickResult && pickResult.pickedMesh) {
  15561. this._pickedUpMesh = pickResult.pickedMesh;
  15562. if (this._pickedDownMesh === this._pickedUpMesh) {
  15563. if (this.onPointerPick) {
  15564. this.onPointerPick(evt, pickResult);
  15565. }
  15566. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  15567. var type = PointerEventTypes.POINTERPICK;
  15568. var pi = new PointerInfo(type, evt, pickResult);
  15569. this.onPointerObservable.notifyObservers(pi, type);
  15570. }
  15571. }
  15572. if (pickResult.pickedMesh.actionManager) {
  15573. if (clickInfo.ignore) {
  15574. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15575. }
  15576. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  15577. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15578. }
  15579. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15580. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15581. }
  15582. }
  15583. }
  15584. if (this._pickedDownMesh &&
  15585. this._pickedDownMesh.actionManager &&
  15586. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  15587. this._pickedDownMesh !== this._pickedUpMesh) {
  15588. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  15589. }
  15590. if (this.onPointerUp) {
  15591. this.onPointerUp(evt, pickResult);
  15592. }
  15593. if (this.onPointerObservable.hasObservers()) {
  15594. if (!clickInfo.ignore) {
  15595. if (!clickInfo.hasSwiped) {
  15596. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  15597. var type = PointerEventTypes.POINTERTAP;
  15598. var pi = new PointerInfo(type, evt, pickResult);
  15599. this.onPointerObservable.notifyObservers(pi, type);
  15600. }
  15601. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  15602. var type = PointerEventTypes.POINTERDOUBLETAP;
  15603. var pi = new PointerInfo(type, evt, pickResult);
  15604. this.onPointerObservable.notifyObservers(pi, type);
  15605. }
  15606. }
  15607. }
  15608. else {
  15609. var type = PointerEventTypes.POINTERUP;
  15610. var pi = new PointerInfo(type, evt, pickResult);
  15611. this.onPointerObservable.notifyObservers(pi, type);
  15612. }
  15613. }
  15614. // Sprites
  15615. if (this.spriteManagers.length > 0) {
  15616. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  15617. if (pickResult.hit && pickResult.pickedSprite) {
  15618. if (pickResult.pickedSprite.actionManager) {
  15619. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  15620. if (pickResult.pickedSprite.actionManager) {
  15621. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  15622. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  15623. }
  15624. }
  15625. }
  15626. }
  15627. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  15628. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  15629. }
  15630. }
  15631. this._previousPickResult = this._currentPickResult;
  15632. }).bind(_this));
  15633. };
  15634. this._onKeyDown = function (evt) {
  15635. if (_this.actionManager) {
  15636. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15637. }
  15638. };
  15639. this._onKeyUp = function (evt) {
  15640. if (_this.actionManager) {
  15641. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15642. }
  15643. };
  15644. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15645. var canvas = this._engine.getRenderingCanvas();
  15646. if (attachMove) {
  15647. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  15648. // Wheel
  15649. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  15650. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  15651. }
  15652. if (attachDown) {
  15653. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  15654. }
  15655. if (attachUp) {
  15656. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  15657. }
  15658. canvas.tabIndex = 1;
  15659. canvas.addEventListener("keydown", this._onKeyDown, false);
  15660. canvas.addEventListener("keyup", this._onKeyUp, false);
  15661. };
  15662. Scene.prototype.detachControl = function () {
  15663. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15664. var canvas = this._engine.getRenderingCanvas();
  15665. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  15666. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  15667. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  15668. // Wheel
  15669. canvas.removeEventListener('mousewheel', this._onPointerMove);
  15670. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  15671. canvas.removeEventListener("keydown", this._onKeyDown);
  15672. canvas.removeEventListener("keyup", this._onKeyUp);
  15673. };
  15674. // Ready
  15675. Scene.prototype.isReady = function () {
  15676. if (this._pendingData.length > 0) {
  15677. return false;
  15678. }
  15679. var index;
  15680. // Geometries
  15681. for (index = 0; index < this._geometries.length; index++) {
  15682. var geometry = this._geometries[index];
  15683. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15684. return false;
  15685. }
  15686. }
  15687. // Meshes
  15688. for (index = 0; index < this.meshes.length; index++) {
  15689. var mesh = this.meshes[index];
  15690. if (!mesh.isEnabled()) {
  15691. continue;
  15692. }
  15693. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  15694. continue;
  15695. }
  15696. if (!mesh.isReady()) {
  15697. return false;
  15698. }
  15699. var mat = mesh.material;
  15700. if (mat) {
  15701. if (!mat.isReady(mesh)) {
  15702. return false;
  15703. }
  15704. }
  15705. }
  15706. return true;
  15707. };
  15708. Scene.prototype.resetCachedMaterial = function () {
  15709. this._cachedMaterial = null;
  15710. this._cachedEffect = null;
  15711. this._cachedVisibility = null;
  15712. };
  15713. Scene.prototype.registerBeforeRender = function (func) {
  15714. this.onBeforeRenderObservable.add(func);
  15715. };
  15716. Scene.prototype.unregisterBeforeRender = function (func) {
  15717. this.onBeforeRenderObservable.removeCallback(func);
  15718. };
  15719. Scene.prototype.registerAfterRender = function (func) {
  15720. this.onAfterRenderObservable.add(func);
  15721. };
  15722. Scene.prototype.unregisterAfterRender = function (func) {
  15723. this.onAfterRenderObservable.removeCallback(func);
  15724. };
  15725. Scene.prototype._addPendingData = function (data) {
  15726. this._pendingData.push(data);
  15727. };
  15728. Scene.prototype._removePendingData = function (data) {
  15729. var index = this._pendingData.indexOf(data);
  15730. if (index !== -1) {
  15731. this._pendingData.splice(index, 1);
  15732. }
  15733. };
  15734. Scene.prototype.getWaitingItemsCount = function () {
  15735. return this._pendingData.length;
  15736. };
  15737. /**
  15738. * Registers a function to be executed when the scene is ready.
  15739. * @param {Function} func - the function to be executed.
  15740. */
  15741. Scene.prototype.executeWhenReady = function (func) {
  15742. var _this = this;
  15743. this.onReadyObservable.add(func);
  15744. if (this._executeWhenReadyTimeoutId !== -1) {
  15745. return;
  15746. }
  15747. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15748. _this._checkIsReady();
  15749. }, 150);
  15750. };
  15751. Scene.prototype._checkIsReady = function () {
  15752. var _this = this;
  15753. if (this.isReady()) {
  15754. this.onReadyObservable.notifyObservers(this);
  15755. this.onReadyObservable.clear();
  15756. this._executeWhenReadyTimeoutId = -1;
  15757. return;
  15758. }
  15759. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15760. _this._checkIsReady();
  15761. }, 150);
  15762. };
  15763. // Animations
  15764. /**
  15765. * Will start the animation sequence of a given target
  15766. * @param target - the target
  15767. * @param {number} from - from which frame should animation start
  15768. * @param {number} to - till which frame should animation run.
  15769. * @param {boolean} [loop] - should the animation loop
  15770. * @param {number} [speedRatio] - the speed in which to run the animation
  15771. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15772. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15773. * @return {BABYLON.Animatable} the animatable object created for this animation
  15774. * @see BABYLON.Animatable
  15775. * @see http://doc.babylonjs.com/page.php?p=22081
  15776. */
  15777. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15778. if (speedRatio === void 0) { speedRatio = 1.0; }
  15779. this.stopAnimation(target);
  15780. if (!animatable) {
  15781. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15782. }
  15783. // Local animations
  15784. if (target.animations) {
  15785. animatable.appendAnimations(target, target.animations);
  15786. }
  15787. // Children animations
  15788. if (target.getAnimatables) {
  15789. var animatables = target.getAnimatables();
  15790. for (var index = 0; index < animatables.length; index++) {
  15791. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15792. }
  15793. }
  15794. animatable.reset();
  15795. return animatable;
  15796. };
  15797. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15798. if (speedRatio === undefined) {
  15799. speedRatio = 1.0;
  15800. }
  15801. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15802. return animatable;
  15803. };
  15804. Scene.prototype.getAnimatableByTarget = function (target) {
  15805. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15806. if (this._activeAnimatables[index].target === target) {
  15807. return this._activeAnimatables[index];
  15808. }
  15809. }
  15810. return null;
  15811. };
  15812. Object.defineProperty(Scene.prototype, "Animatables", {
  15813. get: function () {
  15814. return this._activeAnimatables;
  15815. },
  15816. enumerable: true,
  15817. configurable: true
  15818. });
  15819. /**
  15820. * Will stop the animation of the given target
  15821. * @param target - the target
  15822. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  15823. * @see beginAnimation
  15824. */
  15825. Scene.prototype.stopAnimation = function (target, animationName) {
  15826. var animatable = this.getAnimatableByTarget(target);
  15827. if (animatable) {
  15828. animatable.stop(animationName);
  15829. }
  15830. };
  15831. Scene.prototype._animate = function () {
  15832. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  15833. return;
  15834. }
  15835. // Getting time
  15836. var now = BABYLON.Tools.Now;
  15837. if (!this._animationTimeLast) {
  15838. if (this._pendingData.length > 0) {
  15839. return;
  15840. }
  15841. this._animationTimeLast = now;
  15842. }
  15843. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  15844. this._animationTime += deltaTime;
  15845. this._animationTimeLast = now;
  15846. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15847. this._activeAnimatables[index]._animate(this._animationTime);
  15848. }
  15849. };
  15850. // Matrix
  15851. Scene.prototype.getViewMatrix = function () {
  15852. return this._viewMatrix;
  15853. };
  15854. Scene.prototype.getProjectionMatrix = function () {
  15855. return this._projectionMatrix;
  15856. };
  15857. Scene.prototype.getTransformMatrix = function () {
  15858. return this._transformMatrix;
  15859. };
  15860. Scene.prototype.setTransformMatrix = function (view, projection) {
  15861. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  15862. return;
  15863. }
  15864. this._viewUpdateFlag = view.updateFlag;
  15865. this._projectionUpdateFlag = projection.updateFlag;
  15866. this._viewMatrix = view;
  15867. this._projectionMatrix = projection;
  15868. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15869. // Update frustum
  15870. if (!this._frustumPlanes) {
  15871. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15872. }
  15873. else {
  15874. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15875. }
  15876. if (this._sceneUbo.useUbo) {
  15877. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  15878. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  15879. this._sceneUbo.update();
  15880. }
  15881. };
  15882. Scene.prototype.getSceneUniformBuffer = function () {
  15883. return this._sceneUbo;
  15884. };
  15885. // Methods
  15886. Scene.prototype.getUniqueId = function () {
  15887. var result = this._uniqueIdCounter;
  15888. this._uniqueIdCounter++;
  15889. return result;
  15890. };
  15891. Scene.prototype.addMesh = function (newMesh) {
  15892. newMesh.uniqueId = this.getUniqueId();
  15893. var position = this.meshes.push(newMesh);
  15894. //notify the collision coordinator
  15895. if (this.collisionCoordinator) {
  15896. this.collisionCoordinator.onMeshAdded(newMesh);
  15897. }
  15898. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  15899. };
  15900. Scene.prototype.removeMesh = function (toRemove) {
  15901. var index = this.meshes.indexOf(toRemove);
  15902. if (index !== -1) {
  15903. // Remove from the scene if mesh found
  15904. this.meshes.splice(index, 1);
  15905. }
  15906. //notify the collision coordinator
  15907. if (this.collisionCoordinator) {
  15908. this.collisionCoordinator.onMeshRemoved(toRemove);
  15909. }
  15910. this.onMeshRemovedObservable.notifyObservers(toRemove);
  15911. return index;
  15912. };
  15913. Scene.prototype.removeSkeleton = function (toRemove) {
  15914. var index = this.skeletons.indexOf(toRemove);
  15915. if (index !== -1) {
  15916. // Remove from the scene if found
  15917. this.skeletons.splice(index, 1);
  15918. }
  15919. return index;
  15920. };
  15921. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  15922. var index = this.morphTargetManagers.indexOf(toRemove);
  15923. if (index !== -1) {
  15924. // Remove from the scene if found
  15925. this.morphTargetManagers.splice(index, 1);
  15926. }
  15927. return index;
  15928. };
  15929. Scene.prototype.removeLight = function (toRemove) {
  15930. var index = this.lights.indexOf(toRemove);
  15931. if (index !== -1) {
  15932. // Remove from the scene if mesh found
  15933. this.lights.splice(index, 1);
  15934. }
  15935. this.onLightRemovedObservable.notifyObservers(toRemove);
  15936. return index;
  15937. };
  15938. Scene.prototype.removeCamera = function (toRemove) {
  15939. var index = this.cameras.indexOf(toRemove);
  15940. if (index !== -1) {
  15941. // Remove from the scene if mesh found
  15942. this.cameras.splice(index, 1);
  15943. }
  15944. // Remove from activeCameras
  15945. var index2 = this.activeCameras.indexOf(toRemove);
  15946. if (index2 !== -1) {
  15947. // Remove from the scene if mesh found
  15948. this.activeCameras.splice(index2, 1);
  15949. }
  15950. // Reset the activeCamera
  15951. if (this.activeCamera === toRemove) {
  15952. if (this.cameras.length > 0) {
  15953. this.activeCamera = this.cameras[0];
  15954. }
  15955. else {
  15956. this.activeCamera = null;
  15957. }
  15958. }
  15959. this.onCameraRemovedObservable.notifyObservers(toRemove);
  15960. return index;
  15961. };
  15962. Scene.prototype.addLight = function (newLight) {
  15963. newLight.uniqueId = this.getUniqueId();
  15964. var position = this.lights.push(newLight);
  15965. this.onNewLightAddedObservable.notifyObservers(newLight);
  15966. };
  15967. Scene.prototype.addCamera = function (newCamera) {
  15968. newCamera.uniqueId = this.getUniqueId();
  15969. var position = this.cameras.push(newCamera);
  15970. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  15971. };
  15972. /**
  15973. * Switch active camera
  15974. * @param {Camera} newCamera - new active camera
  15975. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  15976. */
  15977. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  15978. if (attachControl === void 0) { attachControl = true; }
  15979. var canvas = this._engine.getRenderingCanvas();
  15980. this.activeCamera.detachControl(canvas);
  15981. this.activeCamera = newCamera;
  15982. if (attachControl) {
  15983. newCamera.attachControl(canvas);
  15984. }
  15985. };
  15986. /**
  15987. * sets the active camera of the scene using its ID
  15988. * @param {string} id - the camera's ID
  15989. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15990. * @see activeCamera
  15991. */
  15992. Scene.prototype.setActiveCameraByID = function (id) {
  15993. var camera = this.getCameraByID(id);
  15994. if (camera) {
  15995. this.activeCamera = camera;
  15996. return camera;
  15997. }
  15998. return null;
  15999. };
  16000. /**
  16001. * sets the active camera of the scene using its name
  16002. * @param {string} name - the camera's name
  16003. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16004. * @see activeCamera
  16005. */
  16006. Scene.prototype.setActiveCameraByName = function (name) {
  16007. var camera = this.getCameraByName(name);
  16008. if (camera) {
  16009. this.activeCamera = camera;
  16010. return camera;
  16011. }
  16012. return null;
  16013. };
  16014. /**
  16015. * get a material using its id
  16016. * @param {string} the material's ID
  16017. * @return {BABYLON.Material|null} the material or null if none found.
  16018. */
  16019. Scene.prototype.getMaterialByID = function (id) {
  16020. for (var index = 0; index < this.materials.length; index++) {
  16021. if (this.materials[index].id === id) {
  16022. return this.materials[index];
  16023. }
  16024. }
  16025. return null;
  16026. };
  16027. /**
  16028. * get a material using its name
  16029. * @param {string} the material's name
  16030. * @return {BABYLON.Material|null} the material or null if none found.
  16031. */
  16032. Scene.prototype.getMaterialByName = function (name) {
  16033. for (var index = 0; index < this.materials.length; index++) {
  16034. if (this.materials[index].name === name) {
  16035. return this.materials[index];
  16036. }
  16037. }
  16038. return null;
  16039. };
  16040. Scene.prototype.getLensFlareSystemByName = function (name) {
  16041. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16042. if (this.lensFlareSystems[index].name === name) {
  16043. return this.lensFlareSystems[index];
  16044. }
  16045. }
  16046. return null;
  16047. };
  16048. Scene.prototype.getLensFlareSystemByID = function (id) {
  16049. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16050. if (this.lensFlareSystems[index].id === id) {
  16051. return this.lensFlareSystems[index];
  16052. }
  16053. }
  16054. return null;
  16055. };
  16056. Scene.prototype.getCameraByID = function (id) {
  16057. for (var index = 0; index < this.cameras.length; index++) {
  16058. if (this.cameras[index].id === id) {
  16059. return this.cameras[index];
  16060. }
  16061. }
  16062. return null;
  16063. };
  16064. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16065. for (var index = 0; index < this.cameras.length; index++) {
  16066. if (this.cameras[index].uniqueId === uniqueId) {
  16067. return this.cameras[index];
  16068. }
  16069. }
  16070. return null;
  16071. };
  16072. /**
  16073. * get a camera using its name
  16074. * @param {string} the camera's name
  16075. * @return {BABYLON.Camera|null} the camera or null if none found.
  16076. */
  16077. Scene.prototype.getCameraByName = function (name) {
  16078. for (var index = 0; index < this.cameras.length; index++) {
  16079. if (this.cameras[index].name === name) {
  16080. return this.cameras[index];
  16081. }
  16082. }
  16083. return null;
  16084. };
  16085. /**
  16086. * get a bone using its id
  16087. * @param {string} the bone's id
  16088. * @return {BABYLON.Bone|null} the bone or null if not found
  16089. */
  16090. Scene.prototype.getBoneByID = function (id) {
  16091. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16092. var skeleton = this.skeletons[skeletonIndex];
  16093. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16094. if (skeleton.bones[boneIndex].id === id) {
  16095. return skeleton.bones[boneIndex];
  16096. }
  16097. }
  16098. }
  16099. return null;
  16100. };
  16101. /**
  16102. * get a bone using its id
  16103. * @param {string} the bone's name
  16104. * @return {BABYLON.Bone|null} the bone or null if not found
  16105. */
  16106. Scene.prototype.getBoneByName = function (name) {
  16107. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16108. var skeleton = this.skeletons[skeletonIndex];
  16109. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16110. if (skeleton.bones[boneIndex].name === name) {
  16111. return skeleton.bones[boneIndex];
  16112. }
  16113. }
  16114. }
  16115. return null;
  16116. };
  16117. /**
  16118. * get a light node using its name
  16119. * @param {string} the light's name
  16120. * @return {BABYLON.Light|null} the light or null if none found.
  16121. */
  16122. Scene.prototype.getLightByName = function (name) {
  16123. for (var index = 0; index < this.lights.length; index++) {
  16124. if (this.lights[index].name === name) {
  16125. return this.lights[index];
  16126. }
  16127. }
  16128. return null;
  16129. };
  16130. /**
  16131. * get a light node using its ID
  16132. * @param {string} the light's id
  16133. * @return {BABYLON.Light|null} the light or null if none found.
  16134. */
  16135. Scene.prototype.getLightByID = function (id) {
  16136. for (var index = 0; index < this.lights.length; index++) {
  16137. if (this.lights[index].id === id) {
  16138. return this.lights[index];
  16139. }
  16140. }
  16141. return null;
  16142. };
  16143. /**
  16144. * get a light node using its scene-generated unique ID
  16145. * @param {number} the light's unique id
  16146. * @return {BABYLON.Light|null} the light or null if none found.
  16147. */
  16148. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16149. for (var index = 0; index < this.lights.length; index++) {
  16150. if (this.lights[index].uniqueId === uniqueId) {
  16151. return this.lights[index];
  16152. }
  16153. }
  16154. return null;
  16155. };
  16156. /**
  16157. * get a particle system by id
  16158. * @param id {number} the particle system id
  16159. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16160. */
  16161. Scene.prototype.getParticleSystemByID = function (id) {
  16162. for (var index = 0; index < this.particleSystems.length; index++) {
  16163. if (this.particleSystems[index].id === id) {
  16164. return this.particleSystems[index];
  16165. }
  16166. }
  16167. return null;
  16168. };
  16169. /**
  16170. * get a geometry using its ID
  16171. * @param {string} the geometry's id
  16172. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16173. */
  16174. Scene.prototype.getGeometryByID = function (id) {
  16175. for (var index = 0; index < this._geometries.length; index++) {
  16176. if (this._geometries[index].id === id) {
  16177. return this._geometries[index];
  16178. }
  16179. }
  16180. return null;
  16181. };
  16182. /**
  16183. * add a new geometry to this scene.
  16184. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16185. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16186. * @return {boolean} was the geometry added or not
  16187. */
  16188. Scene.prototype.pushGeometry = function (geometry, force) {
  16189. if (!force && this.getGeometryByID(geometry.id)) {
  16190. return false;
  16191. }
  16192. this._geometries.push(geometry);
  16193. //notify the collision coordinator
  16194. if (this.collisionCoordinator) {
  16195. this.collisionCoordinator.onGeometryAdded(geometry);
  16196. }
  16197. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16198. return true;
  16199. };
  16200. /**
  16201. * Removes an existing geometry
  16202. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16203. * @return {boolean} was the geometry removed or not
  16204. */
  16205. Scene.prototype.removeGeometry = function (geometry) {
  16206. var index = this._geometries.indexOf(geometry);
  16207. if (index > -1) {
  16208. this._geometries.splice(index, 1);
  16209. //notify the collision coordinator
  16210. if (this.collisionCoordinator) {
  16211. this.collisionCoordinator.onGeometryDeleted(geometry);
  16212. }
  16213. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16214. return true;
  16215. }
  16216. return false;
  16217. };
  16218. Scene.prototype.getGeometries = function () {
  16219. return this._geometries;
  16220. };
  16221. /**
  16222. * Get the first added mesh found of a given ID
  16223. * @param {string} id - the id to search for
  16224. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16225. */
  16226. Scene.prototype.getMeshByID = function (id) {
  16227. for (var index = 0; index < this.meshes.length; index++) {
  16228. if (this.meshes[index].id === id) {
  16229. return this.meshes[index];
  16230. }
  16231. }
  16232. return null;
  16233. };
  16234. Scene.prototype.getMeshesByID = function (id) {
  16235. return this.meshes.filter(function (m) {
  16236. return m.id === id;
  16237. });
  16238. };
  16239. /**
  16240. * Get a mesh with its auto-generated unique id
  16241. * @param {number} uniqueId - the unique id to search for
  16242. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16243. */
  16244. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16245. for (var index = 0; index < this.meshes.length; index++) {
  16246. if (this.meshes[index].uniqueId === uniqueId) {
  16247. return this.meshes[index];
  16248. }
  16249. }
  16250. return null;
  16251. };
  16252. /**
  16253. * Get a the last added mesh found of a given ID
  16254. * @param {string} id - the id to search for
  16255. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16256. */
  16257. Scene.prototype.getLastMeshByID = function (id) {
  16258. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16259. if (this.meshes[index].id === id) {
  16260. return this.meshes[index];
  16261. }
  16262. }
  16263. return null;
  16264. };
  16265. /**
  16266. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16267. * @param {string} id - the id to search for
  16268. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16269. */
  16270. Scene.prototype.getLastEntryByID = function (id) {
  16271. var index;
  16272. for (index = this.meshes.length - 1; index >= 0; index--) {
  16273. if (this.meshes[index].id === id) {
  16274. return this.meshes[index];
  16275. }
  16276. }
  16277. for (index = this.cameras.length - 1; index >= 0; index--) {
  16278. if (this.cameras[index].id === id) {
  16279. return this.cameras[index];
  16280. }
  16281. }
  16282. for (index = this.lights.length - 1; index >= 0; index--) {
  16283. if (this.lights[index].id === id) {
  16284. return this.lights[index];
  16285. }
  16286. }
  16287. return null;
  16288. };
  16289. Scene.prototype.getNodeByID = function (id) {
  16290. var mesh = this.getMeshByID(id);
  16291. if (mesh) {
  16292. return mesh;
  16293. }
  16294. var light = this.getLightByID(id);
  16295. if (light) {
  16296. return light;
  16297. }
  16298. var camera = this.getCameraByID(id);
  16299. if (camera) {
  16300. return camera;
  16301. }
  16302. var bone = this.getBoneByID(id);
  16303. return bone;
  16304. };
  16305. Scene.prototype.getNodeByName = function (name) {
  16306. var mesh = this.getMeshByName(name);
  16307. if (mesh) {
  16308. return mesh;
  16309. }
  16310. var light = this.getLightByName(name);
  16311. if (light) {
  16312. return light;
  16313. }
  16314. var camera = this.getCameraByName(name);
  16315. if (camera) {
  16316. return camera;
  16317. }
  16318. var bone = this.getBoneByName(name);
  16319. return bone;
  16320. };
  16321. Scene.prototype.getMeshByName = function (name) {
  16322. for (var index = 0; index < this.meshes.length; index++) {
  16323. if (this.meshes[index].name === name) {
  16324. return this.meshes[index];
  16325. }
  16326. }
  16327. return null;
  16328. };
  16329. Scene.prototype.getSoundByName = function (name) {
  16330. var index;
  16331. if (BABYLON.AudioEngine) {
  16332. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  16333. if (this.mainSoundTrack.soundCollection[index].name === name) {
  16334. return this.mainSoundTrack.soundCollection[index];
  16335. }
  16336. }
  16337. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  16338. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  16339. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  16340. return this.soundTracks[sdIndex].soundCollection[index];
  16341. }
  16342. }
  16343. }
  16344. }
  16345. return null;
  16346. };
  16347. Scene.prototype.getLastSkeletonByID = function (id) {
  16348. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  16349. if (this.skeletons[index].id === id) {
  16350. return this.skeletons[index];
  16351. }
  16352. }
  16353. return null;
  16354. };
  16355. Scene.prototype.getSkeletonById = function (id) {
  16356. for (var index = 0; index < this.skeletons.length; index++) {
  16357. if (this.skeletons[index].id === id) {
  16358. return this.skeletons[index];
  16359. }
  16360. }
  16361. return null;
  16362. };
  16363. Scene.prototype.getSkeletonByName = function (name) {
  16364. for (var index = 0; index < this.skeletons.length; index++) {
  16365. if (this.skeletons[index].name === name) {
  16366. return this.skeletons[index];
  16367. }
  16368. }
  16369. return null;
  16370. };
  16371. Scene.prototype.getMorphTargetManagerById = function (id) {
  16372. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  16373. if (this.morphTargetManagers[index].uniqueId === id) {
  16374. return this.morphTargetManagers[index];
  16375. }
  16376. }
  16377. return null;
  16378. };
  16379. Scene.prototype.isActiveMesh = function (mesh) {
  16380. return (this._activeMeshes.indexOf(mesh) !== -1);
  16381. };
  16382. /**
  16383. * Return a the first highlight layer of the scene with a given name.
  16384. * @param name The name of the highlight layer to look for.
  16385. * @return The highlight layer if found otherwise null.
  16386. */
  16387. Scene.prototype.getHighlightLayerByName = function (name) {
  16388. for (var index = 0; index < this.highlightLayers.length; index++) {
  16389. if (this.highlightLayers[index].name === name) {
  16390. return this.highlightLayers[index];
  16391. }
  16392. }
  16393. return null;
  16394. };
  16395. Object.defineProperty(Scene.prototype, "uid", {
  16396. /**
  16397. * Return a unique id as a string which can serve as an identifier for the scene
  16398. */
  16399. get: function () {
  16400. if (!this._uid) {
  16401. this._uid = BABYLON.Tools.RandomId();
  16402. }
  16403. return this._uid;
  16404. },
  16405. enumerable: true,
  16406. configurable: true
  16407. });
  16408. /**
  16409. * Add an externaly attached data from its key.
  16410. * This method call will fail and return false, if such key already exists.
  16411. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16412. * @param key the unique key that identifies the data
  16413. * @param data the data object to associate to the key for this Engine instance
  16414. * @return true if no such key were already present and the data was added successfully, false otherwise
  16415. */
  16416. Scene.prototype.addExternalData = function (key, data) {
  16417. if (!this._externalData) {
  16418. this._externalData = new BABYLON.StringDictionary();
  16419. }
  16420. return this._externalData.add(key, data);
  16421. };
  16422. /**
  16423. * Get an externaly attached data from its key
  16424. * @param key the unique key that identifies the data
  16425. * @return the associated data, if present (can be null), or undefined if not present
  16426. */
  16427. Scene.prototype.getExternalData = function (key) {
  16428. if (!this._externalData) {
  16429. return null;
  16430. }
  16431. return this._externalData.get(key);
  16432. };
  16433. /**
  16434. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16435. * @param key the unique key that identifies the data
  16436. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16437. * @return the associated data, can be null if the factory returned null.
  16438. */
  16439. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16440. if (!this._externalData) {
  16441. this._externalData = new BABYLON.StringDictionary();
  16442. }
  16443. return this._externalData.getOrAddWithFactory(key, factory);
  16444. };
  16445. /**
  16446. * Remove an externaly attached data from the Engine instance
  16447. * @param key the unique key that identifies the data
  16448. * @return true if the data was successfully removed, false if it doesn't exist
  16449. */
  16450. Scene.prototype.removeExternalData = function (key) {
  16451. return this._externalData.remove(key);
  16452. };
  16453. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  16454. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  16455. var material = subMesh.getMaterial();
  16456. if (mesh.showSubMeshesBoundingBox) {
  16457. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  16458. }
  16459. if (material) {
  16460. // Render targets
  16461. if (material.getRenderTargetTextures) {
  16462. if (this._processedMaterials.indexOf(material) === -1) {
  16463. this._processedMaterials.push(material);
  16464. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  16465. }
  16466. }
  16467. // Dispatch
  16468. this._activeIndices.addCount(subMesh.indexCount, false);
  16469. this._renderingManager.dispatch(subMesh);
  16470. }
  16471. }
  16472. };
  16473. Scene.prototype._isInIntermediateRendering = function () {
  16474. return this._intermediateRendering;
  16475. };
  16476. Scene.prototype._evaluateActiveMeshes = function () {
  16477. this.activeCamera._activeMeshes.reset();
  16478. this._activeMeshes.reset();
  16479. this._renderingManager.reset();
  16480. this._processedMaterials.reset();
  16481. this._activeParticleSystems.reset();
  16482. this._activeSkeletons.reset();
  16483. this._softwareSkinnedMeshes.reset();
  16484. if (this._boundingBoxRenderer) {
  16485. this._boundingBoxRenderer.reset();
  16486. }
  16487. this._edgesRenderers.reset();
  16488. // Meshes
  16489. var meshes;
  16490. var len;
  16491. if (this._selectionOctree) {
  16492. var selection = this._selectionOctree.select(this._frustumPlanes);
  16493. meshes = selection.data;
  16494. len = selection.length;
  16495. }
  16496. else {
  16497. len = this.meshes.length;
  16498. meshes = this.meshes;
  16499. }
  16500. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16501. var mesh = meshes[meshIndex];
  16502. if (mesh.isBlocked) {
  16503. continue;
  16504. }
  16505. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  16506. if (!mesh.isReady() || !mesh.isEnabled()) {
  16507. continue;
  16508. }
  16509. mesh.computeWorldMatrix();
  16510. // Intersections
  16511. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  16512. this._meshesForIntersections.pushNoDuplicate(mesh);
  16513. }
  16514. // Switch to current LOD
  16515. var meshLOD = mesh.getLOD(this.activeCamera);
  16516. if (!meshLOD) {
  16517. continue;
  16518. }
  16519. mesh._preActivate();
  16520. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  16521. this._activeMeshes.push(mesh);
  16522. this.activeCamera._activeMeshes.push(mesh);
  16523. mesh._activate(this._renderId);
  16524. this._activeMesh(mesh, meshLOD);
  16525. }
  16526. }
  16527. // Particle systems
  16528. this._particlesDuration.beginMonitoring();
  16529. var beforeParticlesDate = BABYLON.Tools.Now;
  16530. if (this.particlesEnabled) {
  16531. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  16532. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  16533. var particleSystem = this.particleSystems[particleIndex];
  16534. if (!particleSystem.isStarted()) {
  16535. continue;
  16536. }
  16537. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  16538. this._activeParticleSystems.push(particleSystem);
  16539. particleSystem.animate();
  16540. this._renderingManager.dispatchParticles(particleSystem);
  16541. }
  16542. }
  16543. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  16544. }
  16545. this._particlesDuration.endMonitoring(false);
  16546. };
  16547. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  16548. if (mesh.skeleton && this.skeletonsEnabled) {
  16549. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  16550. mesh.skeleton.prepare();
  16551. }
  16552. if (!mesh.computeBonesUsingShaders) {
  16553. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  16554. }
  16555. }
  16556. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  16557. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  16558. }
  16559. if (sourceMesh._edgesRenderer) {
  16560. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  16561. }
  16562. if (mesh && mesh.subMeshes) {
  16563. // Submeshes Octrees
  16564. var len;
  16565. var subMeshes;
  16566. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  16567. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  16568. len = intersections.length;
  16569. subMeshes = intersections.data;
  16570. }
  16571. else {
  16572. subMeshes = mesh.subMeshes;
  16573. len = subMeshes.length;
  16574. }
  16575. for (var subIndex = 0; subIndex < len; subIndex++) {
  16576. var subMesh = subMeshes[subIndex];
  16577. this._evaluateSubMesh(subMesh, mesh);
  16578. }
  16579. }
  16580. };
  16581. Scene.prototype.updateTransformMatrix = function (force) {
  16582. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  16583. };
  16584. Scene.prototype._renderForCamera = function (camera) {
  16585. var engine = this._engine;
  16586. var startTime = BABYLON.Tools.Now;
  16587. this.activeCamera = camera;
  16588. if (!this.activeCamera)
  16589. throw new Error("Active camera not set");
  16590. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16591. // Viewport
  16592. engine.setViewport(this.activeCamera.viewport);
  16593. // Camera
  16594. this.resetCachedMaterial();
  16595. this._renderId++;
  16596. this.updateTransformMatrix();
  16597. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  16598. // Meshes
  16599. this._evaluateActiveMeshesDuration.beginMonitoring();
  16600. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  16601. this._evaluateActiveMeshes();
  16602. this._evaluateActiveMeshesDuration.endMonitoring(false);
  16603. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  16604. // Software skinning
  16605. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  16606. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  16607. mesh.applySkeleton(mesh.skeleton);
  16608. }
  16609. // Render targets
  16610. this._renderTargetsDuration.beginMonitoring();
  16611. var needsRestoreFrameBuffer = false;
  16612. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16613. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  16614. this._intermediateRendering = true;
  16615. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16616. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  16617. var renderTarget = this._renderTargets.data[renderIndex];
  16618. if (renderTarget._shouldRender()) {
  16619. this._renderId++;
  16620. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  16621. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  16622. }
  16623. }
  16624. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16625. this._intermediateRendering = false;
  16626. this._renderId++;
  16627. needsRestoreFrameBuffer = true; // Restore back buffer
  16628. }
  16629. // Render HighlightLayer Texture
  16630. var stencilState = this._engine.getStencilBuffer();
  16631. var renderhighlights = false;
  16632. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  16633. this._intermediateRendering = true;
  16634. for (var i = 0; i < this.highlightLayers.length; i++) {
  16635. var highlightLayer = this.highlightLayers[i];
  16636. if (highlightLayer.shouldRender() &&
  16637. (!highlightLayer.camera ||
  16638. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  16639. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  16640. renderhighlights = true;
  16641. var renderTarget = highlightLayer._mainTexture;
  16642. if (renderTarget._shouldRender()) {
  16643. this._renderId++;
  16644. renderTarget.render(false, false);
  16645. needsRestoreFrameBuffer = true;
  16646. }
  16647. }
  16648. }
  16649. this._intermediateRendering = false;
  16650. this._renderId++;
  16651. }
  16652. if (needsRestoreFrameBuffer) {
  16653. engine.restoreDefaultFramebuffer();
  16654. }
  16655. this._renderTargetsDuration.endMonitoring(false);
  16656. // Prepare Frame
  16657. this.postProcessManager._prepareFrame();
  16658. this._renderDuration.beginMonitoring();
  16659. // Backgrounds
  16660. var layerIndex;
  16661. var layer;
  16662. if (this.layers.length) {
  16663. engine.setDepthBuffer(false);
  16664. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16665. layer = this.layers[layerIndex];
  16666. if (layer.isBackground) {
  16667. layer.render();
  16668. }
  16669. }
  16670. engine.setDepthBuffer(true);
  16671. }
  16672. // Render
  16673. BABYLON.Tools.StartPerformanceCounter("Main render");
  16674. // Activate HighlightLayer stencil
  16675. if (renderhighlights) {
  16676. this._engine.setStencilBuffer(true);
  16677. }
  16678. this._renderingManager.render(null, null, true, true);
  16679. // Restore HighlightLayer stencil
  16680. if (renderhighlights) {
  16681. this._engine.setStencilBuffer(stencilState);
  16682. }
  16683. BABYLON.Tools.EndPerformanceCounter("Main render");
  16684. // Bounding boxes
  16685. if (this._boundingBoxRenderer) {
  16686. this._boundingBoxRenderer.render();
  16687. }
  16688. // Edges
  16689. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16690. this._edgesRenderers.data[edgesRendererIndex].render();
  16691. }
  16692. // Lens flares
  16693. if (this.lensFlaresEnabled) {
  16694. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16695. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  16696. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  16697. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  16698. lensFlareSystem.render();
  16699. }
  16700. }
  16701. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16702. }
  16703. // Foregrounds
  16704. if (this.layers.length) {
  16705. engine.setDepthBuffer(false);
  16706. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16707. layer = this.layers[layerIndex];
  16708. if (!layer.isBackground) {
  16709. layer.render();
  16710. }
  16711. }
  16712. engine.setDepthBuffer(true);
  16713. }
  16714. // Highlight Layer
  16715. if (renderhighlights) {
  16716. engine.setDepthBuffer(false);
  16717. for (var i = 0; i < this.highlightLayers.length; i++) {
  16718. if (this.highlightLayers[i].shouldRender()) {
  16719. this.highlightLayers[i].render();
  16720. }
  16721. }
  16722. engine.setDepthBuffer(true);
  16723. }
  16724. this._renderDuration.endMonitoring(false);
  16725. // Finalize frame
  16726. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  16727. // Update camera
  16728. this.activeCamera._updateFromScene();
  16729. // Reset some special arrays
  16730. this._renderTargets.reset();
  16731. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  16732. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16733. };
  16734. Scene.prototype._processSubCameras = function (camera) {
  16735. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  16736. this._renderForCamera(camera);
  16737. return;
  16738. }
  16739. // rig cameras
  16740. for (var index = 0; index < camera._rigCameras.length; index++) {
  16741. this._renderForCamera(camera._rigCameras[index]);
  16742. }
  16743. this.activeCamera = camera;
  16744. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  16745. // Update camera
  16746. this.activeCamera._updateFromScene();
  16747. };
  16748. Scene.prototype._checkIntersections = function () {
  16749. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  16750. var sourceMesh = this._meshesForIntersections.data[index];
  16751. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  16752. var action = sourceMesh.actionManager.actions[actionIndex];
  16753. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16754. var parameters = action.getTriggerParameter();
  16755. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  16756. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  16757. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  16758. if (areIntersecting && currentIntersectionInProgress === -1) {
  16759. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  16760. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16761. sourceMesh._intersectionsInProgress.push(otherMesh);
  16762. }
  16763. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16764. sourceMesh._intersectionsInProgress.push(otherMesh);
  16765. }
  16766. }
  16767. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  16768. //They intersected, and now they don't.
  16769. //is this trigger an exit trigger? execute an event.
  16770. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16771. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16772. }
  16773. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  16774. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16775. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  16776. }
  16777. }
  16778. }
  16779. }
  16780. }
  16781. };
  16782. Scene.prototype.render = function () {
  16783. if (this.isDisposed) {
  16784. return;
  16785. }
  16786. this._lastFrameDuration.beginMonitoring();
  16787. this._particlesDuration.fetchNewFrame();
  16788. this._spritesDuration.fetchNewFrame();
  16789. this._activeParticles.fetchNewFrame();
  16790. this._renderDuration.fetchNewFrame();
  16791. this._renderTargetsDuration.fetchNewFrame();
  16792. this._evaluateActiveMeshesDuration.fetchNewFrame();
  16793. this._totalVertices.fetchNewFrame();
  16794. this._activeIndices.fetchNewFrame();
  16795. this._activeBones.fetchNewFrame();
  16796. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  16797. this._meshesForIntersections.reset();
  16798. this.resetCachedMaterial();
  16799. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  16800. // Actions
  16801. if (this.actionManager) {
  16802. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  16803. }
  16804. //Simplification Queue
  16805. if (this.simplificationQueue && !this.simplificationQueue.running) {
  16806. this.simplificationQueue.executeNext();
  16807. }
  16808. // Animations
  16809. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  16810. this._animationRatio = deltaTime * (60.0 / 1000.0);
  16811. this._animate();
  16812. // Physics
  16813. if (this._physicsEngine) {
  16814. BABYLON.Tools.StartPerformanceCounter("Physics");
  16815. this._physicsEngine._step(deltaTime / 1000.0);
  16816. BABYLON.Tools.EndPerformanceCounter("Physics");
  16817. }
  16818. // Before render
  16819. this.onBeforeRenderObservable.notifyObservers(this);
  16820. // Customs render targets
  16821. this._renderTargetsDuration.beginMonitoring();
  16822. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16823. var engine = this.getEngine();
  16824. var currentActiveCamera = this.activeCamera;
  16825. if (this.renderTargetsEnabled) {
  16826. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16827. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  16828. var renderTarget = this.customRenderTargets[customIndex];
  16829. if (renderTarget._shouldRender()) {
  16830. this._renderId++;
  16831. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  16832. if (!this.activeCamera)
  16833. throw new Error("Active camera not set");
  16834. // Viewport
  16835. engine.setViewport(this.activeCamera.viewport);
  16836. // Camera
  16837. this.updateTransformMatrix();
  16838. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  16839. }
  16840. }
  16841. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16842. this._renderId++;
  16843. }
  16844. if (this.customRenderTargets.length > 0) {
  16845. engine.restoreDefaultFramebuffer();
  16846. }
  16847. this._renderTargetsDuration.endMonitoring();
  16848. this.activeCamera = currentActiveCamera;
  16849. // Procedural textures
  16850. if (this.proceduralTexturesEnabled) {
  16851. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16852. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  16853. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  16854. if (proceduralTexture._shouldRender()) {
  16855. proceduralTexture.render();
  16856. }
  16857. }
  16858. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16859. }
  16860. // Clear
  16861. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  16862. // Shadows
  16863. if (this.shadowsEnabled) {
  16864. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16865. var light = this.lights[lightIndex];
  16866. var shadowGenerator = light.getShadowGenerator();
  16867. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16868. this._renderTargets.push(shadowGenerator.getShadowMap());
  16869. }
  16870. }
  16871. }
  16872. // Depth renderer
  16873. if (this._depthRenderer) {
  16874. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16875. }
  16876. // RenderPipeline
  16877. if (this._postProcessRenderPipelineManager) {
  16878. this._postProcessRenderPipelineManager.update();
  16879. }
  16880. // Multi-cameras?
  16881. if (this.activeCameras.length > 0) {
  16882. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16883. if (cameraIndex > 0) {
  16884. this._engine.clear(null, false, true, true);
  16885. }
  16886. this._processSubCameras(this.activeCameras[cameraIndex]);
  16887. }
  16888. }
  16889. else {
  16890. if (!this.activeCamera) {
  16891. throw new Error("No camera defined");
  16892. }
  16893. this._processSubCameras(this.activeCamera);
  16894. }
  16895. // Intersection checks
  16896. this._checkIntersections();
  16897. // Update the audio listener attached to the camera
  16898. if (BABYLON.AudioEngine) {
  16899. this._updateAudioParameters();
  16900. }
  16901. // After render
  16902. if (this.afterRender) {
  16903. this.afterRender();
  16904. }
  16905. this.onAfterRenderObservable.notifyObservers(this);
  16906. // Cleaning
  16907. for (var index = 0; index < this._toBeDisposed.length; index++) {
  16908. this._toBeDisposed.data[index].dispose();
  16909. this._toBeDisposed[index] = null;
  16910. }
  16911. this._toBeDisposed.reset();
  16912. if (this.dumpNextRenderTargets) {
  16913. this.dumpNextRenderTargets = false;
  16914. }
  16915. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  16916. this._lastFrameDuration.endMonitoring();
  16917. this._totalMeshesCounter.addCount(this.meshes.length, true);
  16918. this._totalLightsCounter.addCount(this.lights.length, true);
  16919. this._totalMaterialsCounter.addCount(this.materials.length, true);
  16920. this._totalTexturesCounter.addCount(this.textures.length, true);
  16921. this._activeBones.addCount(0, true);
  16922. this._activeIndices.addCount(0, true);
  16923. this._activeParticles.addCount(0, true);
  16924. };
  16925. Scene.prototype._updateAudioParameters = function () {
  16926. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  16927. return;
  16928. }
  16929. var listeningCamera;
  16930. var audioEngine = BABYLON.Engine.audioEngine;
  16931. if (this.activeCameras.length > 0) {
  16932. listeningCamera = this.activeCameras[0];
  16933. }
  16934. else {
  16935. listeningCamera = this.activeCamera;
  16936. }
  16937. if (listeningCamera && audioEngine.canUseWebAudio) {
  16938. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  16939. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  16940. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  16941. cameraDirection.normalize();
  16942. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  16943. var i;
  16944. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16945. var sound = this.mainSoundTrack.soundCollection[i];
  16946. if (sound.useCustomAttenuation) {
  16947. sound.updateDistanceFromListener();
  16948. }
  16949. }
  16950. for (i = 0; i < this.soundTracks.length; i++) {
  16951. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16952. sound = this.soundTracks[i].soundCollection[j];
  16953. if (sound.useCustomAttenuation) {
  16954. sound.updateDistanceFromListener();
  16955. }
  16956. }
  16957. }
  16958. }
  16959. };
  16960. Object.defineProperty(Scene.prototype, "audioEnabled", {
  16961. // Audio
  16962. get: function () {
  16963. return this._audioEnabled;
  16964. },
  16965. set: function (value) {
  16966. this._audioEnabled = value;
  16967. if (BABYLON.AudioEngine) {
  16968. if (this._audioEnabled) {
  16969. this._enableAudio();
  16970. }
  16971. else {
  16972. this._disableAudio();
  16973. }
  16974. }
  16975. },
  16976. enumerable: true,
  16977. configurable: true
  16978. });
  16979. Scene.prototype._disableAudio = function () {
  16980. var i;
  16981. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16982. this.mainSoundTrack.soundCollection[i].pause();
  16983. }
  16984. for (i = 0; i < this.soundTracks.length; i++) {
  16985. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16986. this.soundTracks[i].soundCollection[j].pause();
  16987. }
  16988. }
  16989. };
  16990. Scene.prototype._enableAudio = function () {
  16991. var i;
  16992. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16993. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  16994. this.mainSoundTrack.soundCollection[i].play();
  16995. }
  16996. }
  16997. for (i = 0; i < this.soundTracks.length; i++) {
  16998. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16999. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17000. this.soundTracks[i].soundCollection[j].play();
  17001. }
  17002. }
  17003. }
  17004. };
  17005. Object.defineProperty(Scene.prototype, "headphone", {
  17006. get: function () {
  17007. return this._headphone;
  17008. },
  17009. set: function (value) {
  17010. this._headphone = value;
  17011. if (BABYLON.AudioEngine) {
  17012. if (this._headphone) {
  17013. this._switchAudioModeForHeadphones();
  17014. }
  17015. else {
  17016. this._switchAudioModeForNormalSpeakers();
  17017. }
  17018. }
  17019. },
  17020. enumerable: true,
  17021. configurable: true
  17022. });
  17023. Scene.prototype._switchAudioModeForHeadphones = function () {
  17024. this.mainSoundTrack.switchPanningModelToHRTF();
  17025. for (var i = 0; i < this.soundTracks.length; i++) {
  17026. this.soundTracks[i].switchPanningModelToHRTF();
  17027. }
  17028. };
  17029. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17030. this.mainSoundTrack.switchPanningModelToEqualPower();
  17031. for (var i = 0; i < this.soundTracks.length; i++) {
  17032. this.soundTracks[i].switchPanningModelToEqualPower();
  17033. }
  17034. };
  17035. Scene.prototype.enableDepthRenderer = function () {
  17036. if (this._depthRenderer) {
  17037. return this._depthRenderer;
  17038. }
  17039. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17040. return this._depthRenderer;
  17041. };
  17042. Scene.prototype.disableDepthRenderer = function () {
  17043. if (!this._depthRenderer) {
  17044. return;
  17045. }
  17046. this._depthRenderer.dispose();
  17047. this._depthRenderer = null;
  17048. };
  17049. Scene.prototype.freezeMaterials = function () {
  17050. for (var i = 0; i < this.materials.length; i++) {
  17051. this.materials[i].freeze();
  17052. }
  17053. };
  17054. Scene.prototype.unfreezeMaterials = function () {
  17055. for (var i = 0; i < this.materials.length; i++) {
  17056. this.materials[i].unfreeze();
  17057. }
  17058. };
  17059. Scene.prototype.dispose = function () {
  17060. this.beforeRender = null;
  17061. this.afterRender = null;
  17062. this.skeletons = [];
  17063. this.morphTargetManagers = [];
  17064. this.importedMeshesFiles = new Array();
  17065. if (this._depthRenderer) {
  17066. this._depthRenderer.dispose();
  17067. }
  17068. // Smart arrays
  17069. if (this.activeCamera) {
  17070. this.activeCamera._activeMeshes.dispose();
  17071. this.activeCamera = null;
  17072. }
  17073. this._activeMeshes.dispose();
  17074. this._renderingManager.dispose();
  17075. this._processedMaterials.dispose();
  17076. this._activeParticleSystems.dispose();
  17077. this._activeSkeletons.dispose();
  17078. this._softwareSkinnedMeshes.dispose();
  17079. if (this._boundingBoxRenderer) {
  17080. this._boundingBoxRenderer.dispose();
  17081. }
  17082. this._edgesRenderers.dispose();
  17083. this._meshesForIntersections.dispose();
  17084. this._toBeDisposed.dispose();
  17085. // Debug layer
  17086. if (this._debugLayer) {
  17087. this._debugLayer.hide();
  17088. }
  17089. // Events
  17090. this.onDisposeObservable.notifyObservers(this);
  17091. this.onDisposeObservable.clear();
  17092. this.onBeforeRenderObservable.clear();
  17093. this.onAfterRenderObservable.clear();
  17094. this.detachControl();
  17095. // Release sounds & sounds tracks
  17096. if (BABYLON.AudioEngine) {
  17097. this.disposeSounds();
  17098. }
  17099. // Detach cameras
  17100. var canvas = this._engine.getRenderingCanvas();
  17101. var index;
  17102. for (index = 0; index < this.cameras.length; index++) {
  17103. this.cameras[index].detachControl(canvas);
  17104. }
  17105. // Release lights
  17106. while (this.lights.length) {
  17107. this.lights[0].dispose();
  17108. }
  17109. // Release meshes
  17110. while (this.meshes.length) {
  17111. this.meshes[0].dispose(true);
  17112. }
  17113. // Release cameras
  17114. while (this.cameras.length) {
  17115. this.cameras[0].dispose();
  17116. }
  17117. // Release materials
  17118. while (this.materials.length) {
  17119. this.materials[0].dispose();
  17120. }
  17121. // Release particles
  17122. while (this.particleSystems.length) {
  17123. this.particleSystems[0].dispose();
  17124. }
  17125. // Release sprites
  17126. while (this.spriteManagers.length) {
  17127. this.spriteManagers[0].dispose();
  17128. }
  17129. // Release layers
  17130. while (this.layers.length) {
  17131. this.layers[0].dispose();
  17132. }
  17133. while (this.highlightLayers.length) {
  17134. this.highlightLayers[0].dispose();
  17135. }
  17136. // Release textures
  17137. while (this.textures.length) {
  17138. this.textures[0].dispose();
  17139. }
  17140. // Release UBO
  17141. this._sceneUbo.dispose();
  17142. // Post-processes
  17143. this.postProcessManager.dispose();
  17144. // Physics
  17145. if (this._physicsEngine) {
  17146. this.disablePhysicsEngine();
  17147. }
  17148. // Remove from engine
  17149. index = this._engine.scenes.indexOf(this);
  17150. if (index > -1) {
  17151. this._engine.scenes.splice(index, 1);
  17152. }
  17153. this._engine.wipeCaches();
  17154. this._engine = null;
  17155. };
  17156. Object.defineProperty(Scene.prototype, "isDisposed", {
  17157. get: function () {
  17158. return !this._engine;
  17159. },
  17160. enumerable: true,
  17161. configurable: true
  17162. });
  17163. // Release sounds & sounds tracks
  17164. Scene.prototype.disposeSounds = function () {
  17165. this.mainSoundTrack.dispose();
  17166. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17167. this.soundTracks[scIndex].dispose();
  17168. }
  17169. };
  17170. // Octrees
  17171. Scene.prototype.getWorldExtends = function () {
  17172. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17173. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17174. for (var index = 0; index < this.meshes.length; index++) {
  17175. var mesh = this.meshes[index];
  17176. mesh.computeWorldMatrix(true);
  17177. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17178. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17179. BABYLON.Tools.CheckExtends(minBox, min, max);
  17180. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17181. }
  17182. return {
  17183. min: min,
  17184. max: max
  17185. };
  17186. };
  17187. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17188. if (maxCapacity === void 0) { maxCapacity = 64; }
  17189. if (maxDepth === void 0) { maxDepth = 2; }
  17190. if (!this._selectionOctree) {
  17191. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17192. }
  17193. var worldExtends = this.getWorldExtends();
  17194. // Update octree
  17195. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17196. return this._selectionOctree;
  17197. };
  17198. // Picking
  17199. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17200. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17201. var engine = this._engine;
  17202. if (!camera) {
  17203. if (!this.activeCamera)
  17204. throw new Error("Active camera not set");
  17205. camera = this.activeCamera;
  17206. }
  17207. var cameraViewport = camera.viewport;
  17208. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17209. // Moving coordinates to local viewport world
  17210. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17211. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17212. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17213. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17214. };
  17215. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17216. if (!BABYLON.PickingInfo) {
  17217. return null;
  17218. }
  17219. var engine = this._engine;
  17220. if (!camera) {
  17221. if (!this.activeCamera)
  17222. throw new Error("Active camera not set");
  17223. camera = this.activeCamera;
  17224. }
  17225. var cameraViewport = camera.viewport;
  17226. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17227. var identity = BABYLON.Matrix.Identity();
  17228. // Moving coordinates to local viewport world
  17229. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17230. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17231. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17232. };
  17233. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17234. if (!BABYLON.PickingInfo) {
  17235. return null;
  17236. }
  17237. var pickingInfo = null;
  17238. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17239. var mesh = this.meshes[meshIndex];
  17240. if (predicate) {
  17241. if (!predicate(mesh)) {
  17242. continue;
  17243. }
  17244. }
  17245. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17246. continue;
  17247. }
  17248. var world = mesh.getWorldMatrix();
  17249. var ray = rayFunction(world);
  17250. var result = mesh.intersects(ray, fastCheck);
  17251. if (!result || !result.hit)
  17252. continue;
  17253. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17254. continue;
  17255. pickingInfo = result;
  17256. if (fastCheck) {
  17257. break;
  17258. }
  17259. }
  17260. return pickingInfo || new BABYLON.PickingInfo();
  17261. };
  17262. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  17263. if (!BABYLON.PickingInfo) {
  17264. return null;
  17265. }
  17266. var pickingInfos = new Array();
  17267. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17268. var mesh = this.meshes[meshIndex];
  17269. if (predicate) {
  17270. if (!predicate(mesh)) {
  17271. continue;
  17272. }
  17273. }
  17274. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17275. continue;
  17276. }
  17277. var world = mesh.getWorldMatrix();
  17278. var ray = rayFunction(world);
  17279. var result = mesh.intersects(ray, false);
  17280. if (!result || !result.hit)
  17281. continue;
  17282. pickingInfos.push(result);
  17283. }
  17284. return pickingInfos;
  17285. };
  17286. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17287. if (!BABYLON.PickingInfo) {
  17288. return null;
  17289. }
  17290. var pickingInfo = null;
  17291. camera = camera || this.activeCamera;
  17292. if (this.spriteManagers.length > 0) {
  17293. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17294. var spriteManager = this.spriteManagers[spriteIndex];
  17295. if (!spriteManager.isPickable) {
  17296. continue;
  17297. }
  17298. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17299. if (!result || !result.hit)
  17300. continue;
  17301. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17302. continue;
  17303. pickingInfo = result;
  17304. if (fastCheck) {
  17305. break;
  17306. }
  17307. }
  17308. }
  17309. return pickingInfo || new BABYLON.PickingInfo();
  17310. };
  17311. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17312. /// <param name="x">X position on screen</param>
  17313. /// <param name="y">Y position on screen</param>
  17314. /// <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>
  17315. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17316. /// <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>
  17317. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17318. var _this = this;
  17319. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17320. };
  17321. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17322. /// <param name="x">X position on screen</param>
  17323. /// <param name="y">Y position on screen</param>
  17324. /// <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>
  17325. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17326. /// <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>
  17327. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17328. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17329. };
  17330. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17331. var _this = this;
  17332. return this._internalPick(function (world) {
  17333. if (!_this._pickWithRayInverseMatrix) {
  17334. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17335. }
  17336. world.invertToRef(_this._pickWithRayInverseMatrix);
  17337. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17338. }, predicate, fastCheck);
  17339. };
  17340. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17341. /// <param name="x">X position on screen</param>
  17342. /// <param name="y">Y position on screen</param>
  17343. /// <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>
  17344. /// <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>
  17345. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  17346. var _this = this;
  17347. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  17348. };
  17349. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17350. /// <param name="ray">Ray to use</param>
  17351. /// <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>
  17352. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  17353. var _this = this;
  17354. return this._internalMultiPick(function (world) {
  17355. if (!_this._pickWithRayInverseMatrix) {
  17356. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17357. }
  17358. world.invertToRef(_this._pickWithRayInverseMatrix);
  17359. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17360. }, predicate);
  17361. };
  17362. Scene.prototype.setPointerOverMesh = function (mesh) {
  17363. if (this._pointerOverMesh === mesh) {
  17364. return;
  17365. }
  17366. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17367. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17368. }
  17369. this._pointerOverMesh = mesh;
  17370. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17371. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17372. }
  17373. };
  17374. Scene.prototype.getPointerOverMesh = function () {
  17375. return this._pointerOverMesh;
  17376. };
  17377. Scene.prototype.setPointerOverSprite = function (sprite) {
  17378. if (this._pointerOverSprite === sprite) {
  17379. return;
  17380. }
  17381. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17382. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17383. }
  17384. this._pointerOverSprite = sprite;
  17385. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17386. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17387. }
  17388. };
  17389. Scene.prototype.getPointerOverSprite = function () {
  17390. return this._pointerOverSprite;
  17391. };
  17392. // Physics
  17393. Scene.prototype.getPhysicsEngine = function () {
  17394. return this._physicsEngine;
  17395. };
  17396. /**
  17397. * Enables physics to the current scene
  17398. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17399. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17400. * @return {boolean} was the physics engine initialized
  17401. */
  17402. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17403. if (this._physicsEngine) {
  17404. return true;
  17405. }
  17406. try {
  17407. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17408. return true;
  17409. }
  17410. catch (e) {
  17411. BABYLON.Tools.Error(e.message);
  17412. return false;
  17413. }
  17414. };
  17415. Scene.prototype.disablePhysicsEngine = function () {
  17416. if (!this._physicsEngine) {
  17417. return;
  17418. }
  17419. this._physicsEngine.dispose();
  17420. this._physicsEngine = undefined;
  17421. };
  17422. Scene.prototype.isPhysicsEnabled = function () {
  17423. return this._physicsEngine !== undefined;
  17424. };
  17425. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17426. var mesh = compound.parts[0].mesh;
  17427. mesh.physicsImpostor.dispose();
  17428. mesh.physicsImpostor = null;
  17429. };
  17430. // Misc.
  17431. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  17432. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  17433. // Light
  17434. if (this.lights.length === 0) {
  17435. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17436. }
  17437. // Camera
  17438. if (!this.activeCamera) {
  17439. // Compute position
  17440. var worldExtends = this.getWorldExtends();
  17441. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  17442. var camera;
  17443. if (createArcRotateCamera) {
  17444. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  17445. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  17446. camera.lowerRadiusLimit = 0.5;
  17447. camera.setTarget(worldCenter);
  17448. }
  17449. else {
  17450. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  17451. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  17452. camera.setTarget(worldCenter);
  17453. }
  17454. camera.minZ = 0.1;
  17455. var maxDist = worldExtends.max.subtract(worldExtends.min).length();
  17456. camera.wheelPrecision = 100.0 / maxDist;
  17457. this.activeCamera = camera;
  17458. }
  17459. };
  17460. // Tags
  17461. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17462. if (tagsQuery === undefined) {
  17463. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17464. return list;
  17465. }
  17466. var listByTags = [];
  17467. forEach = forEach || (function (item) { return; });
  17468. for (var i in list) {
  17469. var item = list[i];
  17470. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17471. listByTags.push(item);
  17472. forEach(item);
  17473. }
  17474. }
  17475. return listByTags;
  17476. };
  17477. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17478. return this._getByTags(this.meshes, tagsQuery, forEach);
  17479. };
  17480. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17481. return this._getByTags(this.cameras, tagsQuery, forEach);
  17482. };
  17483. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17484. return this._getByTags(this.lights, tagsQuery, forEach);
  17485. };
  17486. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17487. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17488. };
  17489. /**
  17490. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17491. * This allowed control for front to back rendering or reversly depending of the special needs.
  17492. *
  17493. * @param renderingGroupId The rendering group id corresponding to its index
  17494. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17495. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17496. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17497. */
  17498. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17499. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17500. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17501. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17502. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  17503. };
  17504. /**
  17505. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17506. *
  17507. * @param renderingGroupId The rendering group id corresponding to its index
  17508. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17509. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17510. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17511. */
  17512. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17513. if (depth === void 0) { depth = true; }
  17514. if (stencil === void 0) { stencil = true; }
  17515. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  17516. };
  17517. /**
  17518. * Will flag all materials as dirty to trigger new shader compilation
  17519. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  17520. */
  17521. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  17522. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  17523. var material = _a[_i];
  17524. if (predicate && !predicate(material)) {
  17525. continue;
  17526. }
  17527. material.markAsDirty(flag);
  17528. }
  17529. };
  17530. return Scene;
  17531. }());
  17532. // Statics
  17533. Scene._FOGMODE_NONE = 0;
  17534. Scene._FOGMODE_EXP = 1;
  17535. Scene._FOGMODE_EXP2 = 2;
  17536. Scene._FOGMODE_LINEAR = 3;
  17537. Scene.MinDeltaTime = 1.0;
  17538. Scene.MaxDeltaTime = 1000.0;
  17539. Scene.DragMovementThreshold = 10; // in pixels
  17540. Scene.LongPressDelay = 500; // in milliseconds
  17541. Scene.DoubleClickDelay = 300; // in milliseconds
  17542. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  17543. BABYLON.Scene = Scene;
  17544. })(BABYLON || (BABYLON = {}));
  17545. //# sourceMappingURL=babylon.scene.js.map
  17546. var BABYLON;
  17547. (function (BABYLON) {
  17548. var Buffer = (function () {
  17549. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  17550. if (engine instanceof BABYLON.Mesh) {
  17551. this._engine = engine.getScene().getEngine();
  17552. }
  17553. else {
  17554. this._engine = engine;
  17555. }
  17556. this._updatable = updatable;
  17557. this._data = data;
  17558. this._strideSize = stride;
  17559. if (!postponeInternalCreation) {
  17560. this.create();
  17561. }
  17562. this._instanced = instanced;
  17563. }
  17564. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  17565. // a lot of these parameters are ignored as they are overriden by the buffer
  17566. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  17567. };
  17568. // Properties
  17569. Buffer.prototype.isUpdatable = function () {
  17570. return this._updatable;
  17571. };
  17572. Buffer.prototype.getData = function () {
  17573. return this._data;
  17574. };
  17575. Buffer.prototype.getBuffer = function () {
  17576. return this._buffer;
  17577. };
  17578. Buffer.prototype.getStrideSize = function () {
  17579. return this._strideSize;
  17580. };
  17581. Buffer.prototype.getIsInstanced = function () {
  17582. return this._instanced;
  17583. };
  17584. // Methods
  17585. Buffer.prototype.create = function (data) {
  17586. if (!data && this._buffer) {
  17587. return; // nothing to do
  17588. }
  17589. data = data || this._data;
  17590. if (!this._buffer) {
  17591. if (this._updatable) {
  17592. this._buffer = this._engine.createDynamicVertexBuffer(data);
  17593. this._data = data;
  17594. }
  17595. else {
  17596. this._buffer = this._engine.createVertexBuffer(data);
  17597. }
  17598. }
  17599. else if (this._updatable) {
  17600. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  17601. this._data = data;
  17602. }
  17603. };
  17604. Buffer.prototype.update = function (data) {
  17605. this.create(data);
  17606. };
  17607. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  17608. if (!this._buffer) {
  17609. return;
  17610. }
  17611. if (this._updatable) {
  17612. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  17613. this._data = null;
  17614. }
  17615. };
  17616. Buffer.prototype.dispose = function () {
  17617. if (!this._buffer) {
  17618. return;
  17619. }
  17620. if (this._engine._releaseBuffer(this._buffer)) {
  17621. this._buffer = null;
  17622. }
  17623. };
  17624. return Buffer;
  17625. }());
  17626. BABYLON.Buffer = Buffer;
  17627. })(BABYLON || (BABYLON = {}));
  17628. //# sourceMappingURL=babylon.buffer.js.map
  17629. var BABYLON;
  17630. (function (BABYLON) {
  17631. var VertexBuffer = (function () {
  17632. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  17633. if (!stride) {
  17634. // Deduce stride from kind
  17635. switch (kind) {
  17636. case VertexBuffer.PositionKind:
  17637. stride = 3;
  17638. break;
  17639. case VertexBuffer.NormalKind:
  17640. stride = 3;
  17641. break;
  17642. case VertexBuffer.UVKind:
  17643. case VertexBuffer.UV2Kind:
  17644. case VertexBuffer.UV3Kind:
  17645. case VertexBuffer.UV4Kind:
  17646. case VertexBuffer.UV5Kind:
  17647. case VertexBuffer.UV6Kind:
  17648. stride = 2;
  17649. break;
  17650. case VertexBuffer.TangentKind:
  17651. case VertexBuffer.ColorKind:
  17652. stride = 4;
  17653. break;
  17654. case VertexBuffer.MatricesIndicesKind:
  17655. case VertexBuffer.MatricesIndicesExtraKind:
  17656. stride = 4;
  17657. break;
  17658. case VertexBuffer.MatricesWeightsKind:
  17659. case VertexBuffer.MatricesWeightsExtraKind:
  17660. stride = 4;
  17661. break;
  17662. }
  17663. }
  17664. if (data instanceof BABYLON.Buffer) {
  17665. if (!stride) {
  17666. stride = data.getStrideSize();
  17667. }
  17668. this._buffer = data;
  17669. this._ownsBuffer = false;
  17670. }
  17671. else {
  17672. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  17673. this._ownsBuffer = true;
  17674. }
  17675. this._stride = stride;
  17676. this._offset = offset ? offset : 0;
  17677. this._size = size ? size : stride;
  17678. this._kind = kind;
  17679. }
  17680. /**
  17681. * Returns the kind of the VertexBuffer (string).
  17682. */
  17683. VertexBuffer.prototype.getKind = function () {
  17684. return this._kind;
  17685. };
  17686. // Properties
  17687. /**
  17688. * Boolean : is the VertexBuffer updatable ?
  17689. */
  17690. VertexBuffer.prototype.isUpdatable = function () {
  17691. return this._buffer.isUpdatable();
  17692. };
  17693. /**
  17694. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  17695. */
  17696. VertexBuffer.prototype.getData = function () {
  17697. return this._buffer.getData();
  17698. };
  17699. /**
  17700. * Returns the WebGLBuffer associated to the VertexBuffer.
  17701. */
  17702. VertexBuffer.prototype.getBuffer = function () {
  17703. return this._buffer.getBuffer();
  17704. };
  17705. /**
  17706. * Returns the stride of the VertexBuffer (integer).
  17707. */
  17708. VertexBuffer.prototype.getStrideSize = function () {
  17709. return this._stride;
  17710. };
  17711. /**
  17712. * Returns the offset (integer).
  17713. */
  17714. VertexBuffer.prototype.getOffset = function () {
  17715. return this._offset;
  17716. };
  17717. /**
  17718. * Returns the VertexBuffer total size (integer).
  17719. */
  17720. VertexBuffer.prototype.getSize = function () {
  17721. return this._size;
  17722. };
  17723. /**
  17724. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  17725. */
  17726. VertexBuffer.prototype.getIsInstanced = function () {
  17727. return this._buffer.getIsInstanced();
  17728. };
  17729. // Methods
  17730. /**
  17731. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  17732. * Returns the created WebGLBuffer.
  17733. */
  17734. VertexBuffer.prototype.create = function (data) {
  17735. return this._buffer.create(data);
  17736. };
  17737. /**
  17738. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  17739. * Returns the updated WebGLBuffer.
  17740. */
  17741. VertexBuffer.prototype.update = function (data) {
  17742. return this._buffer.update(data);
  17743. };
  17744. /**
  17745. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  17746. * Returns the directly updated WebGLBuffer.
  17747. */
  17748. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  17749. return this._buffer.updateDirectly(data, offset);
  17750. };
  17751. /**
  17752. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  17753. */
  17754. VertexBuffer.prototype.dispose = function () {
  17755. if (this._ownsBuffer) {
  17756. this._buffer.dispose();
  17757. }
  17758. };
  17759. Object.defineProperty(VertexBuffer, "PositionKind", {
  17760. get: function () {
  17761. return VertexBuffer._PositionKind;
  17762. },
  17763. enumerable: true,
  17764. configurable: true
  17765. });
  17766. Object.defineProperty(VertexBuffer, "NormalKind", {
  17767. get: function () {
  17768. return VertexBuffer._NormalKind;
  17769. },
  17770. enumerable: true,
  17771. configurable: true
  17772. });
  17773. Object.defineProperty(VertexBuffer, "TangentKind", {
  17774. get: function () {
  17775. return VertexBuffer._TangentKind;
  17776. },
  17777. enumerable: true,
  17778. configurable: true
  17779. });
  17780. Object.defineProperty(VertexBuffer, "UVKind", {
  17781. get: function () {
  17782. return VertexBuffer._UVKind;
  17783. },
  17784. enumerable: true,
  17785. configurable: true
  17786. });
  17787. Object.defineProperty(VertexBuffer, "UV2Kind", {
  17788. get: function () {
  17789. return VertexBuffer._UV2Kind;
  17790. },
  17791. enumerable: true,
  17792. configurable: true
  17793. });
  17794. Object.defineProperty(VertexBuffer, "UV3Kind", {
  17795. get: function () {
  17796. return VertexBuffer._UV3Kind;
  17797. },
  17798. enumerable: true,
  17799. configurable: true
  17800. });
  17801. Object.defineProperty(VertexBuffer, "UV4Kind", {
  17802. get: function () {
  17803. return VertexBuffer._UV4Kind;
  17804. },
  17805. enumerable: true,
  17806. configurable: true
  17807. });
  17808. Object.defineProperty(VertexBuffer, "UV5Kind", {
  17809. get: function () {
  17810. return VertexBuffer._UV5Kind;
  17811. },
  17812. enumerable: true,
  17813. configurable: true
  17814. });
  17815. Object.defineProperty(VertexBuffer, "UV6Kind", {
  17816. get: function () {
  17817. return VertexBuffer._UV6Kind;
  17818. },
  17819. enumerable: true,
  17820. configurable: true
  17821. });
  17822. Object.defineProperty(VertexBuffer, "ColorKind", {
  17823. get: function () {
  17824. return VertexBuffer._ColorKind;
  17825. },
  17826. enumerable: true,
  17827. configurable: true
  17828. });
  17829. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  17830. get: function () {
  17831. return VertexBuffer._MatricesIndicesKind;
  17832. },
  17833. enumerable: true,
  17834. configurable: true
  17835. });
  17836. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  17837. get: function () {
  17838. return VertexBuffer._MatricesWeightsKind;
  17839. },
  17840. enumerable: true,
  17841. configurable: true
  17842. });
  17843. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  17844. get: function () {
  17845. return VertexBuffer._MatricesIndicesExtraKind;
  17846. },
  17847. enumerable: true,
  17848. configurable: true
  17849. });
  17850. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  17851. get: function () {
  17852. return VertexBuffer._MatricesWeightsExtraKind;
  17853. },
  17854. enumerable: true,
  17855. configurable: true
  17856. });
  17857. return VertexBuffer;
  17858. }());
  17859. // Enums
  17860. VertexBuffer._PositionKind = "position";
  17861. VertexBuffer._NormalKind = "normal";
  17862. VertexBuffer._TangentKind = "tangent";
  17863. VertexBuffer._UVKind = "uv";
  17864. VertexBuffer._UV2Kind = "uv2";
  17865. VertexBuffer._UV3Kind = "uv3";
  17866. VertexBuffer._UV4Kind = "uv4";
  17867. VertexBuffer._UV5Kind = "uv5";
  17868. VertexBuffer._UV6Kind = "uv6";
  17869. VertexBuffer._ColorKind = "color";
  17870. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  17871. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  17872. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  17873. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  17874. BABYLON.VertexBuffer = VertexBuffer;
  17875. })(BABYLON || (BABYLON = {}));
  17876. //# sourceMappingURL=babylon.vertexBuffer.js.map
  17877. var BABYLON;
  17878. (function (BABYLON) {
  17879. var BaseTexture = (function () {
  17880. function BaseTexture(scene) {
  17881. this._hasAlpha = false;
  17882. this.getAlphaFromRGB = false;
  17883. this.level = 1;
  17884. this.coordinatesIndex = 0;
  17885. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17886. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17887. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17888. this.anisotropicFilteringLevel = 4;
  17889. this.isCube = false;
  17890. this.isRenderTarget = false;
  17891. this.animations = new Array();
  17892. /**
  17893. * An event triggered when the texture is disposed.
  17894. * @type {BABYLON.Observable}
  17895. */
  17896. this.onDisposeObservable = new BABYLON.Observable();
  17897. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17898. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  17899. this._scene.textures.push(this);
  17900. this._uid = null;
  17901. }
  17902. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  17903. get: function () {
  17904. return this._hasAlpha;
  17905. },
  17906. set: function (value) {
  17907. if (this._hasAlpha === value) {
  17908. return;
  17909. }
  17910. this._hasAlpha = value;
  17911. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17912. },
  17913. enumerable: true,
  17914. configurable: true
  17915. });
  17916. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  17917. get: function () {
  17918. return this._coordinatesMode;
  17919. },
  17920. set: function (value) {
  17921. if (this._coordinatesMode === value) {
  17922. return;
  17923. }
  17924. this._coordinatesMode = value;
  17925. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17926. },
  17927. enumerable: true,
  17928. configurable: true
  17929. });
  17930. Object.defineProperty(BaseTexture.prototype, "uid", {
  17931. get: function () {
  17932. if (!this._uid) {
  17933. this._uid = BABYLON.Tools.RandomId();
  17934. }
  17935. return this._uid;
  17936. },
  17937. enumerable: true,
  17938. configurable: true
  17939. });
  17940. BaseTexture.prototype.toString = function () {
  17941. return this.name;
  17942. };
  17943. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  17944. set: function (callback) {
  17945. if (this._onDisposeObserver) {
  17946. this.onDisposeObservable.remove(this._onDisposeObserver);
  17947. }
  17948. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17949. },
  17950. enumerable: true,
  17951. configurable: true
  17952. });
  17953. BaseTexture.prototype.getScene = function () {
  17954. return this._scene;
  17955. };
  17956. BaseTexture.prototype.getTextureMatrix = function () {
  17957. return null;
  17958. };
  17959. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17960. return null;
  17961. };
  17962. BaseTexture.prototype.getInternalTexture = function () {
  17963. return this._texture;
  17964. };
  17965. BaseTexture.prototype.isReady = function () {
  17966. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17967. return true;
  17968. }
  17969. if (this._texture) {
  17970. return this._texture.isReady;
  17971. }
  17972. return false;
  17973. };
  17974. BaseTexture.prototype.getSize = function () {
  17975. if (this._texture._width) {
  17976. return new BABYLON.Size(this._texture._width, this._texture._height);
  17977. }
  17978. if (this._texture._size) {
  17979. return new BABYLON.Size(this._texture._size, this._texture._size);
  17980. }
  17981. return BABYLON.Size.Zero();
  17982. };
  17983. BaseTexture.prototype.getBaseSize = function () {
  17984. if (!this.isReady() || !this._texture)
  17985. return BABYLON.Size.Zero();
  17986. if (this._texture._size) {
  17987. return new BABYLON.Size(this._texture._size, this._texture._size);
  17988. }
  17989. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  17990. };
  17991. BaseTexture.prototype.scale = function (ratio) {
  17992. };
  17993. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17994. get: function () {
  17995. return false;
  17996. },
  17997. enumerable: true,
  17998. configurable: true
  17999. });
  18000. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  18001. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18002. for (var index = 0; index < texturesCache.length; index++) {
  18003. var texturesCacheEntry = texturesCache[index];
  18004. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18005. texturesCache.splice(index, 1);
  18006. return;
  18007. }
  18008. }
  18009. };
  18010. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  18011. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  18012. for (var index = 0; index < texturesCache.length; index++) {
  18013. var texturesCacheEntry = texturesCache[index];
  18014. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  18015. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  18016. texturesCacheEntry.references++;
  18017. return texturesCacheEntry;
  18018. }
  18019. }
  18020. }
  18021. return null;
  18022. };
  18023. BaseTexture.prototype.delayLoad = function () {
  18024. };
  18025. BaseTexture.prototype.clone = function () {
  18026. return null;
  18027. };
  18028. BaseTexture.prototype.releaseInternalTexture = function () {
  18029. if (this._texture) {
  18030. this._scene.getEngine().releaseInternalTexture(this._texture);
  18031. delete this._texture;
  18032. }
  18033. };
  18034. BaseTexture.prototype.dispose = function () {
  18035. // Animations
  18036. this.getScene().stopAnimation(this);
  18037. // Remove from scene
  18038. this._scene._removePendingData(this);
  18039. var index = this._scene.textures.indexOf(this);
  18040. if (index >= 0) {
  18041. this._scene.textures.splice(index, 1);
  18042. }
  18043. if (this._texture === undefined) {
  18044. return;
  18045. }
  18046. // Release
  18047. this.releaseInternalTexture();
  18048. // Callback
  18049. this.onDisposeObservable.notifyObservers(this);
  18050. this.onDisposeObservable.clear();
  18051. };
  18052. BaseTexture.prototype.serialize = function () {
  18053. if (!this.name) {
  18054. return null;
  18055. }
  18056. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18057. // Animations
  18058. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18059. return serializationObject;
  18060. };
  18061. return BaseTexture;
  18062. }());
  18063. __decorate([
  18064. BABYLON.serialize()
  18065. ], BaseTexture.prototype, "name", void 0);
  18066. __decorate([
  18067. BABYLON.serialize("hasAlpha")
  18068. ], BaseTexture.prototype, "_hasAlpha", void 0);
  18069. __decorate([
  18070. BABYLON.serialize()
  18071. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  18072. __decorate([
  18073. BABYLON.serialize()
  18074. ], BaseTexture.prototype, "level", void 0);
  18075. __decorate([
  18076. BABYLON.serialize()
  18077. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  18078. __decorate([
  18079. BABYLON.serialize("coordinatesMode")
  18080. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  18081. __decorate([
  18082. BABYLON.serialize()
  18083. ], BaseTexture.prototype, "wrapU", void 0);
  18084. __decorate([
  18085. BABYLON.serialize()
  18086. ], BaseTexture.prototype, "wrapV", void 0);
  18087. __decorate([
  18088. BABYLON.serialize()
  18089. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  18090. __decorate([
  18091. BABYLON.serialize()
  18092. ], BaseTexture.prototype, "isCube", void 0);
  18093. __decorate([
  18094. BABYLON.serialize()
  18095. ], BaseTexture.prototype, "isRenderTarget", void 0);
  18096. BABYLON.BaseTexture = BaseTexture;
  18097. })(BABYLON || (BABYLON = {}));
  18098. //# sourceMappingURL=babylon.baseTexture.js.map
  18099. var BABYLON;
  18100. (function (BABYLON) {
  18101. var Texture = (function (_super) {
  18102. __extends(Texture, _super);
  18103. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  18104. if (noMipmap === void 0) { noMipmap = false; }
  18105. if (invertY === void 0) { invertY = true; }
  18106. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18107. if (onLoad === void 0) { onLoad = null; }
  18108. if (onError === void 0) { onError = null; }
  18109. if (buffer === void 0) { buffer = null; }
  18110. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18111. var _this = _super.call(this, scene) || this;
  18112. _this.uOffset = 0;
  18113. _this.vOffset = 0;
  18114. _this.uScale = 1.0;
  18115. _this.vScale = 1.0;
  18116. _this.uAng = 0;
  18117. _this.vAng = 0;
  18118. _this.wAng = 0;
  18119. _this.name = url;
  18120. _this.url = url;
  18121. _this._noMipmap = noMipmap;
  18122. _this._invertY = invertY;
  18123. _this._samplingMode = samplingMode;
  18124. _this._buffer = buffer;
  18125. _this._deleteBuffer = deleteBuffer;
  18126. _this._format = format;
  18127. if (!url) {
  18128. return _this;
  18129. }
  18130. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  18131. var load = function () {
  18132. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  18133. _this.onLoadObservable.notifyObservers(true);
  18134. }
  18135. if (onLoad) {
  18136. onLoad();
  18137. }
  18138. };
  18139. if (!_this._texture) {
  18140. if (!scene.useDelayedTextureLoading) {
  18141. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  18142. if (deleteBuffer) {
  18143. delete _this._buffer;
  18144. }
  18145. }
  18146. else {
  18147. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18148. _this._delayedOnLoad = load;
  18149. _this._delayedOnError = onError;
  18150. }
  18151. }
  18152. else {
  18153. if (_this._texture.isReady) {
  18154. BABYLON.Tools.SetImmediate(function () { return load(); });
  18155. }
  18156. else {
  18157. _this._texture.onLoadedCallbacks.push(load);
  18158. }
  18159. }
  18160. return _this;
  18161. }
  18162. Object.defineProperty(Texture.prototype, "noMipmap", {
  18163. get: function () {
  18164. return this._noMipmap;
  18165. },
  18166. enumerable: true,
  18167. configurable: true
  18168. });
  18169. Texture.prototype.delayLoad = function () {
  18170. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18171. return;
  18172. }
  18173. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18174. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  18175. if (!this._texture) {
  18176. 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);
  18177. if (this._deleteBuffer) {
  18178. delete this._buffer;
  18179. }
  18180. }
  18181. };
  18182. Texture.prototype.updateSamplingMode = function (samplingMode) {
  18183. if (!this._texture) {
  18184. return;
  18185. }
  18186. this._samplingMode = samplingMode;
  18187. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  18188. };
  18189. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  18190. x *= this.uScale;
  18191. y *= this.vScale;
  18192. x -= 0.5 * this.uScale;
  18193. y -= 0.5 * this.vScale;
  18194. z -= 0.5;
  18195. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  18196. t.x += 0.5 * this.uScale + this.uOffset;
  18197. t.y += 0.5 * this.vScale + this.vOffset;
  18198. t.z += 0.5;
  18199. };
  18200. Texture.prototype.getTextureMatrix = function () {
  18201. if (this.uOffset === this._cachedUOffset &&
  18202. this.vOffset === this._cachedVOffset &&
  18203. this.uScale === this._cachedUScale &&
  18204. this.vScale === this._cachedVScale &&
  18205. this.uAng === this._cachedUAng &&
  18206. this.vAng === this._cachedVAng &&
  18207. this.wAng === this._cachedWAng) {
  18208. return this._cachedTextureMatrix;
  18209. }
  18210. this._cachedUOffset = this.uOffset;
  18211. this._cachedVOffset = this.vOffset;
  18212. this._cachedUScale = this.uScale;
  18213. this._cachedVScale = this.vScale;
  18214. this._cachedUAng = this.uAng;
  18215. this._cachedVAng = this.vAng;
  18216. this._cachedWAng = this.wAng;
  18217. if (!this._cachedTextureMatrix) {
  18218. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  18219. this._rowGenerationMatrix = new BABYLON.Matrix();
  18220. this._t0 = BABYLON.Vector3.Zero();
  18221. this._t1 = BABYLON.Vector3.Zero();
  18222. this._t2 = BABYLON.Vector3.Zero();
  18223. }
  18224. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  18225. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  18226. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  18227. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  18228. this._t1.subtractInPlace(this._t0);
  18229. this._t2.subtractInPlace(this._t0);
  18230. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18231. this._cachedTextureMatrix.m[0] = this._t1.x;
  18232. this._cachedTextureMatrix.m[1] = this._t1.y;
  18233. this._cachedTextureMatrix.m[2] = this._t1.z;
  18234. this._cachedTextureMatrix.m[4] = this._t2.x;
  18235. this._cachedTextureMatrix.m[5] = this._t2.y;
  18236. this._cachedTextureMatrix.m[6] = this._t2.z;
  18237. this._cachedTextureMatrix.m[8] = this._t0.x;
  18238. this._cachedTextureMatrix.m[9] = this._t0.y;
  18239. this._cachedTextureMatrix.m[10] = this._t0.z;
  18240. return this._cachedTextureMatrix;
  18241. };
  18242. Texture.prototype.getReflectionTextureMatrix = function () {
  18243. if (this.uOffset === this._cachedUOffset &&
  18244. this.vOffset === this._cachedVOffset &&
  18245. this.uScale === this._cachedUScale &&
  18246. this.vScale === this._cachedVScale &&
  18247. this.coordinatesMode === this._cachedCoordinatesMode) {
  18248. return this._cachedTextureMatrix;
  18249. }
  18250. if (!this._cachedTextureMatrix) {
  18251. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  18252. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  18253. }
  18254. this._cachedCoordinatesMode = this.coordinatesMode;
  18255. switch (this.coordinatesMode) {
  18256. case Texture.PLANAR_MODE:
  18257. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18258. this._cachedTextureMatrix[0] = this.uScale;
  18259. this._cachedTextureMatrix[5] = this.vScale;
  18260. this._cachedTextureMatrix[12] = this.uOffset;
  18261. this._cachedTextureMatrix[13] = this.vOffset;
  18262. break;
  18263. case Texture.PROJECTION_MODE:
  18264. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  18265. this._projectionModeMatrix.m[0] = 0.5;
  18266. this._projectionModeMatrix.m[5] = -0.5;
  18267. this._projectionModeMatrix.m[10] = 0.0;
  18268. this._projectionModeMatrix.m[12] = 0.5;
  18269. this._projectionModeMatrix.m[13] = 0.5;
  18270. this._projectionModeMatrix.m[14] = 1.0;
  18271. this._projectionModeMatrix.m[15] = 1.0;
  18272. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  18273. break;
  18274. default:
  18275. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18276. break;
  18277. }
  18278. return this._cachedTextureMatrix;
  18279. };
  18280. Texture.prototype.clone = function () {
  18281. var _this = this;
  18282. return BABYLON.SerializationHelper.Clone(function () {
  18283. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  18284. }, this);
  18285. };
  18286. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  18287. get: function () {
  18288. if (!this._onLoadObservarble) {
  18289. this._onLoadObservarble = new BABYLON.Observable();
  18290. }
  18291. return this._onLoadObservarble;
  18292. },
  18293. enumerable: true,
  18294. configurable: true
  18295. });
  18296. // Statics
  18297. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  18298. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18299. if (onLoad === void 0) { onLoad = null; }
  18300. if (onError === void 0) { onError = null; }
  18301. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  18302. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  18303. };
  18304. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  18305. if (parsedTexture.customType) {
  18306. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  18307. // Update Sampling Mode
  18308. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  18309. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  18310. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  18311. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  18312. }
  18313. }
  18314. return parsedCustomTexture;
  18315. }
  18316. if (parsedTexture.isCube) {
  18317. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  18318. }
  18319. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18320. return null;
  18321. }
  18322. var texture = BABYLON.SerializationHelper.Parse(function () {
  18323. if (parsedTexture.mirrorPlane) {
  18324. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18325. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  18326. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18327. return mirrorTexture;
  18328. }
  18329. else if (parsedTexture.isRenderTarget) {
  18330. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18331. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  18332. return renderTargetTexture;
  18333. }
  18334. else {
  18335. var texture;
  18336. if (parsedTexture.base64String) {
  18337. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  18338. }
  18339. else {
  18340. texture = new Texture(rootUrl + parsedTexture.name, scene);
  18341. }
  18342. return texture;
  18343. }
  18344. }, parsedTexture, scene);
  18345. // Update Sampling Mode
  18346. if (parsedTexture.samplingMode) {
  18347. var sampling = parsedTexture.samplingMode;
  18348. if (texture._samplingMode !== sampling) {
  18349. texture.updateSamplingMode(sampling);
  18350. }
  18351. }
  18352. // Animations
  18353. if (parsedTexture.animations) {
  18354. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18355. var parsedAnimation = parsedTexture.animations[animationIndex];
  18356. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18357. }
  18358. }
  18359. return texture;
  18360. };
  18361. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  18362. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18363. if (noMipmap === void 0) { noMipmap = false; }
  18364. if (invertY === void 0) { invertY = true; }
  18365. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18366. if (onLoad === void 0) { onLoad = null; }
  18367. if (onError === void 0) { onError = null; }
  18368. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  18369. if (name.substr(0, 5) !== "data:") {
  18370. name = "data:" + name;
  18371. }
  18372. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  18373. };
  18374. return Texture;
  18375. }(BABYLON.BaseTexture));
  18376. // Constants
  18377. Texture.NEAREST_SAMPLINGMODE = 1;
  18378. Texture.BILINEAR_SAMPLINGMODE = 2;
  18379. Texture.TRILINEAR_SAMPLINGMODE = 3;
  18380. Texture.EXPLICIT_MODE = 0;
  18381. Texture.SPHERICAL_MODE = 1;
  18382. Texture.PLANAR_MODE = 2;
  18383. Texture.CUBIC_MODE = 3;
  18384. Texture.PROJECTION_MODE = 4;
  18385. Texture.SKYBOX_MODE = 5;
  18386. Texture.INVCUBIC_MODE = 6;
  18387. Texture.EQUIRECTANGULAR_MODE = 7;
  18388. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  18389. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18390. Texture.CLAMP_ADDRESSMODE = 0;
  18391. Texture.WRAP_ADDRESSMODE = 1;
  18392. Texture.MIRROR_ADDRESSMODE = 2;
  18393. __decorate([
  18394. BABYLON.serialize()
  18395. ], Texture.prototype, "url", void 0);
  18396. __decorate([
  18397. BABYLON.serialize()
  18398. ], Texture.prototype, "uOffset", void 0);
  18399. __decorate([
  18400. BABYLON.serialize()
  18401. ], Texture.prototype, "vOffset", void 0);
  18402. __decorate([
  18403. BABYLON.serialize()
  18404. ], Texture.prototype, "uScale", void 0);
  18405. __decorate([
  18406. BABYLON.serialize()
  18407. ], Texture.prototype, "vScale", void 0);
  18408. __decorate([
  18409. BABYLON.serialize()
  18410. ], Texture.prototype, "uAng", void 0);
  18411. __decorate([
  18412. BABYLON.serialize()
  18413. ], Texture.prototype, "vAng", void 0);
  18414. __decorate([
  18415. BABYLON.serialize()
  18416. ], Texture.prototype, "wAng", void 0);
  18417. BABYLON.Texture = Texture;
  18418. })(BABYLON || (BABYLON = {}));
  18419. //# sourceMappingURL=babylon.texture.js.map
  18420. var BABYLON;
  18421. (function (BABYLON) {
  18422. var _InstancesBatch = (function () {
  18423. function _InstancesBatch() {
  18424. this.mustReturn = false;
  18425. this.visibleInstances = new Array();
  18426. this.renderSelf = new Array();
  18427. }
  18428. return _InstancesBatch;
  18429. }());
  18430. BABYLON._InstancesBatch = _InstancesBatch;
  18431. var Mesh = (function (_super) {
  18432. __extends(Mesh, _super);
  18433. /**
  18434. * @constructor
  18435. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18436. * @param {Scene} scene The scene to add this mesh to.
  18437. * @param {Node} parent The parent of this mesh, if it has one
  18438. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18439. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18440. * When false, achieved by calling a clone(), also passing False.
  18441. * This will make creation of children, recursive.
  18442. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  18443. */
  18444. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18445. if (parent === void 0) { parent = null; }
  18446. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18447. var _this = _super.call(this, name, scene) || this;
  18448. // Events
  18449. /**
  18450. * An event triggered before rendering the mesh
  18451. * @type {BABYLON.Observable}
  18452. */
  18453. _this.onBeforeRenderObservable = new BABYLON.Observable();
  18454. /**
  18455. * An event triggered after rendering the mesh
  18456. * @type {BABYLON.Observable}
  18457. */
  18458. _this.onAfterRenderObservable = new BABYLON.Observable();
  18459. /**
  18460. * An event triggered before drawing the mesh
  18461. * @type {BABYLON.Observable}
  18462. */
  18463. _this.onBeforeDrawObservable = new BABYLON.Observable();
  18464. // Members
  18465. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18466. _this.instances = new Array();
  18467. _this._LODLevels = new Array();
  18468. _this._visibleInstances = {};
  18469. _this._renderIdForInstances = new Array();
  18470. _this._batchCache = new _InstancesBatch();
  18471. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  18472. _this._sideOrientation = Mesh._DEFAULTSIDE;
  18473. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  18474. // Will be used to save a source mesh reference, If any
  18475. _this._source = null;
  18476. if (source) {
  18477. // Source mesh
  18478. _this._source = source;
  18479. // Geometry
  18480. if (source._geometry) {
  18481. source._geometry.applyToMesh(_this);
  18482. }
  18483. // Deep copy
  18484. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  18485. // Parent
  18486. _this.parent = source.parent;
  18487. // Pivot
  18488. _this.setPivotMatrix(source.getPivotMatrix());
  18489. _this.id = name + "." + source.id;
  18490. // Material
  18491. _this.material = source.material;
  18492. var index;
  18493. if (!doNotCloneChildren) {
  18494. // Children
  18495. for (index = 0; index < scene.meshes.length; index++) {
  18496. var mesh = scene.meshes[index];
  18497. if (mesh.parent === source) {
  18498. // doNotCloneChildren is always going to be False
  18499. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  18500. }
  18501. }
  18502. }
  18503. // Physics clone
  18504. var physicsEngine = _this.getScene().getPhysicsEngine();
  18505. if (clonePhysicsImpostor && physicsEngine) {
  18506. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  18507. if (impostor) {
  18508. _this.physicsImpostor = impostor.clone(_this);
  18509. }
  18510. }
  18511. // Particles
  18512. for (index = 0; index < scene.particleSystems.length; index++) {
  18513. var system = scene.particleSystems[index];
  18514. if (system.emitter === source) {
  18515. system.clone(system.name, _this);
  18516. }
  18517. }
  18518. _this.computeWorldMatrix(true);
  18519. }
  18520. // Parent
  18521. if (parent !== null) {
  18522. _this.parent = parent;
  18523. }
  18524. return _this;
  18525. }
  18526. Object.defineProperty(Mesh, "FRONTSIDE", {
  18527. /**
  18528. * Mesh side orientation : usually the external or front surface
  18529. */
  18530. get: function () {
  18531. return Mesh._FRONTSIDE;
  18532. },
  18533. enumerable: true,
  18534. configurable: true
  18535. });
  18536. Object.defineProperty(Mesh, "BACKSIDE", {
  18537. /**
  18538. * Mesh side orientation : usually the internal or back surface
  18539. */
  18540. get: function () {
  18541. return Mesh._BACKSIDE;
  18542. },
  18543. enumerable: true,
  18544. configurable: true
  18545. });
  18546. Object.defineProperty(Mesh, "DOUBLESIDE", {
  18547. /**
  18548. * Mesh side orientation : both internal and external or front and back surfaces
  18549. */
  18550. get: function () {
  18551. return Mesh._DOUBLESIDE;
  18552. },
  18553. enumerable: true,
  18554. configurable: true
  18555. });
  18556. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  18557. /**
  18558. * Mesh side orientation : by default, `FRONTSIDE`
  18559. */
  18560. get: function () {
  18561. return Mesh._DEFAULTSIDE;
  18562. },
  18563. enumerable: true,
  18564. configurable: true
  18565. });
  18566. Object.defineProperty(Mesh, "NO_CAP", {
  18567. /**
  18568. * Mesh cap setting : no cap
  18569. */
  18570. get: function () {
  18571. return Mesh._NO_CAP;
  18572. },
  18573. enumerable: true,
  18574. configurable: true
  18575. });
  18576. Object.defineProperty(Mesh, "CAP_START", {
  18577. /**
  18578. * Mesh cap setting : one cap at the beginning of the mesh
  18579. */
  18580. get: function () {
  18581. return Mesh._CAP_START;
  18582. },
  18583. enumerable: true,
  18584. configurable: true
  18585. });
  18586. Object.defineProperty(Mesh, "CAP_END", {
  18587. /**
  18588. * Mesh cap setting : one cap at the end of the mesh
  18589. */
  18590. get: function () {
  18591. return Mesh._CAP_END;
  18592. },
  18593. enumerable: true,
  18594. configurable: true
  18595. });
  18596. Object.defineProperty(Mesh, "CAP_ALL", {
  18597. /**
  18598. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  18599. */
  18600. get: function () {
  18601. return Mesh._CAP_ALL;
  18602. },
  18603. enumerable: true,
  18604. configurable: true
  18605. });
  18606. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  18607. set: function (callback) {
  18608. if (this._onBeforeDrawObserver) {
  18609. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18610. }
  18611. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18612. },
  18613. enumerable: true,
  18614. configurable: true
  18615. });
  18616. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  18617. get: function () {
  18618. return this._morphTargetManager;
  18619. },
  18620. set: function (value) {
  18621. if (this._morphTargetManager === value) {
  18622. return;
  18623. }
  18624. this._morphTargetManager = value;
  18625. this._syncGeometryWithMorphTargetManager();
  18626. },
  18627. enumerable: true,
  18628. configurable: true
  18629. });
  18630. Object.defineProperty(Mesh.prototype, "source", {
  18631. get: function () {
  18632. return this._source;
  18633. },
  18634. enumerable: true,
  18635. configurable: true
  18636. });
  18637. // Methods
  18638. /**
  18639. * Returns the string "Mesh".
  18640. */
  18641. Mesh.prototype.getClassName = function () {
  18642. return "Mesh";
  18643. };
  18644. /**
  18645. * Returns a string.
  18646. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18647. */
  18648. Mesh.prototype.toString = function (fullDetails) {
  18649. var ret = _super.prototype.toString.call(this, fullDetails);
  18650. ret += ", n vertices: " + this.getTotalVertices();
  18651. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18652. if (this.animations) {
  18653. for (var i = 0; i < this.animations.length; i++) {
  18654. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18655. }
  18656. }
  18657. if (fullDetails) {
  18658. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18659. }
  18660. return ret;
  18661. };
  18662. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18663. /**
  18664. * True if the mesh has some Levels Of Details (LOD).
  18665. * Returns a boolean.
  18666. */
  18667. get: function () {
  18668. return this._LODLevels.length > 0;
  18669. },
  18670. enumerable: true,
  18671. configurable: true
  18672. });
  18673. Mesh.prototype._sortLODLevels = function () {
  18674. this._LODLevels.sort(function (a, b) {
  18675. if (a.distance < b.distance) {
  18676. return 1;
  18677. }
  18678. if (a.distance > b.distance) {
  18679. return -1;
  18680. }
  18681. return 0;
  18682. });
  18683. };
  18684. /**
  18685. * Add a mesh as LOD level triggered at the given distance.
  18686. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18687. * @param {number} distance The distance from the center of the object to show this level
  18688. * @param {Mesh} mesh The mesh to be added as LOD level
  18689. * @return {Mesh} This mesh (for chaining)
  18690. */
  18691. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18692. if (mesh && mesh._masterMesh) {
  18693. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18694. return this;
  18695. }
  18696. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18697. this._LODLevels.push(level);
  18698. if (mesh) {
  18699. mesh._masterMesh = this;
  18700. }
  18701. this._sortLODLevels();
  18702. return this;
  18703. };
  18704. /**
  18705. * Returns the LOD level mesh at the passed distance or null if not found.
  18706. * It is related to the method `addLODLevel(distance, mesh)`.
  18707. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18708. * Returns an object Mesh or `null`.
  18709. */
  18710. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18711. for (var index = 0; index < this._LODLevels.length; index++) {
  18712. var level = this._LODLevels[index];
  18713. if (level.distance === distance) {
  18714. return level.mesh;
  18715. }
  18716. }
  18717. return null;
  18718. };
  18719. /**
  18720. * Remove a mesh from the LOD array
  18721. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18722. * @param {Mesh} mesh The mesh to be removed.
  18723. * @return {Mesh} This mesh (for chaining)
  18724. */
  18725. Mesh.prototype.removeLODLevel = function (mesh) {
  18726. for (var index = 0; index < this._LODLevels.length; index++) {
  18727. if (this._LODLevels[index].mesh === mesh) {
  18728. this._LODLevels.splice(index, 1);
  18729. if (mesh) {
  18730. mesh._masterMesh = null;
  18731. }
  18732. }
  18733. }
  18734. this._sortLODLevels();
  18735. return this;
  18736. };
  18737. /**
  18738. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  18739. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18740. */
  18741. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  18742. if (!this._LODLevels || this._LODLevels.length === 0) {
  18743. return this;
  18744. }
  18745. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18746. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18747. if (this.onLODLevelSelection) {
  18748. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18749. }
  18750. return this;
  18751. }
  18752. for (var index = 0; index < this._LODLevels.length; index++) {
  18753. var level = this._LODLevels[index];
  18754. if (level.distance < distanceToCamera) {
  18755. if (level.mesh) {
  18756. level.mesh._preActivate();
  18757. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18758. }
  18759. if (this.onLODLevelSelection) {
  18760. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18761. }
  18762. return level.mesh;
  18763. }
  18764. }
  18765. if (this.onLODLevelSelection) {
  18766. this.onLODLevelSelection(distanceToCamera, this, this);
  18767. }
  18768. return this;
  18769. };
  18770. Object.defineProperty(Mesh.prototype, "geometry", {
  18771. /**
  18772. * Returns the mesh internal Geometry object.
  18773. */
  18774. get: function () {
  18775. return this._geometry;
  18776. },
  18777. enumerable: true,
  18778. configurable: true
  18779. });
  18780. /**
  18781. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18782. */
  18783. Mesh.prototype.getTotalVertices = function () {
  18784. if (!this._geometry) {
  18785. return 0;
  18786. }
  18787. return this._geometry.getTotalVertices();
  18788. };
  18789. /**
  18790. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18791. * 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.
  18792. * Returns null if the mesh has no geometry or no vertex buffer.
  18793. * Possible `kind` values :
  18794. * - BABYLON.VertexBuffer.PositionKind
  18795. * - BABYLON.VertexBuffer.UVKind
  18796. * - BABYLON.VertexBuffer.UV2Kind
  18797. * - BABYLON.VertexBuffer.UV3Kind
  18798. * - BABYLON.VertexBuffer.UV4Kind
  18799. * - BABYLON.VertexBuffer.UV5Kind
  18800. * - BABYLON.VertexBuffer.UV6Kind
  18801. * - BABYLON.VertexBuffer.ColorKind
  18802. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18803. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18804. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18805. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18806. */
  18807. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18808. if (!this._geometry) {
  18809. return null;
  18810. }
  18811. return this._geometry.getVerticesData(kind, copyWhenShared);
  18812. };
  18813. /**
  18814. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18815. * Returns `undefined` if the mesh has no geometry.
  18816. * Possible `kind` values :
  18817. * - BABYLON.VertexBuffer.PositionKind
  18818. * - BABYLON.VertexBuffer.UVKind
  18819. * - BABYLON.VertexBuffer.UV2Kind
  18820. * - BABYLON.VertexBuffer.UV3Kind
  18821. * - BABYLON.VertexBuffer.UV4Kind
  18822. * - BABYLON.VertexBuffer.UV5Kind
  18823. * - BABYLON.VertexBuffer.UV6Kind
  18824. * - BABYLON.VertexBuffer.ColorKind
  18825. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18826. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18827. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18828. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18829. */
  18830. Mesh.prototype.getVertexBuffer = function (kind) {
  18831. if (!this._geometry) {
  18832. return undefined;
  18833. }
  18834. return this._geometry.getVertexBuffer(kind);
  18835. };
  18836. /**
  18837. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18838. * Possible `kind` values :
  18839. * - BABYLON.VertexBuffer.PositionKind
  18840. * - BABYLON.VertexBuffer.UVKind
  18841. * - BABYLON.VertexBuffer.UV2Kind
  18842. * - BABYLON.VertexBuffer.UV3Kind
  18843. * - BABYLON.VertexBuffer.UV4Kind
  18844. * - BABYLON.VertexBuffer.UV5Kind
  18845. * - BABYLON.VertexBuffer.UV6Kind
  18846. * - BABYLON.VertexBuffer.ColorKind
  18847. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18848. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18849. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18850. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18851. */
  18852. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18853. if (!this._geometry) {
  18854. if (this._delayInfo) {
  18855. return this._delayInfo.indexOf(kind) !== -1;
  18856. }
  18857. return false;
  18858. }
  18859. return this._geometry.isVerticesDataPresent(kind);
  18860. };
  18861. /**
  18862. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18863. * Possible `kind` values :
  18864. * - BABYLON.VertexBuffer.PositionKind
  18865. * - BABYLON.VertexBuffer.UVKind
  18866. * - BABYLON.VertexBuffer.UV2Kind
  18867. * - BABYLON.VertexBuffer.UV3Kind
  18868. * - BABYLON.VertexBuffer.UV4Kind
  18869. * - BABYLON.VertexBuffer.UV5Kind
  18870. * - BABYLON.VertexBuffer.UV6Kind
  18871. * - BABYLON.VertexBuffer.ColorKind
  18872. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18873. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18874. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18875. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18876. */
  18877. Mesh.prototype.getVerticesDataKinds = function () {
  18878. if (!this._geometry) {
  18879. var result = [];
  18880. if (this._delayInfo) {
  18881. this._delayInfo.forEach(function (kind, index, array) {
  18882. result.push(kind);
  18883. });
  18884. }
  18885. return result;
  18886. }
  18887. return this._geometry.getVerticesDataKinds();
  18888. };
  18889. /**
  18890. * Returns a positive integer : the total number of indices in this mesh geometry.
  18891. * Returns zero if the mesh has no geometry.
  18892. */
  18893. Mesh.prototype.getTotalIndices = function () {
  18894. if (!this._geometry) {
  18895. return 0;
  18896. }
  18897. return this._geometry.getTotalIndices();
  18898. };
  18899. /**
  18900. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  18901. * 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.
  18902. * Returns an empty array if the mesh has no geometry.
  18903. */
  18904. Mesh.prototype.getIndices = function (copyWhenShared) {
  18905. if (!this._geometry) {
  18906. return [];
  18907. }
  18908. return this._geometry.getIndices(copyWhenShared);
  18909. };
  18910. Object.defineProperty(Mesh.prototype, "isBlocked", {
  18911. get: function () {
  18912. return this._masterMesh !== null && this._masterMesh !== undefined;
  18913. },
  18914. enumerable: true,
  18915. configurable: true
  18916. });
  18917. /**
  18918. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  18919. */
  18920. Mesh.prototype.isReady = function () {
  18921. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18922. return false;
  18923. }
  18924. return _super.prototype.isReady.call(this);
  18925. };
  18926. /**
  18927. * Boolean : true if the mesh has been disposed.
  18928. */
  18929. Mesh.prototype.isDisposed = function () {
  18930. return this._isDisposed;
  18931. };
  18932. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  18933. get: function () {
  18934. return this._sideOrientation;
  18935. },
  18936. /**
  18937. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  18938. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  18939. */
  18940. set: function (sideO) {
  18941. this._sideOrientation = sideO;
  18942. },
  18943. enumerable: true,
  18944. configurable: true
  18945. });
  18946. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  18947. /**
  18948. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  18949. * This property is pertinent only for updatable parametric shapes.
  18950. */
  18951. get: function () {
  18952. return this._areNormalsFrozen;
  18953. },
  18954. enumerable: true,
  18955. configurable: true
  18956. });
  18957. /**
  18958. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18959. * It has no effect at all on other shapes.
  18960. * It prevents the mesh normals from being recomputed on next `positions` array update.
  18961. * Returns the Mesh.
  18962. */
  18963. Mesh.prototype.freezeNormals = function () {
  18964. this._areNormalsFrozen = true;
  18965. return this;
  18966. };
  18967. /**
  18968. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18969. * It has no effect at all on other shapes.
  18970. * It reactivates the mesh normals computation if it was previously frozen.
  18971. * Returns the Mesh.
  18972. */
  18973. Mesh.prototype.unfreezeNormals = function () {
  18974. this._areNormalsFrozen = false;
  18975. return this;
  18976. };
  18977. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  18978. /**
  18979. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  18980. */
  18981. set: function (count) {
  18982. this._overridenInstanceCount = count;
  18983. },
  18984. enumerable: true,
  18985. configurable: true
  18986. });
  18987. // Methods
  18988. Mesh.prototype._preActivate = function () {
  18989. var sceneRenderId = this.getScene().getRenderId();
  18990. if (this._preActivateId === sceneRenderId) {
  18991. return this;
  18992. }
  18993. this._preActivateId = sceneRenderId;
  18994. this._visibleInstances = null;
  18995. return this;
  18996. };
  18997. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18998. if (this._visibleInstances) {
  18999. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19000. }
  19001. return this;
  19002. };
  19003. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19004. if (!this._visibleInstances) {
  19005. this._visibleInstances = {};
  19006. this._visibleInstances.defaultRenderId = renderId;
  19007. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19008. }
  19009. if (!this._visibleInstances[renderId]) {
  19010. this._visibleInstances[renderId] = new Array();
  19011. }
  19012. this._visibleInstances[renderId].push(instance);
  19013. return this;
  19014. };
  19015. /**
  19016. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19017. * This means the mesh underlying bounding box and sphere are recomputed.
  19018. * Returns the Mesh.
  19019. */
  19020. Mesh.prototype.refreshBoundingInfo = function () {
  19021. if (this._boundingInfo.isLocked) {
  19022. return;
  19023. }
  19024. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19025. if (data) {
  19026. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19027. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19028. }
  19029. if (this.subMeshes) {
  19030. for (var index = 0; index < this.subMeshes.length; index++) {
  19031. this.subMeshes[index].refreshBoundingInfo();
  19032. }
  19033. }
  19034. this._updateBoundingInfo();
  19035. return this;
  19036. };
  19037. Mesh.prototype._createGlobalSubMesh = function () {
  19038. var totalVertices = this.getTotalVertices();
  19039. if (!totalVertices || !this.getIndices()) {
  19040. return null;
  19041. }
  19042. this.releaseSubMeshes();
  19043. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19044. };
  19045. Mesh.prototype.subdivide = function (count) {
  19046. if (count < 1) {
  19047. return;
  19048. }
  19049. var totalIndices = this.getTotalIndices();
  19050. var subdivisionSize = (totalIndices / count) | 0;
  19051. var offset = 0;
  19052. // Ensure that subdivisionSize is a multiple of 3
  19053. while (subdivisionSize % 3 !== 0) {
  19054. subdivisionSize++;
  19055. }
  19056. this.releaseSubMeshes();
  19057. for (var index = 0; index < count; index++) {
  19058. if (offset >= totalIndices) {
  19059. break;
  19060. }
  19061. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19062. offset += subdivisionSize;
  19063. }
  19064. this.synchronizeInstances();
  19065. };
  19066. /**
  19067. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19068. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19069. * The `data` are either a numeric array either a Float32Array.
  19070. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19071. * 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).
  19072. * Note that a new underlying VertexBuffer object is created each call.
  19073. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19074. *
  19075. * Possible `kind` values :
  19076. * - BABYLON.VertexBuffer.PositionKind
  19077. * - BABYLON.VertexBuffer.UVKind
  19078. * - BABYLON.VertexBuffer.UV2Kind
  19079. * - BABYLON.VertexBuffer.UV3Kind
  19080. * - BABYLON.VertexBuffer.UV4Kind
  19081. * - BABYLON.VertexBuffer.UV5Kind
  19082. * - BABYLON.VertexBuffer.UV6Kind
  19083. * - BABYLON.VertexBuffer.ColorKind
  19084. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19085. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19086. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19087. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19088. *
  19089. * Returns the Mesh.
  19090. */
  19091. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19092. if (!this._geometry) {
  19093. var vertexData = new BABYLON.VertexData();
  19094. vertexData.set(data, kind);
  19095. var scene = this.getScene();
  19096. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19097. }
  19098. else {
  19099. this._geometry.setVerticesData(kind, data, updatable, stride);
  19100. }
  19101. return this;
  19102. };
  19103. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  19104. if (updatable === void 0) { updatable = true; }
  19105. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  19106. return;
  19107. }
  19108. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  19109. };
  19110. /**
  19111. * Sets the mesh VertexBuffer.
  19112. * Returns the Mesh.
  19113. */
  19114. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19115. if (!this._geometry) {
  19116. var scene = this.getScene();
  19117. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19118. }
  19119. this._geometry.setVerticesBuffer(buffer);
  19120. return this;
  19121. };
  19122. /**
  19123. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19124. * If the mesh has no geometry, it is simply returned as it is.
  19125. * The `data` are either a numeric array either a Float32Array.
  19126. * No new underlying VertexBuffer object is created.
  19127. * 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.
  19128. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19129. *
  19130. * Possible `kind` values :
  19131. * - BABYLON.VertexBuffer.PositionKind
  19132. * - BABYLON.VertexBuffer.UVKind
  19133. * - BABYLON.VertexBuffer.UV2Kind
  19134. * - BABYLON.VertexBuffer.UV3Kind
  19135. * - BABYLON.VertexBuffer.UV4Kind
  19136. * - BABYLON.VertexBuffer.UV5Kind
  19137. * - BABYLON.VertexBuffer.UV6Kind
  19138. * - BABYLON.VertexBuffer.ColorKind
  19139. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19140. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19141. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19142. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19143. *
  19144. * Returns the Mesh.
  19145. */
  19146. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19147. if (!this._geometry) {
  19148. return;
  19149. }
  19150. if (!makeItUnique) {
  19151. this._geometry.updateVerticesData(kind, data, updateExtends);
  19152. }
  19153. else {
  19154. this.makeGeometryUnique();
  19155. this.updateVerticesData(kind, data, updateExtends, false);
  19156. }
  19157. return this;
  19158. };
  19159. /**
  19160. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19161. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19162. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19163. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19164. * Returns the Mesh.
  19165. */
  19166. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19167. if (computeNormals === void 0) { computeNormals = true; }
  19168. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19169. positionFunction(positions);
  19170. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19171. if (computeNormals) {
  19172. var indices = this.getIndices();
  19173. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19174. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19175. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19176. }
  19177. return this;
  19178. };
  19179. /**
  19180. * Creates a un-shared specific occurence of the geometry for the mesh.
  19181. * Returns the Mesh.
  19182. */
  19183. Mesh.prototype.makeGeometryUnique = function () {
  19184. if (!this._geometry) {
  19185. return;
  19186. }
  19187. var oldGeometry = this._geometry;
  19188. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19189. oldGeometry.releaseForMesh(this, true);
  19190. geometry.applyToMesh(this);
  19191. return this;
  19192. };
  19193. /**
  19194. * Sets the mesh indices.
  19195. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19196. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19197. * This method creates a new index buffer each call.
  19198. * Returns the Mesh.
  19199. */
  19200. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19201. if (!this._geometry) {
  19202. var vertexData = new BABYLON.VertexData();
  19203. vertexData.indices = indices;
  19204. var scene = this.getScene();
  19205. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19206. }
  19207. else {
  19208. this._geometry.setIndices(indices, totalVertices);
  19209. }
  19210. return this;
  19211. };
  19212. /**
  19213. * Invert the geometry to move from a right handed system to a left handed one.
  19214. * Returns the Mesh.
  19215. */
  19216. Mesh.prototype.toLeftHanded = function () {
  19217. if (!this._geometry) {
  19218. return;
  19219. }
  19220. this._geometry.toLeftHanded();
  19221. return this;
  19222. };
  19223. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19224. var engine = this.getScene().getEngine();
  19225. // Wireframe
  19226. var indexToBind;
  19227. if (this._unIndexed) {
  19228. indexToBind = null;
  19229. }
  19230. else {
  19231. switch (fillMode) {
  19232. case BABYLON.Material.PointFillMode:
  19233. indexToBind = null;
  19234. break;
  19235. case BABYLON.Material.WireFrameFillMode:
  19236. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19237. break;
  19238. default:
  19239. case BABYLON.Material.TriangleFillMode:
  19240. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19241. break;
  19242. }
  19243. }
  19244. // VBOs
  19245. this._geometry._bind(effect, indexToBind);
  19246. return this;
  19247. };
  19248. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19249. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19250. return this;
  19251. }
  19252. this.onBeforeDrawObservable.notifyObservers(this);
  19253. var engine = this.getScene().getEngine();
  19254. // Draw order
  19255. switch (fillMode) {
  19256. case BABYLON.Material.PointFillMode:
  19257. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19258. break;
  19259. case BABYLON.Material.WireFrameFillMode:
  19260. if (this._unIndexed) {
  19261. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19262. }
  19263. else {
  19264. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19265. }
  19266. break;
  19267. default:
  19268. if (this._unIndexed) {
  19269. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19270. }
  19271. else {
  19272. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19273. }
  19274. }
  19275. return this;
  19276. };
  19277. /**
  19278. * Registers for this mesh a javascript function called just before the rendering process.
  19279. * This function is passed the current mesh.
  19280. * Return the Mesh.
  19281. */
  19282. Mesh.prototype.registerBeforeRender = function (func) {
  19283. this.onBeforeRenderObservable.add(func);
  19284. return this;
  19285. };
  19286. /**
  19287. * Disposes a previously registered javascript function called before the rendering.
  19288. * This function is passed the current mesh.
  19289. * Returns the Mesh.
  19290. */
  19291. Mesh.prototype.unregisterBeforeRender = function (func) {
  19292. this.onBeforeRenderObservable.removeCallback(func);
  19293. return this;
  19294. };
  19295. /**
  19296. * Registers for this mesh a javascript function called just after the rendering is complete.
  19297. * This function is passed the current mesh.
  19298. * Returns the Mesh.
  19299. */
  19300. Mesh.prototype.registerAfterRender = function (func) {
  19301. this.onAfterRenderObservable.add(func);
  19302. return this;
  19303. };
  19304. /**
  19305. * Disposes a previously registered javascript function called after the rendering.
  19306. * This function is passed the current mesh.
  19307. * Return the Mesh.
  19308. */
  19309. Mesh.prototype.unregisterAfterRender = function (func) {
  19310. this.onAfterRenderObservable.removeCallback(func);
  19311. return this;
  19312. };
  19313. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19314. var scene = this.getScene();
  19315. this._batchCache.mustReturn = false;
  19316. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19317. this._batchCache.visibleInstances[subMeshId] = null;
  19318. if (this._visibleInstances) {
  19319. var currentRenderId = scene.getRenderId();
  19320. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19321. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19322. var selfRenderId = this._renderId;
  19323. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19324. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19325. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19326. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19327. }
  19328. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19329. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19330. this._batchCache.mustReturn = true;
  19331. return this._batchCache;
  19332. }
  19333. if (currentRenderId !== selfRenderId) {
  19334. this._batchCache.renderSelf[subMeshId] = false;
  19335. }
  19336. }
  19337. this._renderIdForInstances[subMeshId] = currentRenderId;
  19338. }
  19339. return this._batchCache;
  19340. };
  19341. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19342. var visibleInstances = batch.visibleInstances[subMesh._id];
  19343. var matricesCount = visibleInstances.length + 1;
  19344. var bufferSize = matricesCount * 16 * 4;
  19345. var currentInstancesBufferSize = this._instancesBufferSize;
  19346. var instancesBuffer = this._instancesBuffer;
  19347. while (this._instancesBufferSize < bufferSize) {
  19348. this._instancesBufferSize *= 2;
  19349. }
  19350. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19351. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19352. }
  19353. var offset = 0;
  19354. var instancesCount = 0;
  19355. var world = this.getWorldMatrix();
  19356. if (batch.renderSelf[subMesh._id]) {
  19357. world.copyToArray(this._instancesData, offset);
  19358. offset += 16;
  19359. instancesCount++;
  19360. }
  19361. if (visibleInstances) {
  19362. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19363. var instance = visibleInstances[instanceIndex];
  19364. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19365. offset += 16;
  19366. instancesCount++;
  19367. }
  19368. }
  19369. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19370. if (instancesBuffer) {
  19371. instancesBuffer.dispose();
  19372. }
  19373. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19374. this._instancesBuffer = instancesBuffer;
  19375. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19376. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19377. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19378. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19379. }
  19380. else {
  19381. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19382. }
  19383. this.geometry._bind(effect);
  19384. this._draw(subMesh, fillMode, instancesCount);
  19385. engine.unbindInstanceAttributes();
  19386. return this;
  19387. };
  19388. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19389. var scene = this.getScene();
  19390. var engine = scene.getEngine();
  19391. if (hardwareInstancedRendering) {
  19392. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19393. }
  19394. else {
  19395. if (batch.renderSelf[subMesh._id]) {
  19396. // Draw
  19397. if (onBeforeDraw) {
  19398. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19399. }
  19400. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19401. }
  19402. if (batch.visibleInstances[subMesh._id]) {
  19403. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19404. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19405. // World
  19406. var world = instance.getWorldMatrix();
  19407. if (onBeforeDraw) {
  19408. onBeforeDraw(true, world, effectiveMaterial);
  19409. }
  19410. // Draw
  19411. this._draw(subMesh, fillMode);
  19412. }
  19413. }
  19414. }
  19415. return this;
  19416. };
  19417. /**
  19418. * Triggers the draw call for the mesh.
  19419. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19420. * Returns the Mesh.
  19421. */
  19422. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19423. var scene = this.getScene();
  19424. // Managing instances
  19425. var batch = this._getInstancesRenderList(subMesh._id);
  19426. if (batch.mustReturn) {
  19427. return this;
  19428. }
  19429. // Checking geometry state
  19430. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19431. return this;
  19432. }
  19433. var callbackIndex;
  19434. this.onBeforeRenderObservable.notifyObservers(this);
  19435. var engine = scene.getEngine();
  19436. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19437. // Material
  19438. var effectiveMaterial = subMesh.getMaterial();
  19439. if (!effectiveMaterial) {
  19440. return this;
  19441. }
  19442. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19443. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  19444. return this;
  19445. }
  19446. }
  19447. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19448. return this;
  19449. }
  19450. // Outline - step 1
  19451. var savedDepthWrite = engine.getDepthWrite();
  19452. if (this.renderOutline) {
  19453. engine.setDepthWrite(false);
  19454. scene.getOutlineRenderer().render(subMesh, batch);
  19455. engine.setDepthWrite(savedDepthWrite);
  19456. }
  19457. var effect;
  19458. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19459. effect = subMesh.effect;
  19460. }
  19461. else {
  19462. effect = effectiveMaterial.getEffect();
  19463. }
  19464. effectiveMaterial._preBind(effect);
  19465. // Bind
  19466. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19467. this._bind(subMesh, effect, fillMode);
  19468. var world = this.getWorldMatrix();
  19469. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19470. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  19471. }
  19472. else {
  19473. effectiveMaterial.bind(world, this);
  19474. }
  19475. // Alpha mode
  19476. if (enableAlphaMode) {
  19477. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19478. }
  19479. // Draw
  19480. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  19481. // Unbind
  19482. effectiveMaterial.unbind();
  19483. // Outline - step 2
  19484. if (this.renderOutline && savedDepthWrite) {
  19485. engine.setDepthWrite(true);
  19486. engine.setColorWrite(false);
  19487. scene.getOutlineRenderer().render(subMesh, batch);
  19488. engine.setColorWrite(true);
  19489. }
  19490. // Overlay
  19491. if (this.renderOverlay) {
  19492. var currentMode = engine.getAlphaMode();
  19493. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19494. scene.getOutlineRenderer().render(subMesh, batch, true);
  19495. engine.setAlphaMode(currentMode);
  19496. }
  19497. this.onAfterRenderObservable.notifyObservers(this);
  19498. return this;
  19499. };
  19500. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19501. if (isInstance) {
  19502. effectiveMaterial.bindOnlyWorldMatrix(world);
  19503. }
  19504. return this;
  19505. };
  19506. /**
  19507. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19508. */
  19509. Mesh.prototype.getEmittedParticleSystems = function () {
  19510. var results = new Array();
  19511. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19512. var particleSystem = this.getScene().particleSystems[index];
  19513. if (particleSystem.emitter === this) {
  19514. results.push(particleSystem);
  19515. }
  19516. }
  19517. return results;
  19518. };
  19519. /**
  19520. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19521. */
  19522. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19523. var results = new Array();
  19524. var descendants = this.getDescendants();
  19525. descendants.push(this);
  19526. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19527. var particleSystem = this.getScene().particleSystems[index];
  19528. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19529. results.push(particleSystem);
  19530. }
  19531. }
  19532. return results;
  19533. };
  19534. Mesh.prototype._checkDelayState = function () {
  19535. var scene = this.getScene();
  19536. if (this._geometry) {
  19537. this._geometry.load(scene);
  19538. }
  19539. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19540. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19541. this._queueLoad(this, scene);
  19542. }
  19543. return this;
  19544. };
  19545. Mesh.prototype._queueLoad = function (mesh, scene) {
  19546. var _this = this;
  19547. scene._addPendingData(mesh);
  19548. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19549. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19550. if (data instanceof ArrayBuffer) {
  19551. _this._delayLoadingFunction(data, _this);
  19552. }
  19553. else {
  19554. _this._delayLoadingFunction(JSON.parse(data), _this);
  19555. }
  19556. _this.instances.forEach(function (instance) {
  19557. instance._syncSubMeshes();
  19558. });
  19559. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19560. scene._removePendingData(_this);
  19561. }, function () { }, scene.database, getBinaryData);
  19562. return this;
  19563. };
  19564. /**
  19565. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19566. */
  19567. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  19568. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19569. return false;
  19570. }
  19571. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  19572. return false;
  19573. }
  19574. this._checkDelayState();
  19575. return true;
  19576. };
  19577. /**
  19578. * Sets the mesh material by the material or multiMaterial `id` property.
  19579. * The material `id` is a string identifying the material or the multiMaterial.
  19580. * This method returns the Mesh.
  19581. */
  19582. Mesh.prototype.setMaterialByID = function (id) {
  19583. var materials = this.getScene().materials;
  19584. var index;
  19585. for (index = 0; index < materials.length; index++) {
  19586. if (materials[index].id === id) {
  19587. this.material = materials[index];
  19588. return this;
  19589. }
  19590. }
  19591. // Multi
  19592. var multiMaterials = this.getScene().multiMaterials;
  19593. for (index = 0; index < multiMaterials.length; index++) {
  19594. if (multiMaterials[index].id === id) {
  19595. this.material = multiMaterials[index];
  19596. return this;
  19597. }
  19598. }
  19599. return this;
  19600. };
  19601. /**
  19602. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  19603. */
  19604. Mesh.prototype.getAnimatables = function () {
  19605. var results = [];
  19606. if (this.material) {
  19607. results.push(this.material);
  19608. }
  19609. if (this.skeleton) {
  19610. results.push(this.skeleton);
  19611. }
  19612. return results;
  19613. };
  19614. /**
  19615. * Modifies the mesh geometry according to the passed transformation matrix.
  19616. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  19617. * The mesh normals are modified accordingly the same transformation.
  19618. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19619. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19620. * Returns the Mesh.
  19621. */
  19622. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  19623. // Position
  19624. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19625. return this;
  19626. }
  19627. var submeshes = this.subMeshes.splice(0);
  19628. this._resetPointsArrayCache();
  19629. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19630. var temp = [];
  19631. var index;
  19632. for (index = 0; index < data.length; index += 3) {
  19633. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  19634. }
  19635. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  19636. // Normals
  19637. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19638. return this;
  19639. }
  19640. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19641. temp = [];
  19642. for (index = 0; index < data.length; index += 3) {
  19643. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  19644. }
  19645. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  19646. // flip faces?
  19647. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  19648. this.flipFaces();
  19649. }
  19650. // Restore submeshes
  19651. this.releaseSubMeshes();
  19652. this.subMeshes = submeshes;
  19653. return this;
  19654. };
  19655. /**
  19656. * Modifies the mesh geometry according to its own current World Matrix.
  19657. * The mesh World Matrix is then reset.
  19658. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  19659. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19660. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19661. * Returns the Mesh.
  19662. */
  19663. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  19664. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  19665. this.scaling.copyFromFloats(1, 1, 1);
  19666. this.position.copyFromFloats(0, 0, 0);
  19667. this.rotation.copyFromFloats(0, 0, 0);
  19668. //only if quaternion is already set
  19669. if (this.rotationQuaternion) {
  19670. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  19671. }
  19672. this._worldMatrix = BABYLON.Matrix.Identity();
  19673. return this;
  19674. };
  19675. // Cache
  19676. Mesh.prototype._resetPointsArrayCache = function () {
  19677. this._positions = null;
  19678. return this;
  19679. };
  19680. Mesh.prototype._generatePointsArray = function () {
  19681. if (this._positions)
  19682. return true;
  19683. this._positions = [];
  19684. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19685. if (!data) {
  19686. return false;
  19687. }
  19688. for (var index = 0; index < data.length; index += 3) {
  19689. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  19690. }
  19691. return true;
  19692. };
  19693. /**
  19694. * Returns a new Mesh object generated from the current mesh properties.
  19695. * This method must not get confused with createInstance().
  19696. * The parameter `name` is a string, the name given to the new mesh.
  19697. * The optional parameter `newParent` can be any Node object (default `null`).
  19698. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  19699. * 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.
  19700. */
  19701. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  19702. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19703. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  19704. };
  19705. /**
  19706. * Disposes the mesh.
  19707. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  19708. */
  19709. Mesh.prototype.dispose = function (doNotRecurse) {
  19710. var _this = this;
  19711. this.morphTargetManager = undefined;
  19712. if (this._geometry) {
  19713. this._geometry.releaseForMesh(this, true);
  19714. }
  19715. // Sources
  19716. var meshes = this.getScene().meshes;
  19717. meshes.forEach(function (mesh) {
  19718. if (mesh._source && mesh._source === _this) {
  19719. mesh._source = null;
  19720. }
  19721. });
  19722. this._source = null;
  19723. // Instances
  19724. if (this._instancesBuffer) {
  19725. this._instancesBuffer.dispose();
  19726. this._instancesBuffer = null;
  19727. }
  19728. while (this.instances.length) {
  19729. this.instances[0].dispose();
  19730. }
  19731. // Highlight layers.
  19732. var highlightLayers = this.getScene().highlightLayers;
  19733. for (var i = 0; i < highlightLayers.length; i++) {
  19734. var highlightLayer = highlightLayers[i];
  19735. if (highlightLayer) {
  19736. highlightLayer.removeMesh(this);
  19737. highlightLayer.removeExcludedMesh(this);
  19738. }
  19739. }
  19740. _super.prototype.dispose.call(this, doNotRecurse);
  19741. };
  19742. /**
  19743. * Modifies the mesh geometry according to a displacement map.
  19744. * 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.
  19745. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19746. * This method returns nothing.
  19747. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19748. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19749. * 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.
  19750. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  19751. * The parameter `uvScale` is an optional vector2 used to scale UV.
  19752. *
  19753. * Returns the Mesh.
  19754. */
  19755. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  19756. var _this = this;
  19757. var scene = this.getScene();
  19758. var onload = function (img) {
  19759. // Getting height map data
  19760. var canvas = document.createElement("canvas");
  19761. var context = canvas.getContext("2d");
  19762. var heightMapWidth = img.width;
  19763. var heightMapHeight = img.height;
  19764. canvas.width = heightMapWidth;
  19765. canvas.height = heightMapHeight;
  19766. context.drawImage(img, 0, 0);
  19767. // Create VertexData from map data
  19768. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19769. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19770. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  19771. //execute success callback, if set
  19772. if (onSuccess) {
  19773. onSuccess(_this);
  19774. }
  19775. };
  19776. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19777. return this;
  19778. };
  19779. /**
  19780. * Modifies the mesh geometry according to a displacementMap buffer.
  19781. * 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.
  19782. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19783. * This method returns nothing.
  19784. * 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.
  19785. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19786. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19787. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  19788. * The parameter `uvScale` is an optional vector2 used to scale UV.
  19789. *
  19790. * Returns the Mesh.
  19791. */
  19792. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  19793. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19794. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19795. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19796. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19797. return this;
  19798. }
  19799. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19800. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19801. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19802. var position = BABYLON.Vector3.Zero();
  19803. var normal = BABYLON.Vector3.Zero();
  19804. var uv = BABYLON.Vector2.Zero();
  19805. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  19806. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  19807. for (var index = 0; index < positions.length; index += 3) {
  19808. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19809. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19810. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19811. // Compute height
  19812. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  19813. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  19814. var pos = (u + v * heightMapWidth) * 4;
  19815. var r = buffer[pos] / 255.0;
  19816. var g = buffer[pos + 1] / 255.0;
  19817. var b = buffer[pos + 2] / 255.0;
  19818. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19819. normal.normalize();
  19820. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19821. position = position.add(normal);
  19822. position.toArray(positions, index);
  19823. }
  19824. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  19825. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  19826. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19827. return this;
  19828. };
  19829. /**
  19830. * Modify the mesh to get a flat shading rendering.
  19831. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  19832. * This method returns the Mesh.
  19833. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  19834. */
  19835. Mesh.prototype.convertToFlatShadedMesh = function () {
  19836. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  19837. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19838. var kinds = this.getVerticesDataKinds();
  19839. var vbs = [];
  19840. var data = [];
  19841. var newdata = [];
  19842. var updatableNormals = false;
  19843. var kindIndex;
  19844. var kind;
  19845. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19846. kind = kinds[kindIndex];
  19847. var vertexBuffer = this.getVertexBuffer(kind);
  19848. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19849. updatableNormals = vertexBuffer.isUpdatable();
  19850. kinds.splice(kindIndex, 1);
  19851. kindIndex--;
  19852. continue;
  19853. }
  19854. vbs[kind] = vertexBuffer;
  19855. data[kind] = vbs[kind].getData();
  19856. newdata[kind] = [];
  19857. }
  19858. // Save previous submeshes
  19859. var previousSubmeshes = this.subMeshes.slice(0);
  19860. var indices = this.getIndices();
  19861. var totalIndices = this.getTotalIndices();
  19862. // Generating unique vertices per face
  19863. var index;
  19864. for (index = 0; index < totalIndices; index++) {
  19865. var vertexIndex = indices[index];
  19866. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19867. kind = kinds[kindIndex];
  19868. var stride = vbs[kind].getStrideSize();
  19869. for (var offset = 0; offset < stride; offset++) {
  19870. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19871. }
  19872. }
  19873. }
  19874. // Updating faces & normal
  19875. var normals = [];
  19876. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19877. for (index = 0; index < totalIndices; index += 3) {
  19878. indices[index] = index;
  19879. indices[index + 1] = index + 1;
  19880. indices[index + 2] = index + 2;
  19881. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19882. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19883. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19884. var p1p2 = p1.subtract(p2);
  19885. var p3p2 = p3.subtract(p2);
  19886. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19887. // Store same normals for every vertex
  19888. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19889. normals.push(normal.x);
  19890. normals.push(normal.y);
  19891. normals.push(normal.z);
  19892. }
  19893. }
  19894. this.setIndices(indices);
  19895. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19896. // Updating vertex buffers
  19897. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19898. kind = kinds[kindIndex];
  19899. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19900. }
  19901. // Updating submeshes
  19902. this.releaseSubMeshes();
  19903. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19904. var previousOne = previousSubmeshes[submeshIndex];
  19905. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19906. }
  19907. this.synchronizeInstances();
  19908. return this;
  19909. };
  19910. /**
  19911. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  19912. * In other words, more vertices, no more indices and a single bigger VBO.
  19913. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  19914. * Returns the Mesh.
  19915. */
  19916. Mesh.prototype.convertToUnIndexedMesh = function () {
  19917. /// <summary>Remove indices by unfolding faces into buffers</summary>
  19918. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19919. var kinds = this.getVerticesDataKinds();
  19920. var vbs = [];
  19921. var data = [];
  19922. var newdata = [];
  19923. var updatableNormals = false;
  19924. var kindIndex;
  19925. var kind;
  19926. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19927. kind = kinds[kindIndex];
  19928. var vertexBuffer = this.getVertexBuffer(kind);
  19929. vbs[kind] = vertexBuffer;
  19930. data[kind] = vbs[kind].getData();
  19931. newdata[kind] = [];
  19932. }
  19933. // Save previous submeshes
  19934. var previousSubmeshes = this.subMeshes.slice(0);
  19935. var indices = this.getIndices();
  19936. var totalIndices = this.getTotalIndices();
  19937. // Generating unique vertices per face
  19938. var index;
  19939. for (index = 0; index < totalIndices; index++) {
  19940. var vertexIndex = indices[index];
  19941. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19942. kind = kinds[kindIndex];
  19943. var stride = vbs[kind].getStrideSize();
  19944. for (var offset = 0; offset < stride; offset++) {
  19945. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19946. }
  19947. }
  19948. }
  19949. // Updating indices
  19950. for (index = 0; index < totalIndices; index += 3) {
  19951. indices[index] = index;
  19952. indices[index + 1] = index + 1;
  19953. indices[index + 2] = index + 2;
  19954. }
  19955. this.setIndices(indices);
  19956. // Updating vertex buffers
  19957. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19958. kind = kinds[kindIndex];
  19959. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19960. }
  19961. // Updating submeshes
  19962. this.releaseSubMeshes();
  19963. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19964. var previousOne = previousSubmeshes[submeshIndex];
  19965. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19966. }
  19967. this._unIndexed = true;
  19968. this.synchronizeInstances();
  19969. return this;
  19970. };
  19971. /**
  19972. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  19973. * This method returns the Mesh.
  19974. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  19975. */
  19976. Mesh.prototype.flipFaces = function (flipNormals) {
  19977. if (flipNormals === void 0) { flipNormals = false; }
  19978. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  19979. var i;
  19980. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19981. for (i = 0; i < vertex_data.normals.length; i++) {
  19982. vertex_data.normals[i] *= -1;
  19983. }
  19984. }
  19985. var temp;
  19986. for (i = 0; i < vertex_data.indices.length; i += 3) {
  19987. // reassign indices
  19988. temp = vertex_data.indices[i + 1];
  19989. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  19990. vertex_data.indices[i + 2] = temp;
  19991. }
  19992. vertex_data.applyToMesh(this);
  19993. return this;
  19994. };
  19995. // Instances
  19996. /**
  19997. * Creates a new InstancedMesh object from the mesh model.
  19998. * An instance shares the same properties and the same material than its model.
  19999. * Only these properties of each instance can then be set individually :
  20000. * - position
  20001. * - rotation
  20002. * - rotationQuaternion
  20003. * - setPivotMatrix
  20004. * - scaling
  20005. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20006. * Warning : this method is not supported for Line mesh and LineSystem
  20007. */
  20008. Mesh.prototype.createInstance = function (name) {
  20009. return new BABYLON.InstancedMesh(name, this);
  20010. };
  20011. /**
  20012. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20013. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20014. * This method returns the Mesh.
  20015. */
  20016. Mesh.prototype.synchronizeInstances = function () {
  20017. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20018. var instance = this.instances[instanceIndex];
  20019. instance._syncSubMeshes();
  20020. }
  20021. return this;
  20022. };
  20023. /**
  20024. * Simplify the mesh according to the given array of settings.
  20025. * Function will return immediately and will simplify async. It returns the Mesh.
  20026. * @param settings a collection of simplification settings.
  20027. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20028. * @param type the type of simplification to run.
  20029. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20030. */
  20031. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20032. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20033. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20034. this.getScene().simplificationQueue.addTask({
  20035. settings: settings,
  20036. parallelProcessing: parallelProcessing,
  20037. mesh: this,
  20038. simplificationType: simplificationType,
  20039. successCallback: successCallback
  20040. });
  20041. return this;
  20042. };
  20043. /**
  20044. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20045. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20046. * This should be used together with the simplification to avoid disappearing triangles.
  20047. * Returns the Mesh.
  20048. * @param successCallback an optional success callback to be called after the optimization finished.
  20049. */
  20050. Mesh.prototype.optimizeIndices = function (successCallback) {
  20051. var _this = this;
  20052. var indices = this.getIndices();
  20053. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20054. var vectorPositions = [];
  20055. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20056. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20057. }
  20058. var dupes = [];
  20059. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20060. var realPos = vectorPositions.length - 1 - iteration;
  20061. var testedPosition = vectorPositions[realPos];
  20062. for (var j = 0; j < realPos; ++j) {
  20063. var againstPosition = vectorPositions[j];
  20064. if (testedPosition.equals(againstPosition)) {
  20065. dupes[realPos] = j;
  20066. break;
  20067. }
  20068. }
  20069. }, function () {
  20070. for (var i = 0; i < indices.length; ++i) {
  20071. indices[i] = dupes[indices[i]] || indices[i];
  20072. }
  20073. //indices are now reordered
  20074. var originalSubMeshes = _this.subMeshes.slice(0);
  20075. _this.setIndices(indices);
  20076. _this.subMeshes = originalSubMeshes;
  20077. if (successCallback) {
  20078. successCallback(_this);
  20079. }
  20080. });
  20081. return this;
  20082. };
  20083. Mesh.prototype.serialize = function (serializationObject) {
  20084. serializationObject.name = this.name;
  20085. serializationObject.id = this.id;
  20086. serializationObject.type = this.getClassName();
  20087. if (BABYLON.Tags.HasTags(this)) {
  20088. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20089. }
  20090. serializationObject.position = this.position.asArray();
  20091. if (this.rotationQuaternion) {
  20092. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  20093. }
  20094. else if (this.rotation) {
  20095. serializationObject.rotation = this.rotation.asArray();
  20096. }
  20097. serializationObject.scaling = this.scaling.asArray();
  20098. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20099. serializationObject.isEnabled = this.isEnabled();
  20100. serializationObject.isVisible = this.isVisible;
  20101. serializationObject.infiniteDistance = this.infiniteDistance;
  20102. serializationObject.pickable = this.isPickable;
  20103. serializationObject.receiveShadows = this.receiveShadows;
  20104. serializationObject.billboardMode = this.billboardMode;
  20105. serializationObject.visibility = this.visibility;
  20106. serializationObject.checkCollisions = this.checkCollisions;
  20107. serializationObject.isBlocker = this.isBlocker;
  20108. // Parent
  20109. if (this.parent) {
  20110. serializationObject.parentId = this.parent.id;
  20111. }
  20112. // Geometry
  20113. var geometry = this._geometry;
  20114. if (geometry) {
  20115. var geometryId = geometry.id;
  20116. serializationObject.geometryId = geometryId;
  20117. // SubMeshes
  20118. serializationObject.subMeshes = [];
  20119. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20120. var subMesh = this.subMeshes[subIndex];
  20121. serializationObject.subMeshes.push({
  20122. materialIndex: subMesh.materialIndex,
  20123. verticesStart: subMesh.verticesStart,
  20124. verticesCount: subMesh.verticesCount,
  20125. indexStart: subMesh.indexStart,
  20126. indexCount: subMesh.indexCount
  20127. });
  20128. }
  20129. }
  20130. // Material
  20131. if (this.material) {
  20132. serializationObject.materialId = this.material.id;
  20133. }
  20134. else {
  20135. this.material = null;
  20136. }
  20137. // Morph targets
  20138. if (this.morphTargetManager) {
  20139. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  20140. }
  20141. // Skeleton
  20142. if (this.skeleton) {
  20143. serializationObject.skeletonId = this.skeleton.id;
  20144. }
  20145. // Physics
  20146. //TODO implement correct serialization for physics impostors.
  20147. if (this.getPhysicsImpostor()) {
  20148. var impostor = this.getPhysicsImpostor();
  20149. serializationObject.physicsMass = impostor.getParam("mass");
  20150. serializationObject.physicsFriction = impostor.getParam("friction");
  20151. serializationObject.physicsRestitution = impostor.getParam("mass");
  20152. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  20153. }
  20154. // Metadata
  20155. if (this.metadata) {
  20156. serializationObject.metadata = this.metadata;
  20157. }
  20158. // Instances
  20159. serializationObject.instances = [];
  20160. for (var index = 0; index < this.instances.length; index++) {
  20161. var instance = this.instances[index];
  20162. var serializationInstance = {
  20163. name: instance.name,
  20164. position: instance.position.asArray(),
  20165. scaling: instance.scaling.asArray()
  20166. };
  20167. if (instance.rotationQuaternion) {
  20168. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  20169. }
  20170. else if (instance.rotation) {
  20171. serializationInstance.rotation = instance.rotation.asArray();
  20172. }
  20173. serializationObject.instances.push(serializationInstance);
  20174. // Animations
  20175. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  20176. serializationInstance.ranges = instance.serializeAnimationRanges();
  20177. }
  20178. //
  20179. // Animations
  20180. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20181. serializationObject.ranges = this.serializeAnimationRanges();
  20182. // Layer mask
  20183. serializationObject.layerMask = this.layerMask;
  20184. // Alpha
  20185. serializationObject.alphaIndex = this.alphaIndex;
  20186. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  20187. // Overlay
  20188. serializationObject.overlayAlpha = this.overlayAlpha;
  20189. serializationObject.overlayColor = this.overlayColor.asArray();
  20190. serializationObject.renderOverlay = this.renderOverlay;
  20191. // Fog
  20192. serializationObject.applyFog = this.applyFog;
  20193. // Action Manager
  20194. if (this.actionManager) {
  20195. serializationObject.actions = this.actionManager.serialize(this.name);
  20196. }
  20197. };
  20198. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  20199. if (!this.geometry) {
  20200. return;
  20201. }
  20202. this._markSubMeshesAsAttributesDirty();
  20203. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  20204. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  20205. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  20206. this.morphTargetManager = undefined;
  20207. return;
  20208. }
  20209. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  20210. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  20211. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  20212. if (morphTarget.hasNormals) {
  20213. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  20214. }
  20215. if (morphTarget.hasTangents) {
  20216. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  20217. }
  20218. }
  20219. }
  20220. else {
  20221. var index = 0;
  20222. // Positions
  20223. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  20224. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  20225. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  20226. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  20227. }
  20228. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  20229. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  20230. }
  20231. index++;
  20232. }
  20233. }
  20234. };
  20235. // Statics
  20236. /**
  20237. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20238. * The parameter `parsedMesh` is the mesh to be copied.
  20239. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20240. */
  20241. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20242. var mesh;
  20243. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  20244. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  20245. }
  20246. else {
  20247. mesh = new Mesh(parsedMesh.name, scene);
  20248. }
  20249. mesh.id = parsedMesh.id;
  20250. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20251. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20252. if (parsedMesh.metadata !== undefined) {
  20253. mesh.metadata = parsedMesh.metadata;
  20254. }
  20255. if (parsedMesh.rotationQuaternion) {
  20256. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20257. }
  20258. else if (parsedMesh.rotation) {
  20259. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20260. }
  20261. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20262. if (parsedMesh.localMatrix) {
  20263. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20264. }
  20265. else if (parsedMesh.pivotMatrix) {
  20266. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20267. }
  20268. mesh.setEnabled(parsedMesh.isEnabled);
  20269. mesh.isVisible = parsedMesh.isVisible;
  20270. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20271. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20272. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20273. if (parsedMesh.applyFog !== undefined) {
  20274. mesh.applyFog = parsedMesh.applyFog;
  20275. }
  20276. if (parsedMesh.pickable !== undefined) {
  20277. mesh.isPickable = parsedMesh.pickable;
  20278. }
  20279. if (parsedMesh.alphaIndex !== undefined) {
  20280. mesh.alphaIndex = parsedMesh.alphaIndex;
  20281. }
  20282. mesh.receiveShadows = parsedMesh.receiveShadows;
  20283. mesh.billboardMode = parsedMesh.billboardMode;
  20284. if (parsedMesh.visibility !== undefined) {
  20285. mesh.visibility = parsedMesh.visibility;
  20286. }
  20287. mesh.checkCollisions = parsedMesh.checkCollisions;
  20288. if (parsedMesh.isBlocker !== undefined) {
  20289. mesh.isBlocker = parsedMesh.isBlocker;
  20290. }
  20291. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20292. // freezeWorldMatrix
  20293. if (parsedMesh.freezeWorldMatrix) {
  20294. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20295. }
  20296. // Parent
  20297. if (parsedMesh.parentId) {
  20298. mesh._waitingParentId = parsedMesh.parentId;
  20299. }
  20300. // Actions
  20301. if (parsedMesh.actions !== undefined) {
  20302. mesh._waitingActions = parsedMesh.actions;
  20303. }
  20304. // Overlay
  20305. if (parsedMesh.overlayAlpha !== undefined) {
  20306. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  20307. }
  20308. if (parsedMesh.overlayColor !== undefined) {
  20309. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  20310. }
  20311. if (parsedMesh.renderOverlay !== undefined) {
  20312. mesh.renderOverlay = parsedMesh.renderOverlay;
  20313. }
  20314. // Geometry
  20315. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20316. if (parsedMesh.delayLoadingFile) {
  20317. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20318. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20319. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20320. if (parsedMesh._binaryInfo) {
  20321. mesh._binaryInfo = parsedMesh._binaryInfo;
  20322. }
  20323. mesh._delayInfo = [];
  20324. if (parsedMesh.hasUVs) {
  20325. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20326. }
  20327. if (parsedMesh.hasUVs2) {
  20328. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20329. }
  20330. if (parsedMesh.hasUVs3) {
  20331. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20332. }
  20333. if (parsedMesh.hasUVs4) {
  20334. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20335. }
  20336. if (parsedMesh.hasUVs5) {
  20337. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20338. }
  20339. if (parsedMesh.hasUVs6) {
  20340. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20341. }
  20342. if (parsedMesh.hasColors) {
  20343. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20344. }
  20345. if (parsedMesh.hasMatricesIndices) {
  20346. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20347. }
  20348. if (parsedMesh.hasMatricesWeights) {
  20349. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20350. }
  20351. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20352. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20353. mesh._checkDelayState();
  20354. }
  20355. }
  20356. else {
  20357. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20358. }
  20359. // Material
  20360. if (parsedMesh.materialId) {
  20361. mesh.setMaterialByID(parsedMesh.materialId);
  20362. }
  20363. else {
  20364. mesh.material = null;
  20365. }
  20366. // Morph targets
  20367. if (parsedMesh.morphTargetManagerId > -1) {
  20368. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  20369. }
  20370. // Skeleton
  20371. if (parsedMesh.skeletonId > -1) {
  20372. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20373. if (parsedMesh.numBoneInfluencers) {
  20374. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20375. }
  20376. }
  20377. // Animations
  20378. if (parsedMesh.animations) {
  20379. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20380. var parsedAnimation = parsedMesh.animations[animationIndex];
  20381. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20382. }
  20383. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20384. }
  20385. if (parsedMesh.autoAnimate) {
  20386. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20387. }
  20388. // Layer Mask
  20389. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20390. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20391. }
  20392. else {
  20393. mesh.layerMask = 0x0FFFFFFF;
  20394. }
  20395. // Physics
  20396. if (parsedMesh.physicsImpostor) {
  20397. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20398. mass: parsedMesh.physicsMass,
  20399. friction: parsedMesh.physicsFriction,
  20400. restitution: parsedMesh.physicsRestitution
  20401. }, scene);
  20402. }
  20403. // Instances
  20404. if (parsedMesh.instances) {
  20405. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20406. var parsedInstance = parsedMesh.instances[index];
  20407. var instance = mesh.createInstance(parsedInstance.name);
  20408. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20409. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20410. if (parsedInstance.parentId) {
  20411. instance._waitingParentId = parsedInstance.parentId;
  20412. }
  20413. if (parsedInstance.rotationQuaternion) {
  20414. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20415. }
  20416. else if (parsedInstance.rotation) {
  20417. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20418. }
  20419. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20420. instance.checkCollisions = mesh.checkCollisions;
  20421. if (parsedMesh.animations) {
  20422. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20423. parsedAnimation = parsedMesh.animations[animationIndex];
  20424. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20425. }
  20426. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20427. }
  20428. }
  20429. }
  20430. return mesh;
  20431. };
  20432. /**
  20433. * Creates a ribbon mesh.
  20434. * Please consider using the same method from the MeshBuilder class instead.
  20435. * 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.
  20436. *
  20437. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20438. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20439. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20440. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20441. * 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.
  20442. * 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.
  20443. * 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
  20444. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20445. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20446. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20447. */
  20448. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20449. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20450. pathArray: pathArray,
  20451. closeArray: closeArray,
  20452. closePath: closePath,
  20453. offset: offset,
  20454. updatable: updatable,
  20455. sideOrientation: sideOrientation,
  20456. instance: instance
  20457. }, scene);
  20458. };
  20459. /**
  20460. * Creates a plane polygonal mesh. By default, this is a disc.
  20461. * Please consider using the same method from the MeshBuilder class instead.
  20462. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20463. * 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.
  20464. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20465. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20466. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20467. */
  20468. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20469. var options = {
  20470. radius: radius,
  20471. tessellation: tessellation,
  20472. sideOrientation: sideOrientation,
  20473. updatable: updatable
  20474. };
  20475. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20476. };
  20477. /**
  20478. * Creates a box mesh.
  20479. * Please consider using the same method from the MeshBuilder class instead.
  20480. * The parameter `size` sets the size (float) of each box side (default 1).
  20481. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20482. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20483. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20484. */
  20485. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20486. var options = {
  20487. size: size,
  20488. sideOrientation: sideOrientation,
  20489. updatable: updatable
  20490. };
  20491. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20492. };
  20493. /**
  20494. * Creates a sphere mesh.
  20495. * Please consider using the same method from the MeshBuilder class instead.
  20496. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20497. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20498. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20499. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20500. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20501. */
  20502. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20503. var options = {
  20504. segments: segments,
  20505. diameterX: diameter,
  20506. diameterY: diameter,
  20507. diameterZ: diameter,
  20508. sideOrientation: sideOrientation,
  20509. updatable: updatable
  20510. };
  20511. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20512. };
  20513. /**
  20514. * Creates a cylinder or a cone mesh.
  20515. * Please consider using the same method from the MeshBuilder class instead.
  20516. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20517. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20518. * 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.
  20519. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20520. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20521. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20522. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20523. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20524. */
  20525. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20526. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20527. if (scene !== undefined) {
  20528. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20529. updatable = scene;
  20530. }
  20531. scene = subdivisions;
  20532. subdivisions = 1;
  20533. }
  20534. var options = {
  20535. height: height,
  20536. diameterTop: diameterTop,
  20537. diameterBottom: diameterBottom,
  20538. tessellation: tessellation,
  20539. subdivisions: subdivisions,
  20540. sideOrientation: sideOrientation,
  20541. updatable: updatable
  20542. };
  20543. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20544. };
  20545. // Torus (Code from SharpDX.org)
  20546. /**
  20547. * Creates a torus mesh.
  20548. * Please consider using the same method from the MeshBuilder class instead.
  20549. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20550. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20551. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20552. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20553. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20554. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20555. */
  20556. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20557. var options = {
  20558. diameter: diameter,
  20559. thickness: thickness,
  20560. tessellation: tessellation,
  20561. sideOrientation: sideOrientation,
  20562. updatable: updatable
  20563. };
  20564. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20565. };
  20566. /**
  20567. * Creates a torus knot mesh.
  20568. * Please consider using the same method from the MeshBuilder class instead.
  20569. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20570. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20571. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20572. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20573. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20574. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20575. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20576. */
  20577. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20578. var options = {
  20579. radius: radius,
  20580. tube: tube,
  20581. radialSegments: radialSegments,
  20582. tubularSegments: tubularSegments,
  20583. p: p,
  20584. q: q,
  20585. sideOrientation: sideOrientation,
  20586. updatable: updatable
  20587. };
  20588. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20589. };
  20590. /**
  20591. * Creates a line mesh.
  20592. * Please consider using the same method from the MeshBuilder class instead.
  20593. * 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.
  20594. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20595. * The parameter `points` is an array successive Vector3.
  20596. * 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
  20597. * When updating an instance, remember that only point positions can change, not the number of points.
  20598. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20599. */
  20600. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20601. var options = {
  20602. points: points,
  20603. updatable: updatable,
  20604. instance: instance
  20605. };
  20606. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20607. };
  20608. /**
  20609. * Creates a dashed line mesh.
  20610. * Please consider using the same method from the MeshBuilder class instead.
  20611. * 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.
  20612. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20613. * The parameter `points` is an array successive Vector3.
  20614. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20615. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20616. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20617. * 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
  20618. * When updating an instance, remember that only point positions can change, not the number of points.
  20619. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20620. */
  20621. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20622. var options = {
  20623. points: points,
  20624. dashSize: dashSize,
  20625. gapSize: gapSize,
  20626. dashNb: dashNb,
  20627. updatable: updatable,
  20628. instance: instance
  20629. };
  20630. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20631. };
  20632. /**
  20633. * Creates an extruded shape mesh.
  20634. * 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.
  20635. * Please consider using the same method from the MeshBuilder class instead.
  20636. *
  20637. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20638. * 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
  20639. * extruded along the Z axis.
  20640. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20641. * 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.
  20642. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20643. * 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
  20644. * 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
  20645. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20646. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20647. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20648. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20649. */
  20650. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20651. var options = {
  20652. shape: shape,
  20653. path: path,
  20654. scale: scale,
  20655. rotation: rotation,
  20656. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20657. sideOrientation: sideOrientation,
  20658. instance: instance,
  20659. updatable: updatable
  20660. };
  20661. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20662. };
  20663. /**
  20664. * Creates an custom extruded shape mesh.
  20665. * 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.
  20666. * Please consider using the same method from the MeshBuilder class instead.
  20667. *
  20668. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20669. * 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
  20670. * extruded along the Z axis.
  20671. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20672. * 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
  20673. * and the distance of this point from the begining of the path :
  20674. * ```javascript
  20675. * var rotationFunction = function(i, distance) {
  20676. * // do things
  20677. * return rotationValue; }
  20678. * ```
  20679. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20680. * 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
  20681. * and the distance of this point from the begining of the path :
  20682. * ```javascript
  20683. * var scaleFunction = function(i, distance) {
  20684. * // do things
  20685. * return scaleValue;}
  20686. * ```
  20687. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20688. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20689. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20690. * 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
  20691. * 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
  20692. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20693. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20694. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20695. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20696. */
  20697. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20698. var options = {
  20699. shape: shape,
  20700. path: path,
  20701. scaleFunction: scaleFunction,
  20702. rotationFunction: rotationFunction,
  20703. ribbonCloseArray: ribbonCloseArray,
  20704. ribbonClosePath: ribbonClosePath,
  20705. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20706. sideOrientation: sideOrientation,
  20707. instance: instance,
  20708. updatable: updatable
  20709. };
  20710. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20711. };
  20712. /**
  20713. * Creates lathe mesh.
  20714. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20715. * Please consider using the same method from the MeshBuilder class instead.
  20716. * 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
  20717. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20718. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20719. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20720. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20721. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20722. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20723. */
  20724. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20725. var options = {
  20726. shape: shape,
  20727. radius: radius,
  20728. tessellation: tessellation,
  20729. sideOrientation: sideOrientation,
  20730. updatable: updatable
  20731. };
  20732. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20733. };
  20734. /**
  20735. * Creates a plane mesh.
  20736. * Please consider using the same method from the MeshBuilder class instead.
  20737. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20738. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20739. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20740. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20741. */
  20742. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20743. var options = {
  20744. size: size,
  20745. width: size,
  20746. height: size,
  20747. sideOrientation: sideOrientation,
  20748. updatable: updatable
  20749. };
  20750. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20751. };
  20752. /**
  20753. * Creates a ground mesh.
  20754. * Please consider using the same method from the MeshBuilder class instead.
  20755. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20756. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20757. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20758. */
  20759. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20760. var options = {
  20761. width: width,
  20762. height: height,
  20763. subdivisions: subdivisions,
  20764. updatable: updatable
  20765. };
  20766. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20767. };
  20768. /**
  20769. * Creates a tiled ground mesh.
  20770. * Please consider using the same method from the MeshBuilder class instead.
  20771. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20772. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20773. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20774. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20775. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20776. * numbers of subdivisions on the ground width and height of each tile.
  20777. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20778. */
  20779. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  20780. var options = {
  20781. xmin: xmin,
  20782. zmin: zmin,
  20783. xmax: xmax,
  20784. zmax: zmax,
  20785. subdivisions: subdivisions,
  20786. precision: precision,
  20787. updatable: updatable
  20788. };
  20789. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  20790. };
  20791. /**
  20792. * Creates a ground mesh from a height map.
  20793. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20794. * Please consider using the same method from the MeshBuilder class instead.
  20795. * The parameter `url` sets the URL of the height map image resource.
  20796. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20797. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20798. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20799. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20800. * 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).
  20801. * This function is passed the newly built mesh :
  20802. * ```javascript
  20803. * function(mesh) { // do things
  20804. * return; }
  20805. * ```
  20806. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20807. */
  20808. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  20809. var options = {
  20810. width: width,
  20811. height: height,
  20812. subdivisions: subdivisions,
  20813. minHeight: minHeight,
  20814. maxHeight: maxHeight,
  20815. updatable: updatable,
  20816. onReady: onReady
  20817. };
  20818. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  20819. };
  20820. /**
  20821. * Creates a tube mesh.
  20822. * 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.
  20823. * Please consider using the same method from the MeshBuilder class instead.
  20824. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20825. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20826. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20827. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20828. * 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.
  20829. * It must return a radius value (positive float) :
  20830. * ```javascript
  20831. * var radiusFunction = function(i, distance) {
  20832. * // do things
  20833. * return radius; }
  20834. * ```
  20835. * 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
  20836. * 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
  20837. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20838. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20839. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20840. */
  20841. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  20842. var options = {
  20843. path: path,
  20844. radius: radius,
  20845. tessellation: tessellation,
  20846. radiusFunction: radiusFunction,
  20847. arc: 1,
  20848. cap: cap,
  20849. updatable: updatable,
  20850. sideOrientation: sideOrientation,
  20851. instance: instance
  20852. };
  20853. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  20854. };
  20855. /**
  20856. * Creates a polyhedron mesh.
  20857. * Please consider using the same method from the MeshBuilder class instead.
  20858. * 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
  20859. * to choose the wanted type.
  20860. * The parameter `size` (positive float, default 1) sets the polygon size.
  20861. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20862. * 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`.
  20863. * 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
  20864. * 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)`).
  20865. * 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
  20866. * 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.
  20867. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20868. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20869. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20870. */
  20871. Mesh.CreatePolyhedron = function (name, options, scene) {
  20872. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  20873. };
  20874. /**
  20875. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20876. * Please consider using the same method from the MeshBuilder class instead.
  20877. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20878. * 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`).
  20879. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20880. * 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.
  20881. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20882. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20883. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20884. */
  20885. Mesh.CreateIcoSphere = function (name, options, scene) {
  20886. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  20887. };
  20888. /**
  20889. * Creates a decal mesh.
  20890. * Please consider using the same method from the MeshBuilder class instead.
  20891. * 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.
  20892. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20893. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20894. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  20895. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20896. */
  20897. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  20898. var options = {
  20899. position: position,
  20900. normal: normal,
  20901. size: size,
  20902. angle: angle
  20903. };
  20904. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  20905. };
  20906. // Skeletons
  20907. /**
  20908. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20909. */
  20910. Mesh.prototype.setPositionsForCPUSkinning = function () {
  20911. var source;
  20912. if (!this._sourcePositions) {
  20913. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20914. this._sourcePositions = new Float32Array(source);
  20915. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  20916. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  20917. }
  20918. }
  20919. return this._sourcePositions;
  20920. };
  20921. /**
  20922. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20923. */
  20924. Mesh.prototype.setNormalsForCPUSkinning = function () {
  20925. var source;
  20926. if (!this._sourceNormals) {
  20927. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20928. this._sourceNormals = new Float32Array(source);
  20929. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  20930. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  20931. }
  20932. }
  20933. return this._sourceNormals;
  20934. };
  20935. /**
  20936. * Updates the vertex buffer by applying transformation from the bones.
  20937. * Returns the Mesh.
  20938. *
  20939. * @param {skeleton} skeleton to apply
  20940. */
  20941. Mesh.prototype.applySkeleton = function (skeleton) {
  20942. if (!this.geometry) {
  20943. return this;
  20944. }
  20945. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  20946. return this;
  20947. }
  20948. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  20949. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20950. return this;
  20951. }
  20952. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20953. return this;
  20954. }
  20955. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20956. return this;
  20957. }
  20958. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20959. return this;
  20960. }
  20961. if (!this._sourcePositions) {
  20962. var submeshes = this.subMeshes.slice();
  20963. this.setPositionsForCPUSkinning();
  20964. this.subMeshes = submeshes;
  20965. }
  20966. if (!this._sourceNormals) {
  20967. this.setNormalsForCPUSkinning();
  20968. }
  20969. // positionsData checks for not being Float32Array will only pass at most once
  20970. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20971. if (!(positionsData instanceof Float32Array)) {
  20972. positionsData = new Float32Array(positionsData);
  20973. }
  20974. // normalsData checks for not being Float32Array will only pass at most once
  20975. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20976. if (!(normalsData instanceof Float32Array)) {
  20977. normalsData = new Float32Array(normalsData);
  20978. }
  20979. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20980. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20981. var needExtras = this.numBoneInfluencers > 4;
  20982. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  20983. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  20984. var skeletonMatrices = skeleton.getTransformMatrices(this);
  20985. var tempVector3 = BABYLON.Vector3.Zero();
  20986. var finalMatrix = new BABYLON.Matrix();
  20987. var tempMatrix = new BABYLON.Matrix();
  20988. var matWeightIdx = 0;
  20989. var inf;
  20990. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  20991. var weight;
  20992. for (inf = 0; inf < 4; inf++) {
  20993. weight = matricesWeightsData[matWeightIdx + inf];
  20994. if (weight > 0) {
  20995. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20996. finalMatrix.addToSelf(tempMatrix);
  20997. }
  20998. else
  20999. break;
  21000. }
  21001. if (needExtras) {
  21002. for (inf = 0; inf < 4; inf++) {
  21003. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21004. if (weight > 0) {
  21005. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21006. finalMatrix.addToSelf(tempMatrix);
  21007. }
  21008. else
  21009. break;
  21010. }
  21011. }
  21012. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21013. tempVector3.toArray(positionsData, index);
  21014. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21015. tempVector3.toArray(normalsData, index);
  21016. finalMatrix.reset();
  21017. }
  21018. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21019. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21020. return this;
  21021. };
  21022. // Tools
  21023. /**
  21024. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21025. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21026. */
  21027. Mesh.MinMax = function (meshes) {
  21028. var minVector = null;
  21029. var maxVector = null;
  21030. meshes.forEach(function (mesh, index, array) {
  21031. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21032. if (!minVector) {
  21033. minVector = boundingBox.minimumWorld;
  21034. maxVector = boundingBox.maximumWorld;
  21035. }
  21036. else {
  21037. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21038. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21039. }
  21040. });
  21041. return {
  21042. min: minVector,
  21043. max: maxVector
  21044. };
  21045. };
  21046. /**
  21047. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21048. */
  21049. Mesh.Center = function (meshesOrMinMaxVector) {
  21050. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21051. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21052. };
  21053. /**
  21054. * Merge the array of meshes into a single mesh for performance reasons.
  21055. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21056. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21057. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21058. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21059. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  21060. */
  21061. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  21062. if (disposeSource === void 0) { disposeSource = true; }
  21063. var index;
  21064. if (!allow32BitsIndices) {
  21065. var totalVertices = 0;
  21066. // Counting vertices
  21067. for (index = 0; index < meshes.length; index++) {
  21068. if (meshes[index]) {
  21069. totalVertices += meshes[index].getTotalVertices();
  21070. if (totalVertices > 65536) {
  21071. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21072. return null;
  21073. }
  21074. }
  21075. }
  21076. }
  21077. // Merge
  21078. var vertexData;
  21079. var otherVertexData;
  21080. var indiceArray = new Array();
  21081. var source;
  21082. for (index = 0; index < meshes.length; index++) {
  21083. if (meshes[index]) {
  21084. meshes[index].computeWorldMatrix(true);
  21085. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21086. otherVertexData.transform(meshes[index].getWorldMatrix());
  21087. if (vertexData) {
  21088. vertexData.merge(otherVertexData);
  21089. }
  21090. else {
  21091. vertexData = otherVertexData;
  21092. source = meshes[index];
  21093. }
  21094. if (subdivideWithSubMeshes) {
  21095. indiceArray.push(meshes[index].getTotalIndices());
  21096. }
  21097. }
  21098. }
  21099. if (!meshSubclass) {
  21100. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21101. }
  21102. vertexData.applyToMesh(meshSubclass);
  21103. // Setting properties
  21104. meshSubclass.material = source.material;
  21105. meshSubclass.checkCollisions = source.checkCollisions;
  21106. // Cleaning
  21107. if (disposeSource) {
  21108. for (index = 0; index < meshes.length; index++) {
  21109. if (meshes[index]) {
  21110. meshes[index].dispose();
  21111. }
  21112. }
  21113. }
  21114. // Subdivide
  21115. if (subdivideWithSubMeshes) {
  21116. //-- Suppresions du submesh global
  21117. meshSubclass.releaseSubMeshes();
  21118. index = 0;
  21119. var offset = 0;
  21120. //-- aplique la subdivision en fonction du tableau d'indices
  21121. while (index < indiceArray.length) {
  21122. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  21123. offset += indiceArray[index];
  21124. index++;
  21125. }
  21126. }
  21127. return meshSubclass;
  21128. };
  21129. return Mesh;
  21130. }(BABYLON.AbstractMesh));
  21131. // Consts
  21132. Mesh._FRONTSIDE = 0;
  21133. Mesh._BACKSIDE = 1;
  21134. Mesh._DOUBLESIDE = 2;
  21135. Mesh._DEFAULTSIDE = 0;
  21136. Mesh._NO_CAP = 0;
  21137. Mesh._CAP_START = 1;
  21138. Mesh._CAP_END = 2;
  21139. Mesh._CAP_ALL = 3;
  21140. BABYLON.Mesh = Mesh;
  21141. })(BABYLON || (BABYLON = {}));
  21142. //# sourceMappingURL=babylon.mesh.js.map
  21143. var BABYLON;
  21144. (function (BABYLON) {
  21145. var SubMesh = (function () {
  21146. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  21147. if (createBoundingBox === void 0) { createBoundingBox = true; }
  21148. this.materialIndex = materialIndex;
  21149. this.verticesStart = verticesStart;
  21150. this.verticesCount = verticesCount;
  21151. this.indexStart = indexStart;
  21152. this.indexCount = indexCount;
  21153. this._renderId = 0;
  21154. this._mesh = mesh;
  21155. this._renderingMesh = renderingMesh || mesh;
  21156. mesh.subMeshes.push(this);
  21157. this._trianglePlanes = [];
  21158. this._id = mesh.subMeshes.length - 1;
  21159. if (createBoundingBox) {
  21160. this.refreshBoundingInfo();
  21161. mesh.computeWorldMatrix(true);
  21162. }
  21163. }
  21164. Object.defineProperty(SubMesh.prototype, "effect", {
  21165. get: function () {
  21166. return this._materialEffect;
  21167. },
  21168. enumerable: true,
  21169. configurable: true
  21170. });
  21171. SubMesh.prototype.setEffect = function (effect, defines) {
  21172. if (this._materialEffect === effect) {
  21173. return;
  21174. }
  21175. this._materialDefines = defines;
  21176. this._materialEffect = effect;
  21177. };
  21178. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21179. get: function () {
  21180. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21181. },
  21182. enumerable: true,
  21183. configurable: true
  21184. });
  21185. /**
  21186. * Returns the submesh BoudingInfo object.
  21187. */
  21188. SubMesh.prototype.getBoundingInfo = function () {
  21189. if (this.IsGlobal) {
  21190. return this._mesh.getBoundingInfo();
  21191. }
  21192. return this._boundingInfo;
  21193. };
  21194. /**
  21195. * Sets the submesh BoundingInfo.
  21196. * Return the SubMesh.
  21197. */
  21198. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21199. this._boundingInfo = boundingInfo;
  21200. return this;
  21201. };
  21202. /**
  21203. * Returns the mesh of the current submesh.
  21204. */
  21205. SubMesh.prototype.getMesh = function () {
  21206. return this._mesh;
  21207. };
  21208. /**
  21209. * Returns the rendering mesh of the submesh.
  21210. */
  21211. SubMesh.prototype.getRenderingMesh = function () {
  21212. return this._renderingMesh;
  21213. };
  21214. /**
  21215. * Returns the submesh material.
  21216. */
  21217. SubMesh.prototype.getMaterial = function () {
  21218. var rootMaterial = this._renderingMesh.material;
  21219. if (rootMaterial && rootMaterial.getSubMaterial) {
  21220. var multiMaterial = rootMaterial;
  21221. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  21222. if (this._currentMaterial !== effectiveMaterial) {
  21223. this._currentMaterial = effectiveMaterial;
  21224. if (this._materialDefines) {
  21225. this._materialDefines.markAllAsDirty();
  21226. }
  21227. }
  21228. return effectiveMaterial;
  21229. }
  21230. if (!rootMaterial) {
  21231. return this._mesh.getScene().defaultMaterial;
  21232. }
  21233. return rootMaterial;
  21234. };
  21235. // Methods
  21236. /**
  21237. * Sets a new updated BoundingInfo object to the submesh.
  21238. * Returns the SubMesh.
  21239. */
  21240. SubMesh.prototype.refreshBoundingInfo = function () {
  21241. this._lastColliderWorldVertices = null;
  21242. if (this.IsGlobal) {
  21243. return;
  21244. }
  21245. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21246. if (!data) {
  21247. this._boundingInfo = this._mesh._boundingInfo;
  21248. return;
  21249. }
  21250. var indices = this._renderingMesh.getIndices();
  21251. var extend;
  21252. //is this the only submesh?
  21253. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21254. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21255. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21256. }
  21257. else {
  21258. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21259. }
  21260. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21261. return this;
  21262. };
  21263. SubMesh.prototype._checkCollision = function (collider) {
  21264. return this.getBoundingInfo()._checkCollision(collider);
  21265. };
  21266. /**
  21267. * Updates the submesh BoundingInfo.
  21268. * Returns the Submesh.
  21269. */
  21270. SubMesh.prototype.updateBoundingInfo = function (world) {
  21271. if (!this.getBoundingInfo()) {
  21272. this.refreshBoundingInfo();
  21273. }
  21274. this.getBoundingInfo().update(world);
  21275. return this;
  21276. };
  21277. /**
  21278. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  21279. * Boolean returned.
  21280. */
  21281. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21282. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21283. };
  21284. /**
  21285. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  21286. * Boolean returned.
  21287. */
  21288. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21289. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21290. };
  21291. /**
  21292. * Renders the submesh.
  21293. * Returns it.
  21294. */
  21295. SubMesh.prototype.render = function (enableAlphaMode) {
  21296. this._renderingMesh.render(this, enableAlphaMode);
  21297. return this;
  21298. };
  21299. /**
  21300. * Returns a new Index Buffer.
  21301. * Type returned : WebGLBuffer.
  21302. */
  21303. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21304. if (!this._linesIndexBuffer) {
  21305. var linesIndices = [];
  21306. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21307. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21308. }
  21309. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21310. this.linesIndexCount = linesIndices.length;
  21311. }
  21312. return this._linesIndexBuffer;
  21313. };
  21314. /**
  21315. * True is the passed Ray intersects the submesh bounding box.
  21316. * Boolean returned.
  21317. */
  21318. SubMesh.prototype.canIntersects = function (ray) {
  21319. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21320. };
  21321. /**
  21322. * Returns an object IntersectionInfo.
  21323. */
  21324. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21325. var intersectInfo = null;
  21326. // LineMesh first as it's also a Mesh...
  21327. if (this._mesh instanceof BABYLON.LinesMesh) {
  21328. var lineMesh = this._mesh;
  21329. // Line test
  21330. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21331. var p0 = positions[indices[index]];
  21332. var p1 = positions[indices[index + 1]];
  21333. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21334. if (length < 0) {
  21335. continue;
  21336. }
  21337. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21338. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21339. if (fastCheck) {
  21340. break;
  21341. }
  21342. }
  21343. }
  21344. }
  21345. else {
  21346. // Triangles test
  21347. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21348. var p0 = positions[indices[index]];
  21349. var p1 = positions[indices[index + 1]];
  21350. var p2 = positions[indices[index + 2]];
  21351. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21352. if (currentIntersectInfo) {
  21353. if (currentIntersectInfo.distance < 0) {
  21354. continue;
  21355. }
  21356. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21357. intersectInfo = currentIntersectInfo;
  21358. intersectInfo.faceId = index / 3;
  21359. if (fastCheck) {
  21360. break;
  21361. }
  21362. }
  21363. }
  21364. }
  21365. }
  21366. return intersectInfo;
  21367. };
  21368. // Clone
  21369. /**
  21370. * Creates a new Submesh from the passed Mesh.
  21371. */
  21372. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21373. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21374. if (!this.IsGlobal) {
  21375. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21376. }
  21377. return result;
  21378. };
  21379. // Dispose
  21380. /**
  21381. * Disposes the Submesh.
  21382. * Returns nothing.
  21383. */
  21384. SubMesh.prototype.dispose = function () {
  21385. if (this._linesIndexBuffer) {
  21386. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21387. this._linesIndexBuffer = null;
  21388. }
  21389. // Remove from mesh
  21390. var index = this._mesh.subMeshes.indexOf(this);
  21391. this._mesh.subMeshes.splice(index, 1);
  21392. };
  21393. // Statics
  21394. /**
  21395. * Creates a new Submesh from the passed parameters :
  21396. * - materialIndex (integer) : the index of the main mesh material.
  21397. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  21398. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  21399. * - mesh (Mesh) : the main mesh to create the submesh from.
  21400. * - renderingMesh (optional Mesh) : rendering mesh.
  21401. */
  21402. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21403. var minVertexIndex = Number.MAX_VALUE;
  21404. var maxVertexIndex = -Number.MAX_VALUE;
  21405. renderingMesh = renderingMesh || mesh;
  21406. var indices = renderingMesh.getIndices();
  21407. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21408. var vertexIndex = indices[index];
  21409. if (vertexIndex < minVertexIndex)
  21410. minVertexIndex = vertexIndex;
  21411. if (vertexIndex > maxVertexIndex)
  21412. maxVertexIndex = vertexIndex;
  21413. }
  21414. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21415. };
  21416. return SubMesh;
  21417. }());
  21418. BABYLON.SubMesh = SubMesh;
  21419. })(BABYLON || (BABYLON = {}));
  21420. //# sourceMappingURL=babylon.subMesh.js.map
  21421. var BABYLON;
  21422. (function (BABYLON) {
  21423. var EffectFallbacks = (function () {
  21424. function EffectFallbacks() {
  21425. this._defines = {};
  21426. this._currentRank = 32;
  21427. this._maxRank = -1;
  21428. }
  21429. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21430. if (!this._defines[rank]) {
  21431. if (rank < this._currentRank) {
  21432. this._currentRank = rank;
  21433. }
  21434. if (rank > this._maxRank) {
  21435. this._maxRank = rank;
  21436. }
  21437. this._defines[rank] = new Array();
  21438. }
  21439. this._defines[rank].push(define);
  21440. };
  21441. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21442. this._meshRank = rank;
  21443. this._mesh = mesh;
  21444. if (rank < this._currentRank) {
  21445. this._currentRank = rank;
  21446. }
  21447. if (rank > this._maxRank) {
  21448. this._maxRank = rank;
  21449. }
  21450. };
  21451. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21452. get: function () {
  21453. return this._currentRank <= this._maxRank;
  21454. },
  21455. enumerable: true,
  21456. configurable: true
  21457. });
  21458. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21459. // First we try to switch to CPU skinning
  21460. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  21461. this._mesh.computeBonesUsingShaders = false;
  21462. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21463. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21464. var scene = this._mesh.getScene();
  21465. for (var index = 0; index < scene.meshes.length; index++) {
  21466. var otherMesh = scene.meshes[index];
  21467. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  21468. otherMesh.computeBonesUsingShaders = false;
  21469. }
  21470. }
  21471. }
  21472. else {
  21473. var currentFallbacks = this._defines[this._currentRank];
  21474. if (currentFallbacks) {
  21475. for (var index = 0; index < currentFallbacks.length; index++) {
  21476. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21477. }
  21478. }
  21479. this._currentRank++;
  21480. }
  21481. return currentDefines;
  21482. };
  21483. return EffectFallbacks;
  21484. }());
  21485. BABYLON.EffectFallbacks = EffectFallbacks;
  21486. var EffectCreationOptions = (function () {
  21487. function EffectCreationOptions() {
  21488. }
  21489. return EffectCreationOptions;
  21490. }());
  21491. BABYLON.EffectCreationOptions = EffectCreationOptions;
  21492. var Effect = (function () {
  21493. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  21494. var _this = this;
  21495. this.uniqueId = 0;
  21496. this._uniformBuffersNames = {};
  21497. this._isReady = false;
  21498. this._compilationError = "";
  21499. this._valueCache = {};
  21500. this.name = baseName;
  21501. if (attributesNamesOrOptions.attributes) {
  21502. var options = attributesNamesOrOptions;
  21503. this._engine = uniformsNamesOrEngine;
  21504. this._attributesNames = options.attributes;
  21505. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  21506. this._samplers = options.samplers;
  21507. this.defines = options.defines;
  21508. this.onError = options.onError;
  21509. this.onCompiled = options.onCompiled;
  21510. this._fallbacks = options.fallbacks;
  21511. this._indexParameters = options.indexParameters;
  21512. if (options.uniformBuffersNames) {
  21513. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  21514. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  21515. }
  21516. }
  21517. }
  21518. else {
  21519. this._engine = engine;
  21520. this.defines = defines;
  21521. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  21522. this._samplers = samplers;
  21523. this._attributesNames = attributesNamesOrOptions;
  21524. this.onError = onError;
  21525. this.onCompiled = onCompiled;
  21526. this._indexParameters = indexParameters;
  21527. this._fallbacks = fallbacks;
  21528. }
  21529. this.uniqueId = Effect._uniqueIdSeed++;
  21530. var vertexSource;
  21531. var fragmentSource;
  21532. if (baseName.vertexElement) {
  21533. vertexSource = document.getElementById(baseName.vertexElement);
  21534. if (!vertexSource) {
  21535. vertexSource = baseName.vertexElement;
  21536. }
  21537. }
  21538. else {
  21539. vertexSource = baseName.vertex || baseName;
  21540. }
  21541. if (baseName.fragmentElement) {
  21542. fragmentSource = document.getElementById(baseName.fragmentElement);
  21543. if (!fragmentSource) {
  21544. fragmentSource = baseName.fragmentElement;
  21545. }
  21546. }
  21547. else {
  21548. fragmentSource = baseName.fragment || baseName;
  21549. }
  21550. this._loadVertexShader(vertexSource, function (vertexCode) {
  21551. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  21552. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  21553. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  21554. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  21555. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  21556. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  21557. });
  21558. });
  21559. });
  21560. });
  21561. });
  21562. });
  21563. }
  21564. Object.defineProperty(Effect.prototype, "key", {
  21565. get: function () {
  21566. return this._key;
  21567. },
  21568. enumerable: true,
  21569. configurable: true
  21570. });
  21571. // Properties
  21572. Effect.prototype.isReady = function () {
  21573. return this._isReady;
  21574. };
  21575. Effect.prototype.getProgram = function () {
  21576. return this._program;
  21577. };
  21578. Effect.prototype.getAttributesNames = function () {
  21579. return this._attributesNames;
  21580. };
  21581. Effect.prototype.getAttributeLocation = function (index) {
  21582. return this._attributes[index];
  21583. };
  21584. Effect.prototype.getAttributeLocationByName = function (name) {
  21585. var index = this._attributesNames.indexOf(name);
  21586. return this._attributes[index];
  21587. };
  21588. Effect.prototype.getAttributesCount = function () {
  21589. return this._attributes.length;
  21590. };
  21591. Effect.prototype.getUniformIndex = function (uniformName) {
  21592. return this._uniformsNames.indexOf(uniformName);
  21593. };
  21594. Effect.prototype.getUniform = function (uniformName) {
  21595. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  21596. };
  21597. Effect.prototype.getSamplers = function () {
  21598. return this._samplers;
  21599. };
  21600. Effect.prototype.getCompilationError = function () {
  21601. return this._compilationError;
  21602. };
  21603. Effect.prototype.getVertexShaderSource = function () {
  21604. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  21605. };
  21606. Effect.prototype.getFragmentShaderSource = function () {
  21607. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  21608. };
  21609. // Methods
  21610. Effect.prototype._loadVertexShader = function (vertex, callback) {
  21611. // DOM element ?
  21612. if (vertex instanceof HTMLElement) {
  21613. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  21614. callback(vertexCode);
  21615. return;
  21616. }
  21617. // Base64 encoded ?
  21618. if (vertex.substr(0, 7) === "base64:") {
  21619. var vertexBinary = window.atob(vertex.substr(7));
  21620. callback(vertexBinary);
  21621. return;
  21622. }
  21623. // Is in local store ?
  21624. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  21625. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  21626. return;
  21627. }
  21628. var vertexShaderUrl;
  21629. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  21630. vertexShaderUrl = vertex;
  21631. }
  21632. else {
  21633. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  21634. }
  21635. // Vertex shader
  21636. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  21637. };
  21638. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  21639. // DOM element ?
  21640. if (fragment instanceof HTMLElement) {
  21641. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  21642. callback(fragmentCode);
  21643. return;
  21644. }
  21645. // Base64 encoded ?
  21646. if (fragment.substr(0, 7) === "base64:") {
  21647. var fragmentBinary = window.atob(fragment.substr(7));
  21648. callback(fragmentBinary);
  21649. return;
  21650. }
  21651. // Is in local store ?
  21652. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  21653. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  21654. return;
  21655. }
  21656. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  21657. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  21658. return;
  21659. }
  21660. var fragmentShaderUrl;
  21661. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  21662. fragmentShaderUrl = fragment;
  21663. }
  21664. else {
  21665. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  21666. }
  21667. // Fragment shader
  21668. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  21669. };
  21670. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  21671. // Rebuild shaders source code
  21672. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  21673. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  21674. vertexCode = prefix + vertexCode;
  21675. fragmentCode = prefix + fragmentCode;
  21676. // Number lines of shaders source code
  21677. var i = 2;
  21678. var regex = /\n/gm;
  21679. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  21680. i = 2;
  21681. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  21682. // Dump shaders name and formatted source code
  21683. if (this.name.vertexElement) {
  21684. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  21685. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  21686. }
  21687. else if (this.name.vertex) {
  21688. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  21689. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  21690. }
  21691. else {
  21692. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  21693. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  21694. }
  21695. };
  21696. ;
  21697. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  21698. var preparedSourceCode = this._processPrecision(sourceCode);
  21699. if (this._engine.webGLVersion == 1) {
  21700. callback(preparedSourceCode);
  21701. return;
  21702. }
  21703. // Already converted
  21704. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  21705. callback(preparedSourceCode);
  21706. return;
  21707. }
  21708. // Remove extensions
  21709. // #extension GL_OES_standard_derivatives : enable
  21710. // #extension GL_EXT_shader_texture_lod : enable
  21711. // #extension GL_EXT_frag_depth : enable
  21712. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  21713. var result = preparedSourceCode.replace(regex, "");
  21714. // Migrate to GLSL v300
  21715. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  21716. result = result.replace(/attribute[ \t]/g, "in ");
  21717. result = result.replace(/[ \t]attribute/g, " in");
  21718. if (isFragment) {
  21719. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  21720. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  21721. result = result.replace(/texture2D\(/g, "texture(");
  21722. result = result.replace(/textureCube\(/g, "texture(");
  21723. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  21724. result = result.replace(/gl_FragColor/g, "glFragColor");
  21725. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  21726. }
  21727. callback(result);
  21728. };
  21729. Effect.prototype._processIncludes = function (sourceCode, callback) {
  21730. var _this = this;
  21731. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  21732. var match = regex.exec(sourceCode);
  21733. var returnValue = new String(sourceCode);
  21734. while (match != null) {
  21735. var includeFile = match[1];
  21736. // Uniform declaration
  21737. if (includeFile.indexOf("__decl__") !== -1) {
  21738. includeFile = includeFile.replace(/__decl__/, "");
  21739. if (this._engine.webGLVersion != 1) {
  21740. includeFile = includeFile.replace(/Vertex/, "Ubo");
  21741. includeFile = includeFile.replace(/Fragment/, "Ubo");
  21742. }
  21743. includeFile = includeFile + "Declaration";
  21744. }
  21745. if (Effect.IncludesShadersStore[includeFile]) {
  21746. // Substitution
  21747. var includeContent = Effect.IncludesShadersStore[includeFile];
  21748. if (match[2]) {
  21749. var splits = match[3].split(",");
  21750. for (var index = 0; index < splits.length; index += 2) {
  21751. var source = new RegExp(splits[index], "g");
  21752. var dest = splits[index + 1];
  21753. includeContent = includeContent.replace(source, dest);
  21754. }
  21755. }
  21756. if (match[4]) {
  21757. var indexString = match[5];
  21758. if (indexString.indexOf("..") !== -1) {
  21759. var indexSplits = indexString.split("..");
  21760. var minIndex = parseInt(indexSplits[0]);
  21761. var maxIndex = parseInt(indexSplits[1]);
  21762. var sourceIncludeContent = includeContent.slice(0);
  21763. includeContent = "";
  21764. if (isNaN(maxIndex)) {
  21765. maxIndex = this._indexParameters[indexSplits[1]];
  21766. }
  21767. for (var i = minIndex; i < maxIndex; i++) {
  21768. if (this._engine.webGLVersion === 1) {
  21769. // Ubo replacement
  21770. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  21771. return p1 + "{X}";
  21772. });
  21773. }
  21774. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  21775. }
  21776. }
  21777. else {
  21778. if (this._engine.webGLVersion === 1) {
  21779. // Ubo replacement
  21780. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  21781. return p1 + "{X}";
  21782. });
  21783. }
  21784. includeContent = includeContent.replace(/\{X\}/g, indexString);
  21785. }
  21786. }
  21787. // Replace
  21788. returnValue = returnValue.replace(match[0], includeContent);
  21789. }
  21790. else {
  21791. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  21792. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  21793. Effect.IncludesShadersStore[includeFile] = fileContent;
  21794. _this._processIncludes(returnValue, callback);
  21795. });
  21796. return;
  21797. }
  21798. match = regex.exec(sourceCode);
  21799. }
  21800. callback(returnValue);
  21801. };
  21802. Effect.prototype._processPrecision = function (source) {
  21803. if (source.indexOf("precision highp float") === -1) {
  21804. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21805. source = "precision mediump float;\n" + source;
  21806. }
  21807. else {
  21808. source = "precision highp float;\n" + source;
  21809. }
  21810. }
  21811. else {
  21812. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21813. source = source.replace("precision highp float", "precision mediump float");
  21814. }
  21815. }
  21816. return source;
  21817. };
  21818. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  21819. try {
  21820. var engine = this._engine;
  21821. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  21822. if (engine.webGLVersion > 1) {
  21823. for (var name in this._uniformBuffersNames) {
  21824. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  21825. }
  21826. }
  21827. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  21828. this._attributes = engine.getAttributes(this._program, attributesNames);
  21829. var index;
  21830. for (index = 0; index < this._samplers.length; index++) {
  21831. var sampler = this.getUniform(this._samplers[index]);
  21832. if (sampler == null) {
  21833. this._samplers.splice(index, 1);
  21834. index--;
  21835. }
  21836. }
  21837. engine.bindSamplers(this);
  21838. this._compilationError = "";
  21839. this._isReady = true;
  21840. if (this.onCompiled) {
  21841. this.onCompiled(this);
  21842. }
  21843. }
  21844. catch (e) {
  21845. this._compilationError = e.message;
  21846. // Let's go through fallbacks then
  21847. BABYLON.Tools.Error("Unable to compile effect:");
  21848. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  21849. return " " + uniform;
  21850. }));
  21851. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  21852. return " " + attribute;
  21853. }));
  21854. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  21855. BABYLON.Tools.Error("Error: " + this._compilationError);
  21856. if (fallbacks && fallbacks.isMoreFallbacks) {
  21857. BABYLON.Tools.Error("Trying next fallback.");
  21858. defines = fallbacks.reduce(defines);
  21859. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21860. }
  21861. else {
  21862. if (this.onError) {
  21863. this.onError(this, this._compilationError);
  21864. }
  21865. }
  21866. }
  21867. };
  21868. Object.defineProperty(Effect.prototype, "isSupported", {
  21869. get: function () {
  21870. return this._compilationError === "";
  21871. },
  21872. enumerable: true,
  21873. configurable: true
  21874. });
  21875. Effect.prototype._bindTexture = function (channel, texture) {
  21876. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  21877. };
  21878. Effect.prototype.setTexture = function (channel, texture) {
  21879. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  21880. };
  21881. Effect.prototype.setTextureArray = function (channel, textures) {
  21882. if (this._samplers.indexOf(channel + "Ex") === -1) {
  21883. var initialPos = this._samplers.indexOf(channel);
  21884. for (var index = 1; index < textures.length; index++) {
  21885. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  21886. }
  21887. }
  21888. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  21889. };
  21890. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  21891. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  21892. };
  21893. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  21894. var cache = this._valueCache[uniformName];
  21895. var flag = matrix.updateFlag;
  21896. if (cache !== undefined && cache === flag) {
  21897. return false;
  21898. }
  21899. this._valueCache[uniformName] = flag;
  21900. return true;
  21901. };
  21902. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  21903. var cache = this._valueCache[uniformName];
  21904. if (!cache) {
  21905. cache = [x, y];
  21906. this._valueCache[uniformName] = cache;
  21907. return true;
  21908. }
  21909. var changed = false;
  21910. if (cache[0] !== x) {
  21911. cache[0] = x;
  21912. changed = true;
  21913. }
  21914. if (cache[1] !== y) {
  21915. cache[1] = y;
  21916. changed = true;
  21917. }
  21918. return changed;
  21919. };
  21920. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  21921. var cache = this._valueCache[uniformName];
  21922. if (!cache) {
  21923. cache = [x, y, z];
  21924. this._valueCache[uniformName] = cache;
  21925. return true;
  21926. }
  21927. var changed = false;
  21928. if (cache[0] !== x) {
  21929. cache[0] = x;
  21930. changed = true;
  21931. }
  21932. if (cache[1] !== y) {
  21933. cache[1] = y;
  21934. changed = true;
  21935. }
  21936. if (cache[2] !== z) {
  21937. cache[2] = z;
  21938. changed = true;
  21939. }
  21940. return changed;
  21941. };
  21942. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  21943. var cache = this._valueCache[uniformName];
  21944. if (!cache) {
  21945. cache = [x, y, z, w];
  21946. this._valueCache[uniformName] = cache;
  21947. return true;
  21948. }
  21949. var changed = false;
  21950. if (cache[0] !== x) {
  21951. cache[0] = x;
  21952. changed = true;
  21953. }
  21954. if (cache[1] !== y) {
  21955. cache[1] = y;
  21956. changed = true;
  21957. }
  21958. if (cache[2] !== z) {
  21959. cache[2] = z;
  21960. changed = true;
  21961. }
  21962. if (cache[3] !== w) {
  21963. cache[3] = w;
  21964. changed = true;
  21965. }
  21966. return changed;
  21967. };
  21968. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  21969. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  21970. return;
  21971. }
  21972. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  21973. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  21974. };
  21975. Effect.prototype.bindUniformBlock = function (blockName, index) {
  21976. this._engine.bindUniformBlock(this._program, blockName, index);
  21977. };
  21978. Effect.prototype.setIntArray = function (uniformName, array) {
  21979. this._valueCache[uniformName] = null;
  21980. this._engine.setIntArray(this.getUniform(uniformName), array);
  21981. return this;
  21982. };
  21983. Effect.prototype.setIntArray2 = function (uniformName, array) {
  21984. this._valueCache[uniformName] = null;
  21985. this._engine.setIntArray2(this.getUniform(uniformName), array);
  21986. return this;
  21987. };
  21988. Effect.prototype.setIntArray3 = function (uniformName, array) {
  21989. this._valueCache[uniformName] = null;
  21990. this._engine.setIntArray3(this.getUniform(uniformName), array);
  21991. return this;
  21992. };
  21993. Effect.prototype.setIntArray4 = function (uniformName, array) {
  21994. this._valueCache[uniformName] = null;
  21995. this._engine.setIntArray4(this.getUniform(uniformName), array);
  21996. return this;
  21997. };
  21998. Effect.prototype.setFloatArray = function (uniformName, array) {
  21999. this._valueCache[uniformName] = null;
  22000. this._engine.setFloatArray(this.getUniform(uniformName), array);
  22001. return this;
  22002. };
  22003. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  22004. this._valueCache[uniformName] = null;
  22005. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  22006. return this;
  22007. };
  22008. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  22009. this._valueCache[uniformName] = null;
  22010. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  22011. return this;
  22012. };
  22013. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  22014. this._valueCache[uniformName] = null;
  22015. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  22016. return this;
  22017. };
  22018. Effect.prototype.setArray = function (uniformName, array) {
  22019. this._valueCache[uniformName] = null;
  22020. this._engine.setArray(this.getUniform(uniformName), array);
  22021. return this;
  22022. };
  22023. Effect.prototype.setArray2 = function (uniformName, array) {
  22024. this._valueCache[uniformName] = null;
  22025. this._engine.setArray2(this.getUniform(uniformName), array);
  22026. return this;
  22027. };
  22028. Effect.prototype.setArray3 = function (uniformName, array) {
  22029. this._valueCache[uniformName] = null;
  22030. this._engine.setArray3(this.getUniform(uniformName), array);
  22031. return this;
  22032. };
  22033. Effect.prototype.setArray4 = function (uniformName, array) {
  22034. this._valueCache[uniformName] = null;
  22035. this._engine.setArray4(this.getUniform(uniformName), array);
  22036. return this;
  22037. };
  22038. Effect.prototype.setMatrices = function (uniformName, matrices) {
  22039. if (!matrices) {
  22040. return;
  22041. }
  22042. this._valueCache[uniformName] = null;
  22043. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  22044. return this;
  22045. };
  22046. Effect.prototype.setMatrix = function (uniformName, matrix) {
  22047. if (this._cacheMatrix(uniformName, matrix)) {
  22048. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  22049. }
  22050. return this;
  22051. };
  22052. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  22053. this._valueCache[uniformName] = null;
  22054. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  22055. return this;
  22056. };
  22057. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  22058. this._valueCache[uniformName] = null;
  22059. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  22060. return this;
  22061. };
  22062. Effect.prototype.setFloat = function (uniformName, value) {
  22063. var cache = this._valueCache[uniformName];
  22064. if (cache !== undefined && cache === value)
  22065. return this;
  22066. this._valueCache[uniformName] = value;
  22067. this._engine.setFloat(this.getUniform(uniformName), value);
  22068. return this;
  22069. };
  22070. Effect.prototype.setBool = function (uniformName, bool) {
  22071. var cache = this._valueCache[uniformName];
  22072. if (cache !== undefined && cache === bool)
  22073. return this;
  22074. this._valueCache[uniformName] = bool;
  22075. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  22076. return this;
  22077. };
  22078. Effect.prototype.setVector2 = function (uniformName, vector2) {
  22079. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  22080. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  22081. }
  22082. return this;
  22083. };
  22084. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  22085. if (this._cacheFloat2(uniformName, x, y)) {
  22086. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  22087. }
  22088. return this;
  22089. };
  22090. Effect.prototype.setVector3 = function (uniformName, vector3) {
  22091. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  22092. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  22093. }
  22094. return this;
  22095. };
  22096. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  22097. if (this._cacheFloat3(uniformName, x, y, z)) {
  22098. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  22099. }
  22100. return this;
  22101. };
  22102. Effect.prototype.setVector4 = function (uniformName, vector4) {
  22103. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  22104. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  22105. }
  22106. return this;
  22107. };
  22108. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  22109. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  22110. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  22111. }
  22112. return this;
  22113. };
  22114. Effect.prototype.setColor3 = function (uniformName, color3) {
  22115. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  22116. this._engine.setColor3(this.getUniform(uniformName), color3);
  22117. }
  22118. return this;
  22119. };
  22120. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  22121. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  22122. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  22123. }
  22124. return this;
  22125. };
  22126. Effect.prototype._recombineShader = function (node) {
  22127. if (node.define) {
  22128. if (node.condition) {
  22129. var defineIndex = this.defines.indexOf("#define " + node.define);
  22130. if (defineIndex === -1) {
  22131. return null;
  22132. }
  22133. var nextComma = this.defines.indexOf("\n", defineIndex);
  22134. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  22135. var condition = defineValue + node.condition;
  22136. if (!eval(condition)) {
  22137. return null;
  22138. }
  22139. }
  22140. else if (node.ndef) {
  22141. if (this.defines.indexOf("#define " + node.define) !== -1) {
  22142. return null;
  22143. }
  22144. }
  22145. else if (this.defines.indexOf("#define " + node.define) === -1) {
  22146. return null;
  22147. }
  22148. }
  22149. var result = "";
  22150. for (var index = 0; index < node.children.length; index++) {
  22151. var line = node.children[index];
  22152. if (line.children) {
  22153. var combined = this._recombineShader(line);
  22154. if (combined !== null) {
  22155. result += combined + "\r\n";
  22156. }
  22157. continue;
  22158. }
  22159. if (line.length > 0) {
  22160. result += line + "\r\n";
  22161. }
  22162. }
  22163. return result;
  22164. };
  22165. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  22166. var root = {
  22167. children: []
  22168. };
  22169. var currentNode = root;
  22170. var lines = shaderString.split("\n");
  22171. for (var index = 0; index < lines.length; index++) {
  22172. var line = lines[index].trim();
  22173. // #ifdef
  22174. var pos = line.indexOf("#ifdef ");
  22175. if (pos !== -1) {
  22176. var define = line.substr(pos + 7);
  22177. var newNode = {
  22178. condition: null,
  22179. ndef: false,
  22180. define: define,
  22181. children: [],
  22182. parent: currentNode
  22183. };
  22184. currentNode.children.push(newNode);
  22185. currentNode = newNode;
  22186. continue;
  22187. }
  22188. // #ifndef
  22189. var pos = line.indexOf("#ifndef ");
  22190. if (pos !== -1) {
  22191. var define = line.substr(pos + 8);
  22192. newNode = {
  22193. condition: null,
  22194. define: define,
  22195. ndef: true,
  22196. children: [],
  22197. parent: currentNode
  22198. };
  22199. currentNode.children.push(newNode);
  22200. currentNode = newNode;
  22201. continue;
  22202. }
  22203. // #if
  22204. var pos = line.indexOf("#if ");
  22205. if (pos !== -1) {
  22206. var define = line.substr(pos + 4).trim();
  22207. var conditionPos = define.indexOf(" ");
  22208. newNode = {
  22209. condition: define.substr(conditionPos + 1),
  22210. define: define.substr(0, conditionPos),
  22211. ndef: false,
  22212. children: [],
  22213. parent: currentNode
  22214. };
  22215. currentNode.children.push(newNode);
  22216. currentNode = newNode;
  22217. continue;
  22218. }
  22219. // #endif
  22220. pos = line.indexOf("#endif");
  22221. if (pos !== -1) {
  22222. currentNode = currentNode.parent;
  22223. continue;
  22224. }
  22225. currentNode.children.push(line);
  22226. }
  22227. // Recombine
  22228. return this._recombineShader(root);
  22229. };
  22230. return Effect;
  22231. }());
  22232. Effect._uniqueIdSeed = 0;
  22233. Effect._baseCache = {};
  22234. // Statics
  22235. Effect.ShadersStore = {};
  22236. Effect.IncludesShadersStore = {};
  22237. BABYLON.Effect = Effect;
  22238. })(BABYLON || (BABYLON = {}));
  22239. //# sourceMappingURL=babylon.effect.js.map
  22240. var BABYLON;
  22241. (function (BABYLON) {
  22242. var MaterialHelper = (function () {
  22243. function MaterialHelper() {
  22244. }
  22245. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  22246. if (defines._areMiscDirty) {
  22247. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  22248. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  22249. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  22250. }
  22251. };
  22252. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  22253. var changed = false;
  22254. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  22255. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  22256. changed = true;
  22257. }
  22258. if (defines["ALPHATEST"] !== engine.getAlphaTesting()) {
  22259. defines["ALPHATEST"] = !defines["ALPHATEST"];
  22260. changed = true;
  22261. }
  22262. if (defines["INSTANCES"] !== useInstances) {
  22263. defines["INSTANCES"] = useInstances;
  22264. changed = true;
  22265. }
  22266. if (changed) {
  22267. defines.markAsUnprocessed();
  22268. }
  22269. };
  22270. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  22271. if (useMorphTargets === void 0) { useMorphTargets = false; }
  22272. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  22273. return;
  22274. }
  22275. defines._normals = defines._needNormals;
  22276. defines._uvs = defines._needUVs;
  22277. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  22278. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  22279. defines["TANGENT"] = true;
  22280. }
  22281. if (defines._needUVs) {
  22282. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  22283. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  22284. }
  22285. else {
  22286. defines["UV1"] = false;
  22287. defines["UV2"] = false;
  22288. }
  22289. if (useVertexColor) {
  22290. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  22291. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  22292. }
  22293. if (useBones) {
  22294. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  22295. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  22296. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  22297. }
  22298. else {
  22299. defines["NUM_BONE_INFLUENCERS"] = 0;
  22300. defines["BonesPerMesh"] = 0;
  22301. }
  22302. }
  22303. if (useMorphTargets) {
  22304. if (mesh.morphTargetManager) {
  22305. var manager = mesh.morphTargetManager;
  22306. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  22307. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  22308. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  22309. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  22310. }
  22311. else {
  22312. defines["MORPHTARGETS_TANGENT"] = false;
  22313. defines["MORPHTARGETS_NORMAL"] = false;
  22314. defines["MORPHTARGETS"] = false;
  22315. defines["NUM_MORPH_INFLUENCERS"] = 0;
  22316. }
  22317. }
  22318. };
  22319. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  22320. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22321. if (disableLighting === void 0) { disableLighting = false; }
  22322. if (!defines._areLightsDirty) {
  22323. return defines._needNormals;
  22324. }
  22325. var lightIndex = 0;
  22326. var needNormals = false;
  22327. var needRebuild = false;
  22328. var lightmapMode = false;
  22329. var shadowEnabled = false;
  22330. var specularEnabled = false;
  22331. if (scene.lightsEnabled && !disableLighting) {
  22332. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  22333. var light = _a[_i];
  22334. needNormals = true;
  22335. if (defines["LIGHT" + lightIndex] === undefined) {
  22336. needRebuild = true;
  22337. }
  22338. defines["LIGHT" + lightIndex] = true;
  22339. defines["SPOTLIGHT" + lightIndex] = false;
  22340. defines["HEMILIGHT" + lightIndex] = false;
  22341. defines["POINTLIGHT" + lightIndex] = false;
  22342. defines["DIRLIGHT" + lightIndex] = false;
  22343. var type;
  22344. if (light.getTypeID() === 2) {
  22345. type = "SPOTLIGHT" + lightIndex;
  22346. }
  22347. else if (light.getTypeID() === 3) {
  22348. type = "HEMILIGHT" + lightIndex;
  22349. }
  22350. else if (light.getTypeID() === 0) {
  22351. type = "POINTLIGHT" + lightIndex;
  22352. }
  22353. else {
  22354. type = "DIRLIGHT" + lightIndex;
  22355. }
  22356. defines[type] = true;
  22357. // Specular
  22358. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  22359. specularEnabled = true;
  22360. }
  22361. // Shadows
  22362. defines["SHADOW" + lightIndex] = false;
  22363. if (scene.shadowsEnabled) {
  22364. var shadowGenerator = light.getShadowGenerator();
  22365. if (mesh && mesh.receiveShadows && shadowGenerator) {
  22366. defines["SHADOW" + lightIndex] = true;
  22367. shadowEnabled = true;
  22368. defines["SHADOWPCF" + lightIndex] = false;
  22369. defines["SHADOWESM" + lightIndex] = false;
  22370. if (shadowGenerator.usePoissonSampling) {
  22371. defines["SHADOWPCF" + lightIndex] = true;
  22372. }
  22373. else if (shadowGenerator.useExponentialShadowMap || shadowGenerator.useBlurExponentialShadowMap) {
  22374. defines["SHADOWESM" + lightIndex] = true;
  22375. }
  22376. }
  22377. }
  22378. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  22379. lightmapMode = true;
  22380. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  22381. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  22382. }
  22383. else {
  22384. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  22385. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  22386. }
  22387. lightIndex++;
  22388. if (lightIndex === maxSimultaneousLights)
  22389. break;
  22390. }
  22391. }
  22392. defines["SPECULARTERM"] = specularEnabled;
  22393. defines["SHADOWS"] = shadowEnabled;
  22394. // Resetting all other lights if any
  22395. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  22396. if (defines["LIGHT" + index] !== undefined) {
  22397. defines["LIGHT" + index] = false;
  22398. }
  22399. }
  22400. var caps = scene.getEngine().getCaps();
  22401. if (defines["SHADOWFULLFLOAT"] === undefined) {
  22402. needRebuild = true;
  22403. }
  22404. defines["SHADOWFULLFLOAT"] = (shadowEnabled && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender);
  22405. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  22406. if (needRebuild) {
  22407. defines.rebuild();
  22408. }
  22409. return needNormals;
  22410. };
  22411. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  22412. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22413. var uniformsList, uniformBuffersList, samplersList, defines;
  22414. if (uniformsListOrOptions.uniformsNames) {
  22415. var options = uniformsListOrOptions;
  22416. uniformsList = options.uniformsNames;
  22417. uniformBuffersList = options.uniformBuffersNames;
  22418. samplersList = options.samplers;
  22419. defines = options.defines;
  22420. maxSimultaneousLights = options.maxSimultaneousLights;
  22421. }
  22422. else {
  22423. uniformsList = uniformsListOrOptions;
  22424. }
  22425. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22426. if (!defines["LIGHT" + lightIndex]) {
  22427. break;
  22428. }
  22429. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  22430. if (uniformBuffersList) {
  22431. uniformBuffersList.push("Light" + lightIndex);
  22432. }
  22433. samplersList.push("shadowSampler" + lightIndex);
  22434. }
  22435. if (defines["NUM_MORPH_INFLUENCERS"]) {
  22436. uniformsList.push("morphTargetInfluences");
  22437. }
  22438. };
  22439. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  22440. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22441. if (!defines["SHADOWS"]) {
  22442. return;
  22443. }
  22444. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22445. if (!defines["LIGHT" + lightIndex]) {
  22446. break;
  22447. }
  22448. if (lightIndex > 0) {
  22449. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22450. }
  22451. if (defines["SHADOW" + lightIndex]) {
  22452. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22453. }
  22454. if (defines["SHADOWPCF" + lightIndex]) {
  22455. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22456. }
  22457. if (defines["SHADOWESM" + lightIndex]) {
  22458. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  22459. }
  22460. }
  22461. };
  22462. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  22463. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  22464. if (influencers > 0) {
  22465. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  22466. var manager = mesh.morphTargetManager;
  22467. var normal = manager.supportsNormals && defines["NORMAL"];
  22468. var tangent = manager.supportsTangents && defines["TANGENT"];
  22469. for (var index = 0; index < influencers; index++) {
  22470. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  22471. if (normal) {
  22472. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  22473. }
  22474. if (tangent) {
  22475. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  22476. }
  22477. if (attribs.length > maxAttributesCount) {
  22478. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  22479. }
  22480. }
  22481. }
  22482. };
  22483. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22484. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22485. fallbacks.addCPUSkinningFallback(0, mesh);
  22486. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22487. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22488. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22489. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22490. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22491. }
  22492. }
  22493. };
  22494. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  22495. if (defines["INSTANCES"]) {
  22496. attribs.push("world0");
  22497. attribs.push("world1");
  22498. attribs.push("world2");
  22499. attribs.push("world3");
  22500. }
  22501. };
  22502. // Bindings
  22503. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  22504. var shadowGenerator = light.getShadowGenerator();
  22505. if (mesh.receiveShadows && shadowGenerator) {
  22506. if (!light.needCube()) {
  22507. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  22508. }
  22509. else {
  22510. if (!depthValuesAlreadySet) {
  22511. depthValuesAlreadySet = true;
  22512. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  22513. }
  22514. }
  22515. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  22516. light._uniformBuffer.updateFloat3("shadowsInfo", shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.depthScale, lightIndex);
  22517. }
  22518. return depthValuesAlreadySet;
  22519. };
  22520. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  22521. light.transferToEffect(effect, lightIndex + "");
  22522. };
  22523. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  22524. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22525. var lightIndex = 0;
  22526. var depthValuesAlreadySet = false;
  22527. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  22528. var light = _a[_i];
  22529. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  22530. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22531. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22532. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], light.range, lightIndex + "");
  22533. if (defines["SPECULARTERM"]) {
  22534. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22535. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  22536. }
  22537. // Shadows
  22538. if (scene.shadowsEnabled) {
  22539. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  22540. }
  22541. light._uniformBuffer.update();
  22542. lightIndex++;
  22543. if (lightIndex === maxSimultaneousLights)
  22544. break;
  22545. }
  22546. };
  22547. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22548. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22549. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22550. effect.setColor3("vFogColor", scene.fogColor);
  22551. }
  22552. };
  22553. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22554. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22555. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  22556. if (matrices) {
  22557. effect.setMatrices("mBones", matrices);
  22558. }
  22559. }
  22560. };
  22561. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  22562. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  22563. return;
  22564. }
  22565. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  22566. };
  22567. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22568. if (defines["LOGARITHMICDEPTH"]) {
  22569. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22570. }
  22571. };
  22572. MaterialHelper.BindClipPlane = function (effect, scene) {
  22573. if (scene.clipPlane) {
  22574. var clipPlane = scene.clipPlane;
  22575. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22576. }
  22577. };
  22578. return MaterialHelper;
  22579. }());
  22580. BABYLON.MaterialHelper = MaterialHelper;
  22581. })(BABYLON || (BABYLON = {}));
  22582. //# sourceMappingURL=babylon.materialHelper.js.map
  22583. var BABYLON;
  22584. (function (BABYLON) {
  22585. var MaterialDefines = (function () {
  22586. function MaterialDefines() {
  22587. this._isDirty = true;
  22588. this._areLightsDirty = true;
  22589. this._areAttributesDirty = true;
  22590. this._areTexturesDirty = true;
  22591. this._areFresnelDirty = true;
  22592. this._areMiscDirty = true;
  22593. this._normals = false;
  22594. this._uvs = false;
  22595. this._needNormals = false;
  22596. this._needUVs = false;
  22597. }
  22598. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  22599. get: function () {
  22600. return this._isDirty;
  22601. },
  22602. enumerable: true,
  22603. configurable: true
  22604. });
  22605. MaterialDefines.prototype.markAsProcessed = function () {
  22606. this._isDirty = false;
  22607. this._areAttributesDirty = false;
  22608. this._areTexturesDirty = false;
  22609. this._areFresnelDirty = false;
  22610. this._areLightsDirty = false;
  22611. this._areMiscDirty = false;
  22612. };
  22613. MaterialDefines.prototype.markAsUnprocessed = function () {
  22614. this._isDirty = true;
  22615. };
  22616. MaterialDefines.prototype.markAllAsDirty = function () {
  22617. this._areTexturesDirty = true;
  22618. this._areAttributesDirty = true;
  22619. this._areLightsDirty = true;
  22620. this._areFresnelDirty = true;
  22621. this._areMiscDirty = true;
  22622. this._isDirty = true;
  22623. };
  22624. MaterialDefines.prototype.markAsLightDirty = function () {
  22625. this._areLightsDirty = true;
  22626. this._isDirty = true;
  22627. };
  22628. MaterialDefines.prototype.markAsAttributesDirty = function () {
  22629. this._areAttributesDirty = true;
  22630. this._isDirty = true;
  22631. };
  22632. MaterialDefines.prototype.markAsTexturesDirty = function () {
  22633. this._areTexturesDirty = true;
  22634. this._isDirty = true;
  22635. };
  22636. MaterialDefines.prototype.markAsFresnelDirty = function () {
  22637. this._areFresnelDirty = true;
  22638. this._isDirty = true;
  22639. };
  22640. MaterialDefines.prototype.markAsMiscDirty = function () {
  22641. this._areMiscDirty = true;
  22642. this._isDirty = true;
  22643. };
  22644. MaterialDefines.prototype.rebuild = function () {
  22645. if (this._keys) {
  22646. delete this._keys;
  22647. }
  22648. this._keys = [];
  22649. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  22650. var key = _a[_i];
  22651. if (key[0] === "_") {
  22652. continue;
  22653. }
  22654. this._keys.push(key);
  22655. }
  22656. };
  22657. MaterialDefines.prototype.isEqual = function (other) {
  22658. if (this._keys.length !== other._keys.length) {
  22659. return false;
  22660. }
  22661. for (var index = 0; index < this._keys.length; index++) {
  22662. var prop = this._keys[index];
  22663. if (this[prop] !== other[prop]) {
  22664. return false;
  22665. }
  22666. }
  22667. return true;
  22668. };
  22669. MaterialDefines.prototype.cloneTo = function (other) {
  22670. if (this._keys.length !== other._keys.length) {
  22671. other._keys = this._keys.slice(0);
  22672. }
  22673. for (var index = 0; index < this._keys.length; index++) {
  22674. var prop = this._keys[index];
  22675. other[prop] = this[prop];
  22676. }
  22677. };
  22678. MaterialDefines.prototype.reset = function () {
  22679. for (var index = 0; index < this._keys.length; index++) {
  22680. var prop = this._keys[index];
  22681. if (typeof (this[prop]) === "number") {
  22682. this[prop] = 0;
  22683. }
  22684. else {
  22685. this[prop] = false;
  22686. }
  22687. }
  22688. };
  22689. MaterialDefines.prototype.toString = function () {
  22690. var result = "";
  22691. for (var index = 0; index < this._keys.length; index++) {
  22692. var prop = this._keys[index];
  22693. var value = this[prop];
  22694. if (typeof (value) === "number") {
  22695. result += "#define " + prop + " " + this[prop] + "\n";
  22696. }
  22697. else if (value) {
  22698. result += "#define " + prop + "\n";
  22699. }
  22700. }
  22701. return result;
  22702. };
  22703. return MaterialDefines;
  22704. }());
  22705. BABYLON.MaterialDefines = MaterialDefines;
  22706. var Material = (function () {
  22707. function Material(name, scene, doNotAdd) {
  22708. this.checkReadyOnEveryCall = false;
  22709. this.checkReadyOnlyOnce = false;
  22710. this.state = "";
  22711. this.alpha = 1.0;
  22712. this._backFaceCulling = true;
  22713. this.doNotSerialize = false;
  22714. this.storeEffectOnSubMeshes = false;
  22715. /**
  22716. * An event triggered when the material is disposed.
  22717. * @type {BABYLON.Observable}
  22718. */
  22719. this.onDisposeObservable = new BABYLON.Observable();
  22720. /**
  22721. * An event triggered when the material is bound.
  22722. * @type {BABYLON.Observable}
  22723. */
  22724. this.onBindObservable = new BABYLON.Observable();
  22725. /**
  22726. * An event triggered when the material is unbound.
  22727. * @type {BABYLON.Observable}
  22728. */
  22729. this.onUnBindObservable = new BABYLON.Observable();
  22730. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22731. this.disableDepthWrite = false;
  22732. this._fogEnabled = true;
  22733. this.pointSize = 1.0;
  22734. this.zOffset = 0;
  22735. this._wasPreviouslyReady = false;
  22736. this._fillMode = Material.TriangleFillMode;
  22737. this.name = name;
  22738. this.id = name;
  22739. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22740. if (this._scene.useRightHandedSystem) {
  22741. this.sideOrientation = Material.ClockWiseSideOrientation;
  22742. }
  22743. else {
  22744. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22745. }
  22746. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  22747. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  22748. if (!doNotAdd) {
  22749. this._scene.materials.push(this);
  22750. }
  22751. }
  22752. Object.defineProperty(Material, "TriangleFillMode", {
  22753. get: function () {
  22754. return Material._TriangleFillMode;
  22755. },
  22756. enumerable: true,
  22757. configurable: true
  22758. });
  22759. Object.defineProperty(Material, "WireFrameFillMode", {
  22760. get: function () {
  22761. return Material._WireFrameFillMode;
  22762. },
  22763. enumerable: true,
  22764. configurable: true
  22765. });
  22766. Object.defineProperty(Material, "PointFillMode", {
  22767. get: function () {
  22768. return Material._PointFillMode;
  22769. },
  22770. enumerable: true,
  22771. configurable: true
  22772. });
  22773. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22774. get: function () {
  22775. return Material._ClockWiseSideOrientation;
  22776. },
  22777. enumerable: true,
  22778. configurable: true
  22779. });
  22780. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22781. get: function () {
  22782. return Material._CounterClockWiseSideOrientation;
  22783. },
  22784. enumerable: true,
  22785. configurable: true
  22786. });
  22787. Object.defineProperty(Material, "TextureDirtyFlag", {
  22788. get: function () {
  22789. return Material._TextureDirtyFlag;
  22790. },
  22791. enumerable: true,
  22792. configurable: true
  22793. });
  22794. Object.defineProperty(Material, "LightDirtyFlag", {
  22795. get: function () {
  22796. return Material._LightDirtyFlag;
  22797. },
  22798. enumerable: true,
  22799. configurable: true
  22800. });
  22801. Object.defineProperty(Material, "FresnelDirtyFlag", {
  22802. get: function () {
  22803. return Material._FresnelDirtyFlag;
  22804. },
  22805. enumerable: true,
  22806. configurable: true
  22807. });
  22808. Object.defineProperty(Material, "AttributesDirtyFlag", {
  22809. get: function () {
  22810. return Material._AttributesDirtyFlag;
  22811. },
  22812. enumerable: true,
  22813. configurable: true
  22814. });
  22815. Object.defineProperty(Material, "MiscDirtyFlag", {
  22816. get: function () {
  22817. return Material._MiscDirtyFlag;
  22818. },
  22819. enumerable: true,
  22820. configurable: true
  22821. });
  22822. Object.defineProperty(Material.prototype, "backFaceCulling", {
  22823. get: function () {
  22824. return this._backFaceCulling;
  22825. },
  22826. set: function (value) {
  22827. if (this._backFaceCulling === value) {
  22828. return;
  22829. }
  22830. this._backFaceCulling = value;
  22831. this.markAsDirty(Material.TextureDirtyFlag);
  22832. },
  22833. enumerable: true,
  22834. configurable: true
  22835. });
  22836. Object.defineProperty(Material.prototype, "onDispose", {
  22837. set: function (callback) {
  22838. if (this._onDisposeObserver) {
  22839. this.onDisposeObservable.remove(this._onDisposeObserver);
  22840. }
  22841. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22842. },
  22843. enumerable: true,
  22844. configurable: true
  22845. });
  22846. Object.defineProperty(Material.prototype, "onBind", {
  22847. set: function (callback) {
  22848. if (this._onBindObserver) {
  22849. this.onBindObservable.remove(this._onBindObserver);
  22850. }
  22851. this._onBindObserver = this.onBindObservable.add(callback);
  22852. },
  22853. enumerable: true,
  22854. configurable: true
  22855. });
  22856. Object.defineProperty(Material.prototype, "fogEnabled", {
  22857. get: function () {
  22858. return this._fogEnabled;
  22859. },
  22860. set: function (value) {
  22861. if (this._fogEnabled === value) {
  22862. return;
  22863. }
  22864. this._fogEnabled = value;
  22865. this.markAsDirty(Material.MiscDirtyFlag);
  22866. },
  22867. enumerable: true,
  22868. configurable: true
  22869. });
  22870. Object.defineProperty(Material.prototype, "wireframe", {
  22871. get: function () {
  22872. return this._fillMode === Material.WireFrameFillMode;
  22873. },
  22874. set: function (value) {
  22875. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22876. },
  22877. enumerable: true,
  22878. configurable: true
  22879. });
  22880. Object.defineProperty(Material.prototype, "pointsCloud", {
  22881. get: function () {
  22882. return this._fillMode === Material.PointFillMode;
  22883. },
  22884. set: function (value) {
  22885. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22886. },
  22887. enumerable: true,
  22888. configurable: true
  22889. });
  22890. Object.defineProperty(Material.prototype, "fillMode", {
  22891. get: function () {
  22892. return this._fillMode;
  22893. },
  22894. set: function (value) {
  22895. if (this._fillMode === value) {
  22896. return;
  22897. }
  22898. this._fillMode = value;
  22899. this.markAsDirty(Material.MiscDirtyFlag);
  22900. },
  22901. enumerable: true,
  22902. configurable: true
  22903. });
  22904. /**
  22905. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22906. * subclasses should override adding information pertainent to themselves
  22907. */
  22908. Material.prototype.toString = function (fullDetails) {
  22909. var ret = "Name: " + this.name;
  22910. if (fullDetails) {
  22911. }
  22912. return ret;
  22913. };
  22914. /**
  22915. * Child classes can use it to update shaders
  22916. */
  22917. Material.prototype.markAsDirty = function (flag) {
  22918. };
  22919. Material.prototype.getClassName = function () {
  22920. return "Material";
  22921. };
  22922. Object.defineProperty(Material.prototype, "isFrozen", {
  22923. get: function () {
  22924. return this.checkReadyOnlyOnce;
  22925. },
  22926. enumerable: true,
  22927. configurable: true
  22928. });
  22929. Material.prototype.freeze = function () {
  22930. this.checkReadyOnlyOnce = true;
  22931. };
  22932. Material.prototype.unfreeze = function () {
  22933. this.checkReadyOnlyOnce = false;
  22934. };
  22935. Material.prototype.isReady = function (mesh, useInstances) {
  22936. return true;
  22937. };
  22938. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  22939. return false;
  22940. };
  22941. Material.prototype.getEffect = function () {
  22942. return this._effect;
  22943. };
  22944. Material.prototype.getScene = function () {
  22945. return this._scene;
  22946. };
  22947. Material.prototype.needAlphaBlending = function () {
  22948. return (this.alpha < 1.0);
  22949. };
  22950. Material.prototype.needAlphaTesting = function () {
  22951. return false;
  22952. };
  22953. Material.prototype.getAlphaTestTexture = function () {
  22954. return null;
  22955. };
  22956. Material.prototype.markDirty = function () {
  22957. this._wasPreviouslyReady = false;
  22958. };
  22959. Material.prototype._preBind = function (effect) {
  22960. var engine = this._scene.getEngine();
  22961. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  22962. engine.enableEffect(effect ? effect : this._effect);
  22963. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  22964. };
  22965. Material.prototype.bind = function (world, mesh) {
  22966. };
  22967. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  22968. };
  22969. Material.prototype.bindOnlyWorldMatrix = function (world) {
  22970. };
  22971. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  22972. sceneUbo.bindToEffect(effect, "Scene");
  22973. };
  22974. Material.prototype.bindView = function (effect) {
  22975. if (!this._useUBO) {
  22976. effect.setMatrix("view", this.getScene().getViewMatrix());
  22977. }
  22978. else {
  22979. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  22980. }
  22981. };
  22982. Material.prototype.bindViewProjection = function (effect) {
  22983. if (!this._useUBO) {
  22984. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  22985. }
  22986. else {
  22987. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  22988. }
  22989. };
  22990. Material.prototype._afterBind = function (mesh) {
  22991. this._scene._cachedMaterial = this;
  22992. this.onBindObservable.notifyObservers(mesh);
  22993. if (this.disableDepthWrite) {
  22994. var engine = this._scene.getEngine();
  22995. this._cachedDepthWriteState = engine.getDepthWrite();
  22996. engine.setDepthWrite(false);
  22997. }
  22998. };
  22999. Material.prototype.unbind = function () {
  23000. this.onUnBindObservable.notifyObservers(this);
  23001. if (this.disableDepthWrite) {
  23002. var engine = this._scene.getEngine();
  23003. engine.setDepthWrite(this._cachedDepthWriteState);
  23004. }
  23005. };
  23006. Material.prototype.clone = function (name) {
  23007. return null;
  23008. };
  23009. Material.prototype.getBindedMeshes = function () {
  23010. var result = new Array();
  23011. for (var index = 0; index < this._scene.meshes.length; index++) {
  23012. var mesh = this._scene.meshes[index];
  23013. if (mesh.material === this) {
  23014. result.push(mesh);
  23015. }
  23016. }
  23017. return result;
  23018. };
  23019. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  23020. // Animations
  23021. this.getScene().stopAnimation(this);
  23022. // Remove from scene
  23023. var index = this._scene.materials.indexOf(this);
  23024. if (index >= 0) {
  23025. this._scene.materials.splice(index, 1);
  23026. }
  23027. // Remove from meshes
  23028. for (index = 0; index < this._scene.meshes.length; index++) {
  23029. var mesh = this._scene.meshes[index];
  23030. if (mesh.material === this) {
  23031. mesh.material = null;
  23032. if (mesh.geometry) {
  23033. var geometry = mesh.geometry;
  23034. if (this.storeEffectOnSubMeshes) {
  23035. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  23036. var subMesh = _a[_i];
  23037. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  23038. }
  23039. }
  23040. else {
  23041. geometry._releaseVertexArrayObject(this._effect);
  23042. }
  23043. }
  23044. }
  23045. }
  23046. this._uniformBuffer.dispose();
  23047. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  23048. if (forceDisposeEffect && this._effect) {
  23049. if (this.storeEffectOnSubMeshes) {
  23050. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23051. var subMesh = _c[_b];
  23052. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  23053. }
  23054. }
  23055. else {
  23056. this._scene.getEngine()._releaseEffect(this._effect);
  23057. }
  23058. this._effect = null;
  23059. }
  23060. // Callback
  23061. this.onDisposeObservable.notifyObservers(this);
  23062. this.onDisposeObservable.clear();
  23063. this.onBindObservable.clear();
  23064. this.onUnBindObservable.clear();
  23065. };
  23066. Material.prototype.serialize = function () {
  23067. return BABYLON.SerializationHelper.Serialize(this);
  23068. };
  23069. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  23070. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  23071. multiMaterial.id = parsedMultiMaterial.id;
  23072. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  23073. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  23074. var subMatId = parsedMultiMaterial.materials[matIndex];
  23075. if (subMatId) {
  23076. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  23077. }
  23078. else {
  23079. multiMaterial.subMaterials.push(null);
  23080. }
  23081. }
  23082. return multiMaterial;
  23083. };
  23084. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  23085. if (!parsedMaterial.customType) {
  23086. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  23087. }
  23088. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  23089. return materialType.Parse(parsedMaterial, scene, rootUrl);
  23090. ;
  23091. };
  23092. return Material;
  23093. }());
  23094. Material._TriangleFillMode = 0;
  23095. Material._WireFrameFillMode = 1;
  23096. Material._PointFillMode = 2;
  23097. Material._ClockWiseSideOrientation = 0;
  23098. Material._CounterClockWiseSideOrientation = 1;
  23099. Material._TextureDirtyFlag = 0;
  23100. Material._LightDirtyFlag = 1;
  23101. Material._FresnelDirtyFlag = 2;
  23102. Material._AttributesDirtyFlag = 4;
  23103. Material._MiscDirtyFlag = 8;
  23104. __decorate([
  23105. BABYLON.serialize()
  23106. ], Material.prototype, "id", void 0);
  23107. __decorate([
  23108. BABYLON.serialize()
  23109. ], Material.prototype, "name", void 0);
  23110. __decorate([
  23111. BABYLON.serialize()
  23112. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  23113. __decorate([
  23114. BABYLON.serialize()
  23115. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  23116. __decorate([
  23117. BABYLON.serialize()
  23118. ], Material.prototype, "state", void 0);
  23119. __decorate([
  23120. BABYLON.serialize()
  23121. ], Material.prototype, "alpha", void 0);
  23122. __decorate([
  23123. BABYLON.serialize("backFaceCulling")
  23124. ], Material.prototype, "_backFaceCulling", void 0);
  23125. __decorate([
  23126. BABYLON.serialize()
  23127. ], Material.prototype, "sideOrientation", void 0);
  23128. __decorate([
  23129. BABYLON.serialize()
  23130. ], Material.prototype, "alphaMode", void 0);
  23131. __decorate([
  23132. BABYLON.serialize()
  23133. ], Material.prototype, "disableDepthWrite", void 0);
  23134. __decorate([
  23135. BABYLON.serialize("fogEnabled")
  23136. ], Material.prototype, "_fogEnabled", void 0);
  23137. __decorate([
  23138. BABYLON.serialize()
  23139. ], Material.prototype, "pointSize", void 0);
  23140. __decorate([
  23141. BABYLON.serialize()
  23142. ], Material.prototype, "zOffset", void 0);
  23143. __decorate([
  23144. BABYLON.serialize()
  23145. ], Material.prototype, "wireframe", null);
  23146. __decorate([
  23147. BABYLON.serialize()
  23148. ], Material.prototype, "pointsCloud", null);
  23149. __decorate([
  23150. BABYLON.serialize()
  23151. ], Material.prototype, "fillMode", null);
  23152. BABYLON.Material = Material;
  23153. })(BABYLON || (BABYLON = {}));
  23154. //# sourceMappingURL=babylon.material.js.map
  23155. var BABYLON;
  23156. (function (BABYLON) {
  23157. var UniformBuffer = (function () {
  23158. /**
  23159. * Uniform buffer objects.
  23160. *
  23161. * Handles blocks of uniform on the GPU.
  23162. *
  23163. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  23164. *
  23165. * For more information, please refer to :
  23166. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  23167. */
  23168. function UniformBuffer(engine, data, dynamic) {
  23169. this._engine = engine;
  23170. this._noUBO = engine.webGLVersion === 1;
  23171. this._dynamic = dynamic;
  23172. this._data = data || [];
  23173. this._uniformLocations = {};
  23174. this._uniformSizes = {};
  23175. this._uniformLocationPointer = 0;
  23176. this._needSync = false;
  23177. if (this._noUBO) {
  23178. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  23179. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  23180. this.updateFloat = this._updateFloatForEffect;
  23181. this.updateFloat2 = this._updateFloat2ForEffect;
  23182. this.updateFloat3 = this._updateFloat3ForEffect;
  23183. this.updateFloat4 = this._updateFloat4ForEffect;
  23184. this.updateMatrix = this._updateMatrixForEffect;
  23185. this.updateVector3 = this._updateVector3ForEffect;
  23186. this.updateVector4 = this._updateVector4ForEffect;
  23187. this.updateColor3 = this._updateColor3ForEffect;
  23188. this.updateColor4 = this._updateColor4ForEffect;
  23189. }
  23190. else {
  23191. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  23192. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  23193. this.updateFloat = this._updateFloatForUniform;
  23194. this.updateFloat2 = this._updateFloat2ForUniform;
  23195. this.updateFloat3 = this._updateFloat3ForUniform;
  23196. this.updateFloat4 = this._updateFloat4ForUniform;
  23197. this.updateMatrix = this._updateMatrixForUniform;
  23198. this.updateVector3 = this._updateVector3ForUniform;
  23199. this.updateVector4 = this._updateVector4ForUniform;
  23200. this.updateColor3 = this._updateColor3ForUniform;
  23201. this.updateColor4 = this._updateColor4ForUniform;
  23202. }
  23203. }
  23204. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  23205. // Properties
  23206. /**
  23207. * Indicates if the buffer is using the WebGL2 UBO implementation,
  23208. * or just falling back on setUniformXXX calls.
  23209. */
  23210. get: function () {
  23211. return !this._noUBO;
  23212. },
  23213. enumerable: true,
  23214. configurable: true
  23215. });
  23216. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  23217. /**
  23218. * Indicates if the WebGL underlying uniform buffer is in sync
  23219. * with the javascript cache data.
  23220. */
  23221. get: function () {
  23222. return !this._needSync;
  23223. },
  23224. enumerable: true,
  23225. configurable: true
  23226. });
  23227. /**
  23228. * Indicates if the WebGL underlying uniform buffer is dynamic.
  23229. * Also, a dynamic UniformBuffer will disable cache verification and always
  23230. * update the underlying WebGL uniform buffer to the GPU.
  23231. */
  23232. UniformBuffer.prototype.isDynamic = function () {
  23233. return this._dynamic;
  23234. };
  23235. /**
  23236. * The data cache on JS side.
  23237. */
  23238. UniformBuffer.prototype.getData = function () {
  23239. return this._bufferData;
  23240. };
  23241. /**
  23242. * The underlying WebGL Uniform buffer.
  23243. */
  23244. UniformBuffer.prototype.getBuffer = function () {
  23245. return this._buffer;
  23246. };
  23247. /**
  23248. * std140 layout specifies how to align data within an UBO structure.
  23249. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  23250. * for specs.
  23251. */
  23252. UniformBuffer.prototype._fillAlignment = function (size) {
  23253. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  23254. // and 4x4 matrices
  23255. // TODO : change if other types are used
  23256. var alignment;
  23257. if (size <= 2) {
  23258. alignment = size;
  23259. }
  23260. else {
  23261. alignment = 4;
  23262. }
  23263. if ((this._uniformLocationPointer % alignment) !== 0) {
  23264. var oldPointer = this._uniformLocationPointer;
  23265. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  23266. var diff = this._uniformLocationPointer - oldPointer;
  23267. for (var i = 0; i < diff; i++) {
  23268. this._data.push(0);
  23269. }
  23270. }
  23271. };
  23272. /**
  23273. * Adds an uniform in the buffer.
  23274. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  23275. * for the layout to be correct !
  23276. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23277. * @param {number|number[]} size Data size, or data directly.
  23278. */
  23279. UniformBuffer.prototype.addUniform = function (name, size) {
  23280. if (this._noUBO) {
  23281. return;
  23282. }
  23283. if (this._uniformLocations[name] !== undefined) {
  23284. // Already existing uniform
  23285. return;
  23286. }
  23287. // This function must be called in the order of the shader layout !
  23288. // size can be the size of the uniform, or data directly
  23289. var data;
  23290. if (size instanceof Array) {
  23291. data = size;
  23292. size = data.length;
  23293. }
  23294. else {
  23295. size = size;
  23296. data = [];
  23297. // Fill with zeros
  23298. for (var i = 0; i < size; i++) {
  23299. data.push(0);
  23300. }
  23301. }
  23302. this._fillAlignment(size);
  23303. this._uniformSizes[name] = size;
  23304. this._uniformLocations[name] = this._uniformLocationPointer;
  23305. this._uniformLocationPointer += size;
  23306. for (var i = 0; i < size; i++) {
  23307. this._data.push(data[i]);
  23308. }
  23309. this._needSync = true;
  23310. };
  23311. /**
  23312. * Wrapper for addUniform.
  23313. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23314. * @param {Matrix} mat A 4x4 matrix.
  23315. */
  23316. UniformBuffer.prototype.addMatrix = function (name, mat) {
  23317. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  23318. };
  23319. /**
  23320. * Wrapper for addUniform.
  23321. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23322. * @param {number} x
  23323. * @param {number} y
  23324. */
  23325. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  23326. var temp = [x, y];
  23327. this.addUniform(name, temp);
  23328. };
  23329. /**
  23330. * Wrapper for addUniform.
  23331. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23332. * @param {number} x
  23333. * @param {number} y
  23334. * @param {number} z
  23335. */
  23336. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  23337. var temp = [x, y, z];
  23338. this.addUniform(name, temp);
  23339. };
  23340. /**
  23341. * Wrapper for addUniform.
  23342. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23343. * @param {Color3} color
  23344. */
  23345. UniformBuffer.prototype.addColor3 = function (name, color) {
  23346. var temp = [];
  23347. color.toArray(temp);
  23348. this.addUniform(name, temp);
  23349. };
  23350. /**
  23351. * Wrapper for addUniform.
  23352. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23353. * @param {Color3} color
  23354. * @param {number} alpha
  23355. */
  23356. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  23357. var temp = [];
  23358. color.toArray(temp);
  23359. temp.push(alpha);
  23360. this.addUniform(name, temp);
  23361. };
  23362. /**
  23363. * Wrapper for addUniform.
  23364. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23365. * @param {Vector3} vector
  23366. */
  23367. UniformBuffer.prototype.addVector3 = function (name, vector) {
  23368. var temp = [];
  23369. vector.toArray(temp);
  23370. this.addUniform(name, temp);
  23371. };
  23372. /**
  23373. * Wrapper for addUniform.
  23374. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23375. */
  23376. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  23377. this.addUniform(name, 12);
  23378. };
  23379. /**
  23380. * Wrapper for addUniform.
  23381. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23382. */
  23383. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  23384. this.addUniform(name, 8);
  23385. };
  23386. /**
  23387. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  23388. */
  23389. UniformBuffer.prototype.create = function () {
  23390. if (this._noUBO) {
  23391. return;
  23392. }
  23393. if (this._buffer) {
  23394. return; // nothing to do
  23395. }
  23396. // See spec, alignment must be filled as a vec4
  23397. this._fillAlignment(4);
  23398. this._bufferData = new Float32Array(this._data);
  23399. if (this._dynamic) {
  23400. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  23401. }
  23402. else {
  23403. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  23404. }
  23405. this._needSync = true;
  23406. };
  23407. /**
  23408. * Updates the WebGL Uniform Buffer on the GPU.
  23409. * If the `dynamic` flag is set to true, no cache comparison is done.
  23410. * Otherwise, the buffer will be updated only if the cache differs.
  23411. */
  23412. UniformBuffer.prototype.update = function () {
  23413. if (!this._buffer) {
  23414. this.create();
  23415. return;
  23416. }
  23417. if (!this._dynamic && !this._needSync) {
  23418. return;
  23419. }
  23420. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  23421. this._needSync = false;
  23422. };
  23423. /**
  23424. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  23425. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  23426. * @param {number[]|Float32Array} data Flattened data
  23427. * @param {number} size Size of the data.
  23428. */
  23429. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  23430. var location = this._uniformLocations[uniformName];
  23431. if (location === undefined) {
  23432. if (this._buffer) {
  23433. // Cannot add an uniform if the buffer is already created
  23434. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  23435. return;
  23436. }
  23437. this.addUniform(uniformName, size);
  23438. location = this._uniformLocations[uniformName];
  23439. }
  23440. if (!this._buffer) {
  23441. this.create();
  23442. }
  23443. if (!this._dynamic) {
  23444. // Cache for static uniform buffers
  23445. var changed = false;
  23446. for (var i = 0; i < size; i++) {
  23447. if (this._bufferData[location + i] !== data[i]) {
  23448. changed = true;
  23449. this._bufferData[location + i] = data[i];
  23450. }
  23451. }
  23452. this._needSync = this._needSync || changed;
  23453. }
  23454. else {
  23455. // No cache for dynamic
  23456. for (var i = 0; i < size; i++) {
  23457. this._bufferData[location + i] = data[i];
  23458. }
  23459. }
  23460. };
  23461. // Update methods
  23462. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  23463. // To match std140, matrix must be realigned
  23464. for (var i = 0; i < 3; i++) {
  23465. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  23466. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  23467. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  23468. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  23469. }
  23470. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  23471. };
  23472. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  23473. this._currentEffect.setMatrix3x3(name, matrix);
  23474. };
  23475. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  23476. this._currentEffect.setMatrix2x2(name, matrix);
  23477. };
  23478. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  23479. // To match std140, matrix must be realigned
  23480. for (var i = 0; i < 2; i++) {
  23481. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  23482. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  23483. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  23484. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  23485. }
  23486. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  23487. };
  23488. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  23489. this._currentEffect.setFloat(name, x);
  23490. };
  23491. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  23492. UniformBuffer._tempBuffer[0] = x;
  23493. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  23494. };
  23495. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y) {
  23496. this._currentEffect.setFloat2(name, x, y);
  23497. };
  23498. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y) {
  23499. UniformBuffer._tempBuffer[0] = x;
  23500. UniformBuffer._tempBuffer[1] = y;
  23501. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  23502. };
  23503. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  23504. if (suffix === void 0) { suffix = ""; }
  23505. this._currentEffect.setFloat3(name + suffix, x, y, z);
  23506. };
  23507. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  23508. if (suffix === void 0) { suffix = ""; }
  23509. UniformBuffer._tempBuffer[0] = x;
  23510. UniformBuffer._tempBuffer[1] = y;
  23511. UniformBuffer._tempBuffer[2] = z;
  23512. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  23513. };
  23514. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  23515. if (suffix === void 0) { suffix = ""; }
  23516. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  23517. };
  23518. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  23519. if (suffix === void 0) { suffix = ""; }
  23520. UniformBuffer._tempBuffer[0] = x;
  23521. UniformBuffer._tempBuffer[1] = y;
  23522. UniformBuffer._tempBuffer[2] = z;
  23523. UniformBuffer._tempBuffer[3] = w;
  23524. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  23525. };
  23526. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  23527. this._currentEffect.setMatrix(name, mat);
  23528. };
  23529. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  23530. this.updateUniform(name, mat.toArray(), 16);
  23531. };
  23532. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  23533. this._currentEffect.setVector3(name, vector);
  23534. };
  23535. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  23536. vector.toArray(UniformBuffer._tempBuffer);
  23537. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  23538. };
  23539. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  23540. this._currentEffect.setVector4(name, vector);
  23541. };
  23542. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  23543. vector.toArray(UniformBuffer._tempBuffer);
  23544. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  23545. };
  23546. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  23547. if (suffix === void 0) { suffix = ""; }
  23548. this._currentEffect.setColor3(name + suffix, color);
  23549. };
  23550. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  23551. if (suffix === void 0) { suffix = ""; }
  23552. color.toArray(UniformBuffer._tempBuffer);
  23553. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  23554. };
  23555. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  23556. if (suffix === void 0) { suffix = ""; }
  23557. this._currentEffect.setColor4(name + suffix, color, alpha);
  23558. };
  23559. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  23560. if (suffix === void 0) { suffix = ""; }
  23561. color.toArray(UniformBuffer._tempBuffer);
  23562. UniformBuffer._tempBuffer[3] = alpha;
  23563. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  23564. };
  23565. /**
  23566. * Sets a sampler uniform on the effect.
  23567. * @param {string} name Name of the sampler.
  23568. * @param {Texture} texture
  23569. */
  23570. UniformBuffer.prototype.setTexture = function (name, texture) {
  23571. this._currentEffect.setTexture(name, texture);
  23572. };
  23573. /**
  23574. * Directly updates the value of the uniform in the cache AND on the GPU.
  23575. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  23576. * @param {number[]|Float32Array} data Flattened data
  23577. */
  23578. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  23579. this.updateUniform(uniformName, data, data.length);
  23580. this.update();
  23581. };
  23582. /**
  23583. * Binds this uniform buffer to an effect.
  23584. * @param {Effect} effect
  23585. * @param {string} name Name of the uniform block in the shader.
  23586. */
  23587. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  23588. this._currentEffect = effect;
  23589. if (this._noUBO) {
  23590. return;
  23591. }
  23592. effect.bindUniformBuffer(this._buffer, name);
  23593. };
  23594. /**
  23595. * Disposes the uniform buffer.
  23596. */
  23597. UniformBuffer.prototype.dispose = function () {
  23598. if (!this._buffer) {
  23599. return;
  23600. }
  23601. if (this._engine._releaseBuffer(this._buffer)) {
  23602. this._buffer = null;
  23603. }
  23604. };
  23605. return UniformBuffer;
  23606. }());
  23607. // Pool for avoiding memory leaks
  23608. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  23609. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  23610. BABYLON.UniformBuffer = UniformBuffer;
  23611. })(BABYLON || (BABYLON = {}));
  23612. //# sourceMappingURL=babylon.uniformBuffer.js.map
  23613. var BABYLON;
  23614. (function (BABYLON) {
  23615. var PushMaterial = (function (_super) {
  23616. __extends(PushMaterial, _super);
  23617. function PushMaterial(name, scene) {
  23618. var _this = _super.call(this, name, scene) || this;
  23619. _this.storeEffectOnSubMeshes = true;
  23620. return _this;
  23621. }
  23622. PushMaterial.prototype.getEffect = function () {
  23623. return this._activeEffect;
  23624. };
  23625. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  23626. if (!mesh) {
  23627. return false;
  23628. }
  23629. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23630. return true;
  23631. }
  23632. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  23633. };
  23634. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23635. this._activeEffect.setMatrix("world", world);
  23636. };
  23637. PushMaterial.prototype.bind = function (world, mesh) {
  23638. if (!mesh) {
  23639. return;
  23640. }
  23641. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  23642. };
  23643. PushMaterial.prototype._afterBind = function (mesh, effect) {
  23644. _super.prototype._afterBind.call(this, mesh);
  23645. this.getScene()._cachedEffect = effect;
  23646. };
  23647. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  23648. if (visibility === void 0) { visibility = 0; }
  23649. return scene.isCachedMaterialValid(this, effect, visibility);
  23650. };
  23651. PushMaterial.prototype.markAsDirty = function (flag) {
  23652. if (flag & BABYLON.Material.TextureDirtyFlag) {
  23653. this._markAllSubMeshesAsTexturesDirty();
  23654. }
  23655. if (flag & BABYLON.Material.LightDirtyFlag) {
  23656. this._markAllSubMeshesAsLightsDirty();
  23657. }
  23658. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  23659. this._markAllSubMeshesAsFresnelDirty();
  23660. }
  23661. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  23662. this._markAllSubMeshesAsAttributesDirty();
  23663. }
  23664. if (flag & BABYLON.Material.MiscDirtyFlag) {
  23665. this._markAllSubMeshesAsMiscDirty();
  23666. }
  23667. };
  23668. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  23669. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23670. var mesh = _a[_i];
  23671. if (!mesh.subMeshes) {
  23672. continue;
  23673. }
  23674. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23675. var subMesh = _c[_b];
  23676. if (subMesh.getMaterial() !== this) {
  23677. continue;
  23678. }
  23679. if (!subMesh._materialDefines) {
  23680. return;
  23681. }
  23682. func(subMesh._materialDefines);
  23683. }
  23684. }
  23685. };
  23686. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  23687. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  23688. };
  23689. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  23690. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  23691. };
  23692. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  23693. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  23694. };
  23695. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  23696. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  23697. };
  23698. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  23699. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  23700. };
  23701. return PushMaterial;
  23702. }(BABYLON.Material));
  23703. BABYLON.PushMaterial = PushMaterial;
  23704. })(BABYLON || (BABYLON = {}));
  23705. //# sourceMappingURL=babylon.pushMaterial.js.map
  23706. var BABYLON;
  23707. (function (BABYLON) {
  23708. var VertexData = (function () {
  23709. function VertexData() {
  23710. }
  23711. VertexData.prototype.set = function (data, kind) {
  23712. switch (kind) {
  23713. case BABYLON.VertexBuffer.PositionKind:
  23714. this.positions = data;
  23715. break;
  23716. case BABYLON.VertexBuffer.NormalKind:
  23717. this.normals = data;
  23718. break;
  23719. case BABYLON.VertexBuffer.TangentKind:
  23720. this.tangents = data;
  23721. break;
  23722. case BABYLON.VertexBuffer.UVKind:
  23723. this.uvs = data;
  23724. break;
  23725. case BABYLON.VertexBuffer.UV2Kind:
  23726. this.uvs2 = data;
  23727. break;
  23728. case BABYLON.VertexBuffer.UV3Kind:
  23729. this.uvs3 = data;
  23730. break;
  23731. case BABYLON.VertexBuffer.UV4Kind:
  23732. this.uvs4 = data;
  23733. break;
  23734. case BABYLON.VertexBuffer.UV5Kind:
  23735. this.uvs5 = data;
  23736. break;
  23737. case BABYLON.VertexBuffer.UV6Kind:
  23738. this.uvs6 = data;
  23739. break;
  23740. case BABYLON.VertexBuffer.ColorKind:
  23741. this.colors = data;
  23742. break;
  23743. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23744. this.matricesIndices = data;
  23745. break;
  23746. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23747. this.matricesWeights = data;
  23748. break;
  23749. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23750. this.matricesIndicesExtra = data;
  23751. break;
  23752. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23753. this.matricesWeightsExtra = data;
  23754. break;
  23755. }
  23756. };
  23757. /**
  23758. * Associates the vertexData to the passed Mesh.
  23759. * Sets it as updatable or not (default `false`).
  23760. * Returns the VertexData.
  23761. */
  23762. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23763. this._applyTo(mesh, updatable);
  23764. return this;
  23765. };
  23766. /**
  23767. * Associates the vertexData to the passed Geometry.
  23768. * Sets it as updatable or not (default `false`).
  23769. * Returns the VertexData.
  23770. */
  23771. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23772. this._applyTo(geometry, updatable);
  23773. return this;
  23774. };
  23775. /**
  23776. * Updates the associated mesh.
  23777. * Returns the VertexData.
  23778. */
  23779. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23780. this._update(mesh);
  23781. return this;
  23782. };
  23783. /**
  23784. * Updates the associated geometry.
  23785. * Returns the VertexData.
  23786. */
  23787. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23788. this._update(geometry);
  23789. return this;
  23790. };
  23791. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23792. if (this.positions) {
  23793. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23794. }
  23795. if (this.normals) {
  23796. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23797. }
  23798. if (this.tangents) {
  23799. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  23800. }
  23801. if (this.uvs) {
  23802. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23803. }
  23804. if (this.uvs2) {
  23805. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23806. }
  23807. if (this.uvs3) {
  23808. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23809. }
  23810. if (this.uvs4) {
  23811. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23812. }
  23813. if (this.uvs5) {
  23814. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23815. }
  23816. if (this.uvs6) {
  23817. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23818. }
  23819. if (this.colors) {
  23820. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23821. }
  23822. if (this.matricesIndices) {
  23823. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23824. }
  23825. if (this.matricesWeights) {
  23826. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23827. }
  23828. if (this.matricesIndicesExtra) {
  23829. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23830. }
  23831. if (this.matricesWeightsExtra) {
  23832. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23833. }
  23834. if (this.indices) {
  23835. meshOrGeometry.setIndices(this.indices);
  23836. }
  23837. return this;
  23838. };
  23839. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23840. if (this.positions) {
  23841. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23842. }
  23843. if (this.normals) {
  23844. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23845. }
  23846. if (this.tangents) {
  23847. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  23848. }
  23849. if (this.uvs) {
  23850. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23851. }
  23852. if (this.uvs2) {
  23853. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23854. }
  23855. if (this.uvs3) {
  23856. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23857. }
  23858. if (this.uvs4) {
  23859. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23860. }
  23861. if (this.uvs5) {
  23862. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23863. }
  23864. if (this.uvs6) {
  23865. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23866. }
  23867. if (this.colors) {
  23868. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23869. }
  23870. if (this.matricesIndices) {
  23871. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23872. }
  23873. if (this.matricesWeights) {
  23874. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23875. }
  23876. if (this.matricesIndicesExtra) {
  23877. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23878. }
  23879. if (this.matricesWeightsExtra) {
  23880. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23881. }
  23882. if (this.indices) {
  23883. meshOrGeometry.setIndices(this.indices);
  23884. }
  23885. return this;
  23886. };
  23887. /**
  23888. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  23889. * Returns the VertexData.
  23890. */
  23891. VertexData.prototype.transform = function (matrix) {
  23892. var transformed = BABYLON.Vector3.Zero();
  23893. var index;
  23894. if (this.positions) {
  23895. var position = BABYLON.Vector3.Zero();
  23896. for (index = 0; index < this.positions.length; index += 3) {
  23897. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23898. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23899. this.positions[index] = transformed.x;
  23900. this.positions[index + 1] = transformed.y;
  23901. this.positions[index + 2] = transformed.z;
  23902. }
  23903. }
  23904. if (this.normals) {
  23905. var normal = BABYLON.Vector3.Zero();
  23906. for (index = 0; index < this.normals.length; index += 3) {
  23907. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23908. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23909. this.normals[index] = transformed.x;
  23910. this.normals[index + 1] = transformed.y;
  23911. this.normals[index + 2] = transformed.z;
  23912. }
  23913. }
  23914. if (this.tangents) {
  23915. var tangent = BABYLON.Vector4.Zero();
  23916. var tangentTransformed = BABYLON.Vector4.Zero();
  23917. for (index = 0; index < this.tangents.length; index += 4) {
  23918. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  23919. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  23920. this.tangents[index] = tangentTransformed.x;
  23921. this.tangents[index + 1] = tangentTransformed.y;
  23922. this.tangents[index + 2] = tangentTransformed.z;
  23923. this.tangents[index + 3] = tangentTransformed.w;
  23924. }
  23925. }
  23926. return this;
  23927. };
  23928. /**
  23929. * Merges the passed VertexData into the current one.
  23930. * Returns the modified VertexData.
  23931. */
  23932. VertexData.prototype.merge = function (other) {
  23933. if (other.indices) {
  23934. if (!this.indices) {
  23935. this.indices = [];
  23936. }
  23937. var offset = this.positions ? this.positions.length / 3 : 0;
  23938. for (var index = 0; index < other.indices.length; index++) {
  23939. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  23940. this.indices.push(other.indices[index] + offset);
  23941. }
  23942. }
  23943. this.positions = this._mergeElement(this.positions, other.positions);
  23944. this.normals = this._mergeElement(this.normals, other.normals);
  23945. this.tangents = this._mergeElement(this.tangents, other.tangents);
  23946. this.uvs = this._mergeElement(this.uvs, other.uvs);
  23947. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  23948. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  23949. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  23950. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  23951. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  23952. this.colors = this._mergeElement(this.colors, other.colors);
  23953. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  23954. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  23955. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  23956. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  23957. return this;
  23958. };
  23959. VertexData.prototype._mergeElement = function (source, other) {
  23960. if (!other)
  23961. return source;
  23962. if (!source)
  23963. return other;
  23964. var len = other.length + source.length;
  23965. var isSrcTypedArray = source instanceof Float32Array;
  23966. var isOthTypedArray = other instanceof Float32Array;
  23967. // use non-loop method when the source is Float32Array
  23968. if (isSrcTypedArray) {
  23969. var ret32 = new Float32Array(len);
  23970. ret32.set(source);
  23971. ret32.set(other, source.length);
  23972. return ret32;
  23973. // source is number[], when other is also use concat
  23974. }
  23975. else if (!isOthTypedArray) {
  23976. return source.concat(other);
  23977. // source is a number[], but other is a Float32Array, loop required
  23978. }
  23979. else {
  23980. var ret = source.slice(0); // copy source to a separate array
  23981. for (var i = 0, len = other.length; i < len; i++) {
  23982. ret.push(other[i]);
  23983. }
  23984. return ret;
  23985. }
  23986. };
  23987. /**
  23988. * Serializes the VertexData.
  23989. * Returns a serialized object.
  23990. */
  23991. VertexData.prototype.serialize = function () {
  23992. var serializationObject = this.serialize();
  23993. if (this.positions) {
  23994. serializationObject.positions = this.positions;
  23995. }
  23996. if (this.normals) {
  23997. serializationObject.normals = this.normals;
  23998. }
  23999. if (this.tangents) {
  24000. serializationObject.tangents = this.tangents;
  24001. }
  24002. if (this.uvs) {
  24003. serializationObject.uvs = this.uvs;
  24004. }
  24005. if (this.uvs2) {
  24006. serializationObject.uvs2 = this.uvs2;
  24007. }
  24008. if (this.uvs3) {
  24009. serializationObject.uvs3 = this.uvs3;
  24010. }
  24011. if (this.uvs4) {
  24012. serializationObject.uvs4 = this.uvs4;
  24013. }
  24014. if (this.uvs5) {
  24015. serializationObject.uvs5 = this.uvs5;
  24016. }
  24017. if (this.uvs6) {
  24018. serializationObject.uvs6 = this.uvs6;
  24019. }
  24020. if (this.colors) {
  24021. serializationObject.colors = this.colors;
  24022. }
  24023. if (this.matricesIndices) {
  24024. serializationObject.matricesIndices = this.matricesIndices;
  24025. serializationObject.matricesIndices._isExpanded = true;
  24026. }
  24027. if (this.matricesWeights) {
  24028. serializationObject.matricesWeights = this.matricesWeights;
  24029. }
  24030. if (this.matricesIndicesExtra) {
  24031. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  24032. serializationObject.matricesIndicesExtra._isExpanded = true;
  24033. }
  24034. if (this.matricesWeightsExtra) {
  24035. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  24036. }
  24037. serializationObject.indices = this.indices;
  24038. return serializationObject;
  24039. };
  24040. // Statics
  24041. /**
  24042. * Returns the object VertexData associated to the passed mesh.
  24043. */
  24044. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24045. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24046. };
  24047. /**
  24048. * Returns the object VertexData associated to the passed geometry.
  24049. */
  24050. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24051. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24052. };
  24053. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24054. var result = new VertexData();
  24055. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24056. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24057. }
  24058. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24059. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24060. }
  24061. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24062. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared);
  24063. }
  24064. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24065. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24066. }
  24067. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24068. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24069. }
  24070. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  24071. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  24072. }
  24073. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  24074. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  24075. }
  24076. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  24077. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  24078. }
  24079. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  24080. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  24081. }
  24082. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24083. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24084. }
  24085. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24086. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24087. }
  24088. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24089. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24090. }
  24091. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  24092. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  24093. }
  24094. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  24095. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  24096. }
  24097. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24098. return result;
  24099. };
  24100. /**
  24101. * Creates the vertexData of the Ribbon.
  24102. */
  24103. VertexData.CreateRibbon = function (options) {
  24104. var pathArray = options.pathArray;
  24105. var closeArray = options.closeArray || false;
  24106. var closePath = options.closePath || false;
  24107. var invertUV = options.invertUV || false;
  24108. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24109. var offset = options.offset || defaultOffset;
  24110. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24111. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24112. var customUV = options.uvs;
  24113. var customColors = options.colors;
  24114. var positions = [];
  24115. var indices = [];
  24116. var normals = [];
  24117. var uvs = [];
  24118. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24119. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24120. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24121. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24122. var minlg; // minimal length among all paths from pathArray
  24123. var lg = []; // array of path lengths : nb of vertex per path
  24124. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  24125. var p; // path iterator
  24126. var i; // point iterator
  24127. var j; // point iterator
  24128. // if single path in pathArray
  24129. if (pathArray.length < 2) {
  24130. var ar1 = [];
  24131. var ar2 = [];
  24132. for (i = 0; i < pathArray[0].length - offset; i++) {
  24133. ar1.push(pathArray[0][i]);
  24134. ar2.push(pathArray[0][i + offset]);
  24135. }
  24136. pathArray = [ar1, ar2];
  24137. }
  24138. // positions and horizontal distances (u)
  24139. var idc = 0;
  24140. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  24141. var path;
  24142. var l;
  24143. minlg = pathArray[0].length;
  24144. var vectlg;
  24145. var dist;
  24146. for (p = 0; p < pathArray.length; p++) {
  24147. uTotalDistance[p] = 0;
  24148. us[p] = [0];
  24149. path = pathArray[p];
  24150. l = path.length;
  24151. minlg = (minlg < l) ? minlg : l;
  24152. j = 0;
  24153. while (j < l) {
  24154. positions.push(path[j].x, path[j].y, path[j].z);
  24155. if (j > 0) {
  24156. vectlg = path[j].subtract(path[j - 1]).length();
  24157. dist = vectlg + uTotalDistance[p];
  24158. us[p].push(dist);
  24159. uTotalDistance[p] = dist;
  24160. }
  24161. j++;
  24162. }
  24163. if (closePath) {
  24164. j--;
  24165. positions.push(path[0].x, path[0].y, path[0].z);
  24166. vectlg = path[j].subtract(path[0]).length();
  24167. dist = vectlg + uTotalDistance[p];
  24168. us[p].push(dist);
  24169. uTotalDistance[p] = dist;
  24170. }
  24171. lg[p] = l + closePathCorr;
  24172. idx[p] = idc;
  24173. idc += (l + closePathCorr);
  24174. }
  24175. // vertical distances (v)
  24176. var path1;
  24177. var path2;
  24178. var vertex1;
  24179. var vertex2;
  24180. for (i = 0; i < minlg + closePathCorr; i++) {
  24181. vTotalDistance[i] = 0;
  24182. vs[i] = [0];
  24183. for (p = 0; p < pathArray.length - 1; p++) {
  24184. path1 = pathArray[p];
  24185. path2 = pathArray[p + 1];
  24186. if (i === minlg) {
  24187. vertex1 = path1[0];
  24188. vertex2 = path2[0];
  24189. }
  24190. else {
  24191. vertex1 = path1[i];
  24192. vertex2 = path2[i];
  24193. }
  24194. vectlg = vertex2.subtract(vertex1).length();
  24195. dist = vectlg + vTotalDistance[i];
  24196. vs[i].push(dist);
  24197. vTotalDistance[i] = dist;
  24198. }
  24199. if (closeArray) {
  24200. path1 = pathArray[p];
  24201. path2 = pathArray[0];
  24202. if (i === minlg) {
  24203. vertex2 = path2[0];
  24204. }
  24205. vectlg = vertex2.subtract(vertex1).length();
  24206. dist = vectlg + vTotalDistance[i];
  24207. vTotalDistance[i] = dist;
  24208. }
  24209. }
  24210. // uvs
  24211. var u;
  24212. var v;
  24213. if (customUV) {
  24214. for (p = 0; p < customUV.length; p++) {
  24215. uvs.push(customUV[p].x, customUV[p].y);
  24216. }
  24217. }
  24218. else {
  24219. for (p = 0; p < pathArray.length; p++) {
  24220. for (i = 0; i < minlg + closePathCorr; i++) {
  24221. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  24222. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  24223. if (invertUV) {
  24224. uvs.push(v, u);
  24225. }
  24226. else {
  24227. uvs.push(u, v);
  24228. }
  24229. }
  24230. }
  24231. }
  24232. // indices
  24233. p = 0; // path index
  24234. var pi = 0; // positions array index
  24235. var l1 = lg[p] - 1; // path1 length
  24236. var l2 = lg[p + 1] - 1; // path2 length
  24237. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24238. var shft = idx[1] - idx[0]; // shift
  24239. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  24240. while (pi <= min && p < path1nb) {
  24241. // 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
  24242. indices.push(pi, pi + shft, pi + 1);
  24243. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24244. pi += 1;
  24245. if (pi === min) {
  24246. p++;
  24247. if (p === lg.length - 1) {
  24248. shft = idx[0] - idx[p];
  24249. l1 = lg[p] - 1;
  24250. l2 = lg[0] - 1;
  24251. }
  24252. else {
  24253. shft = idx[p + 1] - idx[p];
  24254. l1 = lg[p] - 1;
  24255. l2 = lg[p + 1] - 1;
  24256. }
  24257. pi = idx[p];
  24258. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24259. }
  24260. }
  24261. // normals
  24262. VertexData.ComputeNormals(positions, indices, normals);
  24263. if (closePath) {
  24264. var indexFirst = 0;
  24265. var indexLast = 0;
  24266. for (p = 0; p < pathArray.length; p++) {
  24267. indexFirst = idx[p] * 3;
  24268. if (p + 1 < pathArray.length) {
  24269. indexLast = (idx[p + 1] - 1) * 3;
  24270. }
  24271. else {
  24272. indexLast = normals.length - 3;
  24273. }
  24274. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  24275. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  24276. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  24277. normals[indexLast] = normals[indexFirst];
  24278. normals[indexLast + 1] = normals[indexFirst + 1];
  24279. normals[indexLast + 2] = normals[indexFirst + 2];
  24280. }
  24281. }
  24282. // sides
  24283. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24284. // Colors
  24285. if (customColors) {
  24286. var colors = new Float32Array(customColors.length * 4);
  24287. for (var c = 0; c < customColors.length; c++) {
  24288. colors[c * 4] = customColors[c].r;
  24289. colors[c * 4 + 1] = customColors[c].g;
  24290. colors[c * 4 + 2] = customColors[c].b;
  24291. colors[c * 4 + 3] = customColors[c].a;
  24292. }
  24293. }
  24294. // Result
  24295. var vertexData = new VertexData();
  24296. var positions32 = new Float32Array(positions);
  24297. var normals32 = new Float32Array(normals);
  24298. var uvs32 = new Float32Array(uvs);
  24299. vertexData.indices = indices;
  24300. vertexData.positions = positions32;
  24301. vertexData.normals = normals32;
  24302. vertexData.uvs = uvs32;
  24303. if (customColors) {
  24304. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  24305. }
  24306. if (closePath) {
  24307. vertexData._idx = idx;
  24308. }
  24309. return vertexData;
  24310. };
  24311. /**
  24312. * Creates the VertexData of the Box.
  24313. */
  24314. VertexData.CreateBox = function (options) {
  24315. var normalsSource = [
  24316. new BABYLON.Vector3(0, 0, 1),
  24317. new BABYLON.Vector3(0, 0, -1),
  24318. new BABYLON.Vector3(1, 0, 0),
  24319. new BABYLON.Vector3(-1, 0, 0),
  24320. new BABYLON.Vector3(0, 1, 0),
  24321. new BABYLON.Vector3(0, -1, 0)
  24322. ];
  24323. var indices = [];
  24324. var positions = [];
  24325. var normals = [];
  24326. var uvs = [];
  24327. var width = options.width || options.size || 1;
  24328. var height = options.height || options.size || 1;
  24329. var depth = options.depth || options.size || 1;
  24330. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24331. var faceUV = options.faceUV || new Array(6);
  24332. var faceColors = options.faceColors;
  24333. var colors = [];
  24334. // default face colors and UV if undefined
  24335. for (var f = 0; f < 6; f++) {
  24336. if (faceUV[f] === undefined) {
  24337. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24338. }
  24339. if (faceColors && faceColors[f] === undefined) {
  24340. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24341. }
  24342. }
  24343. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  24344. // Create each face in turn.
  24345. for (var index = 0; index < normalsSource.length; index++) {
  24346. var normal = normalsSource[index];
  24347. // Get two vectors perpendicular to the face normal and to each other.
  24348. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24349. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24350. // Six indices (two triangles) per face.
  24351. var verticesLength = positions.length / 3;
  24352. indices.push(verticesLength);
  24353. indices.push(verticesLength + 1);
  24354. indices.push(verticesLength + 2);
  24355. indices.push(verticesLength);
  24356. indices.push(verticesLength + 2);
  24357. indices.push(verticesLength + 3);
  24358. // Four vertices per face.
  24359. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  24360. positions.push(vertex.x, vertex.y, vertex.z);
  24361. normals.push(normal.x, normal.y, normal.z);
  24362. uvs.push(faceUV[index].z, faceUV[index].w);
  24363. if (faceColors) {
  24364. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24365. }
  24366. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  24367. positions.push(vertex.x, vertex.y, vertex.z);
  24368. normals.push(normal.x, normal.y, normal.z);
  24369. uvs.push(faceUV[index].x, faceUV[index].w);
  24370. if (faceColors) {
  24371. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24372. }
  24373. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  24374. positions.push(vertex.x, vertex.y, vertex.z);
  24375. normals.push(normal.x, normal.y, normal.z);
  24376. uvs.push(faceUV[index].x, faceUV[index].y);
  24377. if (faceColors) {
  24378. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24379. }
  24380. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  24381. positions.push(vertex.x, vertex.y, vertex.z);
  24382. normals.push(normal.x, normal.y, normal.z);
  24383. uvs.push(faceUV[index].z, faceUV[index].y);
  24384. if (faceColors) {
  24385. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24386. }
  24387. }
  24388. // sides
  24389. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24390. // Result
  24391. var vertexData = new VertexData();
  24392. vertexData.indices = indices;
  24393. vertexData.positions = positions;
  24394. vertexData.normals = normals;
  24395. vertexData.uvs = uvs;
  24396. if (faceColors) {
  24397. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  24398. vertexData.colors = totalColors;
  24399. }
  24400. return vertexData;
  24401. };
  24402. /**
  24403. * Creates the VertexData of the Sphere.
  24404. */
  24405. VertexData.CreateSphere = function (options) {
  24406. var segments = options.segments || 32;
  24407. var diameterX = options.diameterX || options.diameter || 1;
  24408. var diameterY = options.diameterY || options.diameter || 1;
  24409. var diameterZ = options.diameterZ || options.diameter || 1;
  24410. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24411. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  24412. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24413. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  24414. var totalZRotationSteps = 2 + segments;
  24415. var totalYRotationSteps = 2 * totalZRotationSteps;
  24416. var indices = [];
  24417. var positions = [];
  24418. var normals = [];
  24419. var uvs = [];
  24420. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24421. var normalizedZ = zRotationStep / totalZRotationSteps;
  24422. var angleZ = normalizedZ * Math.PI * slice;
  24423. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24424. var normalizedY = yRotationStep / totalYRotationSteps;
  24425. var angleY = normalizedY * Math.PI * 2 * arc;
  24426. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24427. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24428. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24429. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24430. var vertex = complete.multiply(radius);
  24431. var normal = complete.divide(radius).normalize();
  24432. positions.push(vertex.x, vertex.y, vertex.z);
  24433. normals.push(normal.x, normal.y, normal.z);
  24434. uvs.push(normalizedY, normalizedZ);
  24435. }
  24436. if (zRotationStep > 0) {
  24437. var verticesCount = positions.length / 3;
  24438. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24439. indices.push((firstIndex));
  24440. indices.push((firstIndex + 1));
  24441. indices.push(firstIndex + totalYRotationSteps + 1);
  24442. indices.push((firstIndex + totalYRotationSteps + 1));
  24443. indices.push((firstIndex + 1));
  24444. indices.push((firstIndex + totalYRotationSteps + 2));
  24445. }
  24446. }
  24447. }
  24448. // Sides
  24449. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24450. // Result
  24451. var vertexData = new VertexData();
  24452. vertexData.indices = indices;
  24453. vertexData.positions = positions;
  24454. vertexData.normals = normals;
  24455. vertexData.uvs = uvs;
  24456. return vertexData;
  24457. };
  24458. /**
  24459. * Creates the VertexData of the Cylinder or Cone.
  24460. */
  24461. VertexData.CreateCylinder = function (options) {
  24462. var height = options.height || 2;
  24463. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  24464. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  24465. var tessellation = options.tessellation || 24;
  24466. var subdivisions = options.subdivisions || 1;
  24467. var hasRings = options.hasRings;
  24468. var enclose = options.enclose;
  24469. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24470. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24471. var faceUV = options.faceUV || new Array(3);
  24472. var faceColors = options.faceColors;
  24473. // default face colors and UV if undefined
  24474. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  24475. var ringNb = (hasRings) ? subdivisions : 1;
  24476. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  24477. var f;
  24478. for (f = 0; f < surfaceNb; f++) {
  24479. if (faceColors && faceColors[f] === undefined) {
  24480. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24481. }
  24482. }
  24483. for (f = 0; f < surfaceNb; f++) {
  24484. if (faceUV && faceUV[f] === undefined) {
  24485. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24486. }
  24487. }
  24488. var indices = [];
  24489. var positions = [];
  24490. var normals = [];
  24491. var uvs = [];
  24492. var colors = [];
  24493. var angle_step = Math.PI * 2 * arc / tessellation;
  24494. var angle;
  24495. var h;
  24496. var radius;
  24497. var tan = (diameterBottom - diameterTop) / 2 / height;
  24498. var ringVertex = BABYLON.Vector3.Zero();
  24499. var ringNormal = BABYLON.Vector3.Zero();
  24500. var ringFirstVertex = BABYLON.Vector3.Zero();
  24501. var ringFirstNormal = BABYLON.Vector3.Zero();
  24502. var quadNormal = BABYLON.Vector3.Zero();
  24503. var Y = BABYLON.Axis.Y;
  24504. // positions, normals, uvs
  24505. var i;
  24506. var j;
  24507. var r;
  24508. var ringIdx = 1;
  24509. var s = 1; // surface index
  24510. var cs = 0;
  24511. var v = 0;
  24512. for (i = 0; i <= subdivisions; i++) {
  24513. h = i / subdivisions;
  24514. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  24515. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  24516. for (r = 0; r < ringIdx; r++) {
  24517. if (hasRings) {
  24518. s += r;
  24519. }
  24520. if (enclose) {
  24521. s += 2 * r;
  24522. }
  24523. for (j = 0; j <= tessellation; j++) {
  24524. angle = j * angle_step;
  24525. // position
  24526. ringVertex.x = Math.cos(-angle) * radius;
  24527. ringVertex.y = -height / 2 + h * height;
  24528. ringVertex.z = Math.sin(-angle) * radius;
  24529. // normal
  24530. if (diameterTop === 0 && i === subdivisions) {
  24531. // if no top cap, reuse former normals
  24532. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  24533. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  24534. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  24535. }
  24536. else {
  24537. ringNormal.x = ringVertex.x;
  24538. ringNormal.z = ringVertex.z;
  24539. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  24540. ringNormal.normalize();
  24541. }
  24542. // keep first ring vertex values for enclose
  24543. if (j === 0) {
  24544. ringFirstVertex.copyFrom(ringVertex);
  24545. ringFirstNormal.copyFrom(ringNormal);
  24546. }
  24547. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24548. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  24549. if (hasRings) {
  24550. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  24551. }
  24552. else {
  24553. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  24554. }
  24555. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  24556. if (faceColors) {
  24557. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  24558. }
  24559. }
  24560. // if enclose, add four vertices and their dedicated normals
  24561. if (arc !== 1 && enclose) {
  24562. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24563. positions.push(0, ringVertex.y, 0);
  24564. positions.push(0, ringVertex.y, 0);
  24565. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  24566. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  24567. quadNormal.normalize();
  24568. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24569. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  24570. quadNormal.normalize();
  24571. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24572. if (hasRings) {
  24573. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  24574. }
  24575. else {
  24576. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  24577. }
  24578. uvs.push(faceUV[s + 1].x, v);
  24579. uvs.push(faceUV[s + 1].z, v);
  24580. if (hasRings) {
  24581. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  24582. }
  24583. else {
  24584. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  24585. }
  24586. uvs.push(faceUV[s + 2].x, v);
  24587. uvs.push(faceUV[s + 2].z, v);
  24588. if (faceColors) {
  24589. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24590. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24591. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24592. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24593. }
  24594. }
  24595. if (cs !== s) {
  24596. cs = s;
  24597. }
  24598. }
  24599. }
  24600. // indices
  24601. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  24602. var s;
  24603. i = 0;
  24604. for (s = 0; s < subdivisions; s++) {
  24605. for (j = 0; j < tessellation; j++) {
  24606. var i0 = i * (e + 1) + j;
  24607. var i1 = (i + 1) * (e + 1) + j;
  24608. var i2 = i * (e + 1) + (j + 1);
  24609. var i3 = (i + 1) * (e + 1) + (j + 1);
  24610. indices.push(i0, i1, i2);
  24611. indices.push(i3, i2, i1);
  24612. }
  24613. if (arc !== 1 && enclose) {
  24614. indices.push(i0 + 2, i1 + 2, i2 + 2);
  24615. indices.push(i3 + 2, i2 + 2, i1 + 2);
  24616. indices.push(i0 + 4, i1 + 4, i2 + 4);
  24617. indices.push(i3 + 4, i2 + 4, i1 + 4);
  24618. }
  24619. i = (hasRings) ? (i + 2) : (i + 1);
  24620. }
  24621. // Caps
  24622. var createCylinderCap = function (isTop) {
  24623. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  24624. if (radius === 0) {
  24625. return;
  24626. }
  24627. // Cap positions, normals & uvs
  24628. var angle;
  24629. var circleVector;
  24630. var i;
  24631. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  24632. var c;
  24633. if (faceColors) {
  24634. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  24635. }
  24636. // cap center
  24637. var vbase = positions.length / 3;
  24638. var offset = isTop ? height / 2 : -height / 2;
  24639. var center = new BABYLON.Vector3(0, offset, 0);
  24640. positions.push(center.x, center.y, center.z);
  24641. normals.push(0, isTop ? 1 : -1, 0);
  24642. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  24643. if (faceColors) {
  24644. colors.push(c.r, c.g, c.b, c.a);
  24645. }
  24646. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24647. for (i = 0; i <= tessellation; i++) {
  24648. angle = Math.PI * 2 * i * arc / tessellation;
  24649. var cos = Math.cos(-angle);
  24650. var sin = Math.sin(-angle);
  24651. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  24652. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  24653. positions.push(circleVector.x, circleVector.y, circleVector.z);
  24654. normals.push(0, isTop ? 1 : -1, 0);
  24655. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  24656. if (faceColors) {
  24657. colors.push(c.r, c.g, c.b, c.a);
  24658. }
  24659. }
  24660. // Cap indices
  24661. for (i = 0; i < tessellation; i++) {
  24662. if (!isTop) {
  24663. indices.push(vbase);
  24664. indices.push(vbase + (i + 1));
  24665. indices.push(vbase + (i + 2));
  24666. }
  24667. else {
  24668. indices.push(vbase);
  24669. indices.push(vbase + (i + 2));
  24670. indices.push(vbase + (i + 1));
  24671. }
  24672. }
  24673. };
  24674. // add caps to geometry
  24675. createCylinderCap(false);
  24676. createCylinderCap(true);
  24677. // Sides
  24678. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24679. var vertexData = new VertexData();
  24680. vertexData.indices = indices;
  24681. vertexData.positions = positions;
  24682. vertexData.normals = normals;
  24683. vertexData.uvs = uvs;
  24684. if (faceColors) {
  24685. vertexData.colors = colors;
  24686. }
  24687. return vertexData;
  24688. };
  24689. /**
  24690. * Creates the VertexData of the Torus.
  24691. */
  24692. VertexData.CreateTorus = function (options) {
  24693. var indices = [];
  24694. var positions = [];
  24695. var normals = [];
  24696. var uvs = [];
  24697. var diameter = options.diameter || 1;
  24698. var thickness = options.thickness || 0.5;
  24699. var tessellation = options.tessellation || 16;
  24700. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24701. var stride = tessellation + 1;
  24702. for (var i = 0; i <= tessellation; i++) {
  24703. var u = i / tessellation;
  24704. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24705. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24706. for (var j = 0; j <= tessellation; j++) {
  24707. var v = 1 - j / tessellation;
  24708. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24709. var dx = Math.cos(innerAngle);
  24710. var dy = Math.sin(innerAngle);
  24711. // Create a vertex.
  24712. var normal = new BABYLON.Vector3(dx, dy, 0);
  24713. var position = normal.scale(thickness / 2);
  24714. var textureCoordinate = new BABYLON.Vector2(u, v);
  24715. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24716. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24717. positions.push(position.x, position.y, position.z);
  24718. normals.push(normal.x, normal.y, normal.z);
  24719. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24720. // And create indices for two triangles.
  24721. var nextI = (i + 1) % stride;
  24722. var nextJ = (j + 1) % stride;
  24723. indices.push(i * stride + j);
  24724. indices.push(i * stride + nextJ);
  24725. indices.push(nextI * stride + j);
  24726. indices.push(i * stride + nextJ);
  24727. indices.push(nextI * stride + nextJ);
  24728. indices.push(nextI * stride + j);
  24729. }
  24730. }
  24731. // Sides
  24732. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24733. // Result
  24734. var vertexData = new VertexData();
  24735. vertexData.indices = indices;
  24736. vertexData.positions = positions;
  24737. vertexData.normals = normals;
  24738. vertexData.uvs = uvs;
  24739. return vertexData;
  24740. };
  24741. /**
  24742. * Creates the VertexData of the LineSystem.
  24743. */
  24744. VertexData.CreateLineSystem = function (options) {
  24745. var indices = [];
  24746. var positions = [];
  24747. var lines = options.lines;
  24748. var idx = 0;
  24749. for (var l = 0; l < lines.length; l++) {
  24750. var points = lines[l];
  24751. for (var index = 0; index < points.length; index++) {
  24752. positions.push(points[index].x, points[index].y, points[index].z);
  24753. if (index > 0) {
  24754. indices.push(idx - 1);
  24755. indices.push(idx);
  24756. }
  24757. idx++;
  24758. }
  24759. }
  24760. var vertexData = new VertexData();
  24761. vertexData.indices = indices;
  24762. vertexData.positions = positions;
  24763. return vertexData;
  24764. };
  24765. /**
  24766. * Create the VertexData of the DashedLines.
  24767. */
  24768. VertexData.CreateDashedLines = function (options) {
  24769. var dashSize = options.dashSize || 3;
  24770. var gapSize = options.gapSize || 1;
  24771. var dashNb = options.dashNb || 200;
  24772. var points = options.points;
  24773. var positions = new Array();
  24774. var indices = new Array();
  24775. var curvect = BABYLON.Vector3.Zero();
  24776. var lg = 0;
  24777. var nb = 0;
  24778. var shft = 0;
  24779. var dashshft = 0;
  24780. var curshft = 0;
  24781. var idx = 0;
  24782. var i = 0;
  24783. for (i = 0; i < points.length - 1; i++) {
  24784. points[i + 1].subtractToRef(points[i], curvect);
  24785. lg += curvect.length();
  24786. }
  24787. shft = lg / dashNb;
  24788. dashshft = dashSize * shft / (dashSize + gapSize);
  24789. for (i = 0; i < points.length - 1; i++) {
  24790. points[i + 1].subtractToRef(points[i], curvect);
  24791. nb = Math.floor(curvect.length() / shft);
  24792. curvect.normalize();
  24793. for (var j = 0; j < nb; j++) {
  24794. curshft = shft * j;
  24795. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  24796. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  24797. indices.push(idx, idx + 1);
  24798. idx += 2;
  24799. }
  24800. }
  24801. // Result
  24802. var vertexData = new VertexData();
  24803. vertexData.positions = positions;
  24804. vertexData.indices = indices;
  24805. return vertexData;
  24806. };
  24807. /**
  24808. * Creates the VertexData of the Ground.
  24809. */
  24810. VertexData.CreateGround = function (options) {
  24811. var indices = [];
  24812. var positions = [];
  24813. var normals = [];
  24814. var uvs = [];
  24815. var row, col;
  24816. var width = options.width || 1;
  24817. var height = options.height || 1;
  24818. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  24819. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  24820. for (row = 0; row <= subdivisionsY; row++) {
  24821. for (col = 0; col <= subdivisionsX; col++) {
  24822. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  24823. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24824. positions.push(position.x, position.y, position.z);
  24825. normals.push(normal.x, normal.y, normal.z);
  24826. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  24827. }
  24828. }
  24829. for (row = 0; row < subdivisionsY; row++) {
  24830. for (col = 0; col < subdivisionsX; col++) {
  24831. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  24832. indices.push(col + 1 + row * (subdivisionsX + 1));
  24833. indices.push(col + row * (subdivisionsX + 1));
  24834. indices.push(col + (row + 1) * (subdivisionsX + 1));
  24835. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  24836. indices.push(col + row * (subdivisionsX + 1));
  24837. }
  24838. }
  24839. // Result
  24840. var vertexData = new VertexData();
  24841. vertexData.indices = indices;
  24842. vertexData.positions = positions;
  24843. vertexData.normals = normals;
  24844. vertexData.uvs = uvs;
  24845. return vertexData;
  24846. };
  24847. /**
  24848. * Creates the VertexData of the TiledGround.
  24849. */
  24850. VertexData.CreateTiledGround = function (options) {
  24851. var xmin = options.xmin || -1.0;
  24852. var zmin = options.zmin || -1.0;
  24853. var xmax = options.xmax || 1.0;
  24854. var zmax = options.zmax || 1.0;
  24855. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24856. var precision = options.precision || { w: 1, h: 1 };
  24857. var indices = [];
  24858. var positions = [];
  24859. var normals = [];
  24860. var uvs = [];
  24861. var row, col, tileRow, tileCol;
  24862. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  24863. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24864. precision.w = (precision.w < 1) ? 1 : precision.w;
  24865. precision.h = (precision.h < 1) ? 1 : precision.h;
  24866. var tileSize = {
  24867. 'w': (xmax - xmin) / subdivisions.w,
  24868. 'h': (zmax - zmin) / subdivisions.h
  24869. };
  24870. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24871. // Indices
  24872. var base = positions.length / 3;
  24873. var rowLength = precision.w + 1;
  24874. for (row = 0; row < precision.h; row++) {
  24875. for (col = 0; col < precision.w; col++) {
  24876. var square = [
  24877. base + col + row * rowLength,
  24878. base + (col + 1) + row * rowLength,
  24879. base + (col + 1) + (row + 1) * rowLength,
  24880. base + col + (row + 1) * rowLength
  24881. ];
  24882. indices.push(square[1]);
  24883. indices.push(square[2]);
  24884. indices.push(square[3]);
  24885. indices.push(square[0]);
  24886. indices.push(square[1]);
  24887. indices.push(square[3]);
  24888. }
  24889. }
  24890. // Position, normals and uvs
  24891. var position = BABYLON.Vector3.Zero();
  24892. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24893. for (row = 0; row <= precision.h; row++) {
  24894. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24895. for (col = 0; col <= precision.w; col++) {
  24896. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24897. position.y = 0;
  24898. positions.push(position.x, position.y, position.z);
  24899. normals.push(normal.x, normal.y, normal.z);
  24900. uvs.push(col / precision.w, row / precision.h);
  24901. }
  24902. }
  24903. }
  24904. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24905. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24906. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24907. }
  24908. }
  24909. // Result
  24910. var vertexData = new VertexData();
  24911. vertexData.indices = indices;
  24912. vertexData.positions = positions;
  24913. vertexData.normals = normals;
  24914. vertexData.uvs = uvs;
  24915. return vertexData;
  24916. };
  24917. /**
  24918. * Creates the VertexData of the Ground designed from a heightmap.
  24919. */
  24920. VertexData.CreateGroundFromHeightMap = function (options) {
  24921. var indices = [];
  24922. var positions = [];
  24923. var normals = [];
  24924. var uvs = [];
  24925. var row, col;
  24926. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  24927. // Vertices
  24928. for (row = 0; row <= options.subdivisions; row++) {
  24929. for (col = 0; col <= options.subdivisions; col++) {
  24930. 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));
  24931. // Compute height
  24932. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  24933. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  24934. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  24935. var r = options.buffer[pos] / 255.0;
  24936. var g = options.buffer[pos + 1] / 255.0;
  24937. var b = options.buffer[pos + 2] / 255.0;
  24938. var gradient = r * filter.r + g * filter.g + b * filter.b;
  24939. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  24940. // Add vertex
  24941. positions.push(position.x, position.y, position.z);
  24942. normals.push(0, 0, 0);
  24943. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  24944. }
  24945. }
  24946. // Indices
  24947. for (row = 0; row < options.subdivisions; row++) {
  24948. for (col = 0; col < options.subdivisions; col++) {
  24949. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24950. indices.push(col + 1 + row * (options.subdivisions + 1));
  24951. indices.push(col + row * (options.subdivisions + 1));
  24952. indices.push(col + (row + 1) * (options.subdivisions + 1));
  24953. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24954. indices.push(col + row * (options.subdivisions + 1));
  24955. }
  24956. }
  24957. // Normals
  24958. VertexData.ComputeNormals(positions, indices, normals);
  24959. // Result
  24960. var vertexData = new VertexData();
  24961. vertexData.indices = indices;
  24962. vertexData.positions = positions;
  24963. vertexData.normals = normals;
  24964. vertexData.uvs = uvs;
  24965. return vertexData;
  24966. };
  24967. /**
  24968. * Creates the VertexData of the Plane.
  24969. */
  24970. VertexData.CreatePlane = function (options) {
  24971. var indices = [];
  24972. var positions = [];
  24973. var normals = [];
  24974. var uvs = [];
  24975. var width = options.width || options.size || 1;
  24976. var height = options.height || options.size || 1;
  24977. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24978. // Vertices
  24979. var halfWidth = width / 2.0;
  24980. var halfHeight = height / 2.0;
  24981. positions.push(-halfWidth, -halfHeight, 0);
  24982. normals.push(0, 0, -1.0);
  24983. uvs.push(0.0, 0.0);
  24984. positions.push(halfWidth, -halfHeight, 0);
  24985. normals.push(0, 0, -1.0);
  24986. uvs.push(1.0, 0.0);
  24987. positions.push(halfWidth, halfHeight, 0);
  24988. normals.push(0, 0, -1.0);
  24989. uvs.push(1.0, 1.0);
  24990. positions.push(-halfWidth, halfHeight, 0);
  24991. normals.push(0, 0, -1.0);
  24992. uvs.push(0.0, 1.0);
  24993. // Indices
  24994. indices.push(0);
  24995. indices.push(1);
  24996. indices.push(2);
  24997. indices.push(0);
  24998. indices.push(2);
  24999. indices.push(3);
  25000. // Sides
  25001. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25002. // Result
  25003. var vertexData = new VertexData();
  25004. vertexData.indices = indices;
  25005. vertexData.positions = positions;
  25006. vertexData.normals = normals;
  25007. vertexData.uvs = uvs;
  25008. return vertexData;
  25009. };
  25010. /**
  25011. * Creates the VertexData of the Disc or regular Polygon.
  25012. */
  25013. VertexData.CreateDisc = function (options) {
  25014. var positions = [];
  25015. var indices = [];
  25016. var normals = [];
  25017. var uvs = [];
  25018. var radius = options.radius || 0.5;
  25019. var tessellation = options.tessellation || 64;
  25020. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  25021. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25022. // positions and uvs
  25023. positions.push(0, 0, 0); // disc center first
  25024. uvs.push(0.5, 0.5);
  25025. var theta = Math.PI * 2 * arc;
  25026. var step = theta / tessellation;
  25027. for (var a = 0; a < theta; a += step) {
  25028. var x = Math.cos(a);
  25029. var y = Math.sin(a);
  25030. var u = (x + 1) / 2;
  25031. var v = (1 - y) / 2;
  25032. positions.push(radius * x, radius * y, 0);
  25033. uvs.push(u, v);
  25034. }
  25035. if (arc === 1) {
  25036. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25037. uvs.push(uvs[2], uvs[3]);
  25038. }
  25039. //indices
  25040. var vertexNb = positions.length / 3;
  25041. for (var i = 1; i < vertexNb - 1; i++) {
  25042. indices.push(i + 1, 0, i);
  25043. }
  25044. // result
  25045. VertexData.ComputeNormals(positions, indices, normals);
  25046. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25047. var vertexData = new VertexData();
  25048. vertexData.indices = indices;
  25049. vertexData.positions = positions;
  25050. vertexData.normals = normals;
  25051. vertexData.uvs = uvs;
  25052. return vertexData;
  25053. };
  25054. /**
  25055. * Creates the VertexData of the IcoSphere.
  25056. */
  25057. VertexData.CreateIcoSphere = function (options) {
  25058. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25059. var radius = options.radius || 1;
  25060. var flat = (options.flat === undefined) ? true : options.flat;
  25061. var subdivisions = options.subdivisions || 4;
  25062. var radiusX = options.radiusX || radius;
  25063. var radiusY = options.radiusY || radius;
  25064. var radiusZ = options.radiusZ || radius;
  25065. var t = (1 + Math.sqrt(5)) / 2;
  25066. // 12 vertex x,y,z
  25067. var ico_vertices = [
  25068. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  25069. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  25070. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  25071. ];
  25072. // index of 3 vertex makes a face of icopshere
  25073. var ico_indices = [
  25074. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  25075. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  25076. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  25077. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  25078. ];
  25079. // vertex for uv have aliased position, not for UV
  25080. var vertices_unalias_id = [
  25081. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  25082. // vertex alias
  25083. 0,
  25084. 2,
  25085. 3,
  25086. 3,
  25087. 3,
  25088. 4,
  25089. 7,
  25090. 8,
  25091. 9,
  25092. 9,
  25093. 10,
  25094. 11 // 23: B + 12
  25095. ];
  25096. // uv as integer step (not pixels !)
  25097. var ico_vertexuv = [
  25098. 5, 1, 3, 1, 6, 4, 0, 0,
  25099. 5, 3, 4, 2, 2, 2, 4, 0,
  25100. 2, 0, 1, 1, 6, 0, 6, 2,
  25101. // vertex alias (for same vertex on different faces)
  25102. 0, 4,
  25103. 3, 3,
  25104. 4, 4,
  25105. 3, 1,
  25106. 4, 2,
  25107. 4, 4,
  25108. 0, 2,
  25109. 1, 1,
  25110. 2, 2,
  25111. 3, 3,
  25112. 1, 3,
  25113. 2, 4 // 23: B + 12
  25114. ];
  25115. // Vertices[0, 1, ...9, A, B] : position on UV plane
  25116. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  25117. // First island of uv mapping
  25118. // v = 4h 3+ 2
  25119. // v = 3h 9+ 4
  25120. // v = 2h 9+ 5 B
  25121. // v = 1h 9 1 0
  25122. // v = 0h 3 8 7 A
  25123. // u = 0 1 2 3 4 5 6 *a
  25124. // Second island of uv mapping
  25125. // v = 4h 0+ B+ 4+
  25126. // v = 3h A+ 2+
  25127. // v = 2h 7+ 6 3+
  25128. // v = 1h 8+ 3+
  25129. // v = 0h
  25130. // u = 0 1 2 3 4 5 6 *a
  25131. // Face layout on texture UV mapping
  25132. // ============
  25133. // \ 4 /\ 16 / ======
  25134. // \ / \ / /\ 11 /
  25135. // \/ 7 \/ / \ /
  25136. // ======= / 10 \/
  25137. // /\ 17 /\ =======
  25138. // / \ / \ \ 15 /\
  25139. // / 8 \/ 12 \ \ / \
  25140. // ============ \/ 6 \
  25141. // \ 18 /\ ============
  25142. // \ / \ \ 5 /\ 0 /
  25143. // \/ 13 \ \ / \ /
  25144. // ======= \/ 1 \/
  25145. // =============
  25146. // /\ 19 /\ 2 /\
  25147. // / \ / \ / \
  25148. // / 14 \/ 9 \/ 3 \
  25149. // ===================
  25150. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  25151. var ustep = 138 / 1024;
  25152. var vstep = 239 / 1024;
  25153. var uoffset = 60 / 1024;
  25154. var voffset = 26 / 1024;
  25155. // Second island should have margin, not to touch the first island
  25156. // avoid any borderline artefact in pixel rounding
  25157. var island_u_offset = -40 / 1024;
  25158. var island_v_offset = +20 / 1024;
  25159. // face is either island 0 or 1 :
  25160. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  25161. var island = [
  25162. 0, 0, 0, 0, 1,
  25163. 0, 0, 1, 1, 0,
  25164. 0, 0, 1, 1, 0,
  25165. 0, 1, 1, 1, 0 // 15 - 19
  25166. ];
  25167. var indices = [];
  25168. var positions = [];
  25169. var normals = [];
  25170. var uvs = [];
  25171. var current_indice = 0;
  25172. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  25173. var face_vertex_pos = new Array(3);
  25174. var face_vertex_uv = new Array(3);
  25175. var v012;
  25176. for (v012 = 0; v012 < 3; v012++) {
  25177. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  25178. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  25179. }
  25180. // create all with normals
  25181. for (var face = 0; face < 20; face++) {
  25182. // 3 vertex per face
  25183. for (v012 = 0; v012 < 3; v012++) {
  25184. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  25185. var v_id = ico_indices[3 * face + v012];
  25186. // vertex have 3D position (x,y,z)
  25187. 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]);
  25188. // Normalize to get normal, then scale to radius
  25189. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  25190. // uv Coordinates from vertex ID
  25191. 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);
  25192. }
  25193. // Subdivide the face (interpolate pos, norm, uv)
  25194. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  25195. // - norm is linear interpolation of vertex corner normal
  25196. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  25197. // - uv is linear interpolation
  25198. //
  25199. // Topology is as below for sub-divide by 2
  25200. // vertex shown as v0,v1,v2
  25201. // interp index is i1 to progress in range [v0,v1[
  25202. // interp index is i2 to progress in range [v0,v2[
  25203. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  25204. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25205. //
  25206. //
  25207. // i2 v2
  25208. // ^ ^
  25209. // / / \
  25210. // / / \
  25211. // / / \
  25212. // / / (0,1) \
  25213. // / #---------\
  25214. // / / \ (0,0)'/ \
  25215. // / / \ / \
  25216. // / / \ / \
  25217. // / / (0,0) \ / (1,0) \
  25218. // / #---------#---------\
  25219. // v0 v1
  25220. //
  25221. // --------------------> i1
  25222. //
  25223. // interp of (i1,i2):
  25224. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  25225. // along i1 : lerp(x0,x1, i1/(S-i2))
  25226. //
  25227. // centroid of triangle is needed to get help normal computation
  25228. // (c1,c2) are used for centroid location
  25229. var interp_vertex = function (i1, i2, c1, c2) {
  25230. // vertex is interpolated from
  25231. // - face_vertex_pos[0..2]
  25232. // - face_vertex_uv[0..2]
  25233. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  25234. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  25235. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  25236. pos_interp.normalize();
  25237. var vertex_normal;
  25238. if (flat) {
  25239. // in flat mode, recalculate normal as face centroid normal
  25240. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  25241. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  25242. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  25243. }
  25244. else {
  25245. // in smooth mode, recalculate normal from each single vertex position
  25246. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  25247. }
  25248. // Vertex normal need correction due to X,Y,Z radius scaling
  25249. vertex_normal.x /= radiusX;
  25250. vertex_normal.y /= radiusY;
  25251. vertex_normal.z /= radiusZ;
  25252. vertex_normal.normalize();
  25253. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  25254. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  25255. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  25256. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  25257. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  25258. uvs.push(uv_interp.x, uv_interp.y);
  25259. // push each vertex has member of a face
  25260. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  25261. indices.push(current_indice);
  25262. current_indice++;
  25263. };
  25264. for (var i2 = 0; i2 < subdivisions; i2++) {
  25265. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  25266. // face : (i1,i2) for /\ :
  25267. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  25268. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25269. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25270. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25271. if (i1 + i2 + 1 < subdivisions) {
  25272. // face : (i1,i2)' for \/ :
  25273. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25274. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25275. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25276. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25277. }
  25278. }
  25279. }
  25280. }
  25281. // Sides
  25282. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25283. // Result
  25284. var vertexData = new VertexData();
  25285. vertexData.indices = indices;
  25286. vertexData.positions = positions;
  25287. vertexData.normals = normals;
  25288. vertexData.uvs = uvs;
  25289. return vertexData;
  25290. };
  25291. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  25292. /**
  25293. * Creates the VertexData of the Polyhedron.
  25294. */
  25295. VertexData.CreatePolyhedron = function (options) {
  25296. // provided polyhedron types :
  25297. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  25298. // 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)
  25299. var polyhedra = [];
  25300. 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]] };
  25301. 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]] };
  25302. polyhedra[2] = {
  25303. 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]],
  25304. 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]]
  25305. };
  25306. polyhedra[3] = {
  25307. 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]],
  25308. 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]]
  25309. };
  25310. polyhedra[4] = {
  25311. 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]],
  25312. 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]]
  25313. };
  25314. 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]] };
  25315. 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]] };
  25316. 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]] };
  25317. 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]] };
  25318. 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]] };
  25319. 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]] };
  25320. 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]] };
  25321. 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]] };
  25322. 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]] };
  25323. polyhedra[14] = {
  25324. 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]],
  25325. 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]]
  25326. };
  25327. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  25328. var size = options.size;
  25329. var sizeX = options.sizeX || size || 1;
  25330. var sizeY = options.sizeY || size || 1;
  25331. var sizeZ = options.sizeZ || size || 1;
  25332. var data = options.custom || polyhedra[type];
  25333. var nbfaces = data.face.length;
  25334. var faceUV = options.faceUV || new Array(nbfaces);
  25335. var faceColors = options.faceColors;
  25336. var flat = (options.flat === undefined) ? true : options.flat;
  25337. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25338. var positions = [];
  25339. var indices = [];
  25340. var normals = [];
  25341. var uvs = [];
  25342. var colors = [];
  25343. var index = 0;
  25344. var faceIdx = 0; // face cursor in the array "indexes"
  25345. var indexes = [];
  25346. var i = 0;
  25347. var f = 0;
  25348. var u, v, ang, x, y, tmp;
  25349. // default face colors and UV if undefined
  25350. if (flat) {
  25351. for (f = 0; f < nbfaces; f++) {
  25352. if (faceColors && faceColors[f] === undefined) {
  25353. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25354. }
  25355. if (faceUV && faceUV[f] === undefined) {
  25356. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25357. }
  25358. }
  25359. }
  25360. if (!flat) {
  25361. for (i = 0; i < data.vertex.length; i++) {
  25362. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  25363. uvs.push(0, 0);
  25364. }
  25365. for (f = 0; f < nbfaces; f++) {
  25366. for (i = 0; i < data.face[f].length - 2; i++) {
  25367. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  25368. }
  25369. }
  25370. }
  25371. else {
  25372. for (f = 0; f < nbfaces; f++) {
  25373. var fl = data.face[f].length; // number of vertices of the current face
  25374. ang = 2 * Math.PI / fl;
  25375. x = 0.5 * Math.tan(ang / 2);
  25376. y = 0.5;
  25377. // positions, uvs, colors
  25378. for (i = 0; i < fl; i++) {
  25379. // positions
  25380. 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);
  25381. indexes.push(index);
  25382. index++;
  25383. // uvs
  25384. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  25385. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  25386. uvs.push(u, v);
  25387. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  25388. y = x * Math.sin(ang) + y * Math.cos(ang);
  25389. x = tmp;
  25390. // colors
  25391. if (faceColors) {
  25392. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  25393. }
  25394. }
  25395. // indices from indexes
  25396. for (i = 0; i < fl - 2; i++) {
  25397. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  25398. }
  25399. faceIdx += fl;
  25400. }
  25401. }
  25402. VertexData.ComputeNormals(positions, indices, normals);
  25403. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25404. var vertexData = new VertexData();
  25405. vertexData.positions = positions;
  25406. vertexData.indices = indices;
  25407. vertexData.normals = normals;
  25408. vertexData.uvs = uvs;
  25409. if (faceColors && flat) {
  25410. vertexData.colors = colors;
  25411. }
  25412. return vertexData;
  25413. };
  25414. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25415. /**
  25416. * Creates the VertexData of the Torus Knot.
  25417. */
  25418. VertexData.CreateTorusKnot = function (options) {
  25419. var indices = [];
  25420. var positions = [];
  25421. var normals = [];
  25422. var uvs = [];
  25423. var radius = options.radius || 2;
  25424. var tube = options.tube || 0.5;
  25425. var radialSegments = options.radialSegments || 32;
  25426. var tubularSegments = options.tubularSegments || 32;
  25427. var p = options.p || 2;
  25428. var q = options.q || 3;
  25429. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25430. // Helper
  25431. var getPos = function (angle) {
  25432. var cu = Math.cos(angle);
  25433. var su = Math.sin(angle);
  25434. var quOverP = q / p * angle;
  25435. var cs = Math.cos(quOverP);
  25436. var tx = radius * (2 + cs) * 0.5 * cu;
  25437. var ty = radius * (2 + cs) * su * 0.5;
  25438. var tz = radius * Math.sin(quOverP) * 0.5;
  25439. return new BABYLON.Vector3(tx, ty, tz);
  25440. };
  25441. // Vertices
  25442. var i;
  25443. var j;
  25444. for (i = 0; i <= radialSegments; i++) {
  25445. var modI = i % radialSegments;
  25446. var u = modI / radialSegments * 2 * p * Math.PI;
  25447. var p1 = getPos(u);
  25448. var p2 = getPos(u + 0.01);
  25449. var tang = p2.subtract(p1);
  25450. var n = p2.add(p1);
  25451. var bitan = BABYLON.Vector3.Cross(tang, n);
  25452. n = BABYLON.Vector3.Cross(bitan, tang);
  25453. bitan.normalize();
  25454. n.normalize();
  25455. for (j = 0; j < tubularSegments; j++) {
  25456. var modJ = j % tubularSegments;
  25457. var v = modJ / tubularSegments * 2 * Math.PI;
  25458. var cx = -tube * Math.cos(v);
  25459. var cy = tube * Math.sin(v);
  25460. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25461. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25462. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25463. uvs.push(i / radialSegments);
  25464. uvs.push(j / tubularSegments);
  25465. }
  25466. }
  25467. for (i = 0; i < radialSegments; i++) {
  25468. for (j = 0; j < tubularSegments; j++) {
  25469. var jNext = (j + 1) % tubularSegments;
  25470. var a = i * tubularSegments + j;
  25471. var b = (i + 1) * tubularSegments + j;
  25472. var c = (i + 1) * tubularSegments + jNext;
  25473. var d = i * tubularSegments + jNext;
  25474. indices.push(d);
  25475. indices.push(b);
  25476. indices.push(a);
  25477. indices.push(d);
  25478. indices.push(c);
  25479. indices.push(b);
  25480. }
  25481. }
  25482. // Normals
  25483. VertexData.ComputeNormals(positions, indices, normals);
  25484. // Sides
  25485. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25486. // Result
  25487. var vertexData = new VertexData();
  25488. vertexData.indices = indices;
  25489. vertexData.positions = positions;
  25490. vertexData.normals = normals;
  25491. vertexData.uvs = uvs;
  25492. return vertexData;
  25493. };
  25494. // Tools
  25495. /**
  25496. * @param {any} - positions (number[] or Float32Array)
  25497. * @param {any} - indices (number[] or Uint16Array)
  25498. * @param {any} - normals (number[] or Float32Array)
  25499. * options (optional) :
  25500. * facetPositions : optional array of facet positions (vector3)
  25501. * facetNormals : optional array of facet normals (vector3)
  25502. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  25503. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  25504. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  25505. * bbSize : optional bounding box size data, required for facetPartitioning computation
  25506. * bInfo : optional bounding info, required for facetPartitioning computation
  25507. */
  25508. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  25509. // temporary scalar variables
  25510. var index = 0; // facet index
  25511. var p1p2x = 0.0; // p1p2 vector x coordinate
  25512. var p1p2y = 0.0; // p1p2 vector y coordinate
  25513. var p1p2z = 0.0; // p1p2 vector z coordinate
  25514. var p3p2x = 0.0; // p3p2 vector x coordinate
  25515. var p3p2y = 0.0; // p3p2 vector y coordinate
  25516. var p3p2z = 0.0; // p3p2 vector z coordinate
  25517. var faceNormalx = 0.0; // facet normal x coordinate
  25518. var faceNormaly = 0.0; // facet normal y coordinate
  25519. var faceNormalz = 0.0; // facet normal z coordinate
  25520. var length = 0.0; // facet normal length before normalization
  25521. var v1x = 0; // vector1 x index in the positions array
  25522. var v1y = 0; // vector1 y index in the positions array
  25523. var v1z = 0; // vector1 z index in the positions array
  25524. var v2x = 0; // vector2 x index in the positions array
  25525. var v2y = 0; // vector2 y index in the positions array
  25526. var v2z = 0; // vector2 z index in the positions array
  25527. var v3x = 0; // vector3 x index in the positions array
  25528. var v3y = 0; // vector3 y index in the positions array
  25529. var v3z = 0; // vector3 z index in the positions array
  25530. var computeFacetNormals = false;
  25531. var computeFacetPositions = false;
  25532. var computeFacetPartitioning = false;
  25533. var faceNormalSign = 1;
  25534. if (options) {
  25535. computeFacetNormals = (options.facetNormals) ? true : false;
  25536. computeFacetPositions = (options.facetPositions) ? true : false;
  25537. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  25538. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  25539. }
  25540. // facetPartitioning reinit if needed
  25541. if (computeFacetPartitioning) {
  25542. var ox = 0; // X partitioning index for facet position
  25543. var oy = 0; // Y partinioning index for facet position
  25544. var oz = 0; // Z partinioning index for facet position
  25545. var b1x = 0; // X partitioning index for facet v1 vertex
  25546. var b1y = 0; // Y partitioning index for facet v1 vertex
  25547. var b1z = 0; // z partitioning index for facet v1 vertex
  25548. var b2x = 0; // X partitioning index for facet v2 vertex
  25549. var b2y = 0; // Y partitioning index for facet v2 vertex
  25550. var b2z = 0; // Z partitioning index for facet v2 vertex
  25551. var b3x = 0; // X partitioning index for facet v3 vertex
  25552. var b3y = 0; // Y partitioning index for facet v3 vertex
  25553. var b3z = 0; // Z partitioning index for facet v3 vertex
  25554. var block_idx_o = 0; // facet barycenter block index
  25555. var block_idx_v1 = 0; // v1 vertex block index
  25556. var block_idx_v2 = 0; // v2 vertex block index
  25557. var block_idx_v3 = 0; // v3 vertex block index
  25558. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  25559. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  25560. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  25561. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  25562. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  25563. var subSq = options.subDiv.max * options.subDiv.max;
  25564. options.facetPartitioning.length = 0;
  25565. }
  25566. // reset the normals
  25567. for (index = 0; index < positions.length; index++) {
  25568. normals[index] = 0.0;
  25569. }
  25570. // Loop : 1 indice triplet = 1 facet
  25571. var nbFaces = indices.length / 3;
  25572. for (index = 0; index < nbFaces; index++) {
  25573. // get the indexes of the coordinates of each vertex of the facet
  25574. v1x = indices[index * 3] * 3;
  25575. v1y = v1x + 1;
  25576. v1z = v1x + 2;
  25577. v2x = indices[index * 3 + 1] * 3;
  25578. v2y = v2x + 1;
  25579. v2z = v2x + 2;
  25580. v3x = indices[index * 3 + 2] * 3;
  25581. v3y = v3x + 1;
  25582. v3z = v3x + 2;
  25583. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  25584. p1p2y = positions[v1y] - positions[v2y];
  25585. p1p2z = positions[v1z] - positions[v2z];
  25586. p3p2x = positions[v3x] - positions[v2x];
  25587. p3p2y = positions[v3y] - positions[v2y];
  25588. p3p2z = positions[v3z] - positions[v2z];
  25589. // compute the face normal with the cross product
  25590. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  25591. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  25592. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  25593. // normalize this normal and store it in the array facetData
  25594. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25595. length = (length === 0) ? 1.0 : length;
  25596. faceNormalx /= length;
  25597. faceNormaly /= length;
  25598. faceNormalz /= length;
  25599. if (computeFacetNormals) {
  25600. options.facetNormals[index].x = faceNormalx;
  25601. options.facetNormals[index].y = faceNormaly;
  25602. options.facetNormals[index].z = faceNormalz;
  25603. }
  25604. if (computeFacetPositions) {
  25605. // compute and the facet barycenter coordinates in the array facetPositions
  25606. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  25607. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  25608. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  25609. }
  25610. if (computeFacetPartitioning) {
  25611. // store the facet indexes in arrays in the main facetPartitioning array :
  25612. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  25613. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25614. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25615. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25616. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25617. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25618. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25619. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25620. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25621. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25622. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25623. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25624. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25625. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  25626. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  25627. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  25628. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  25629. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  25630. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  25631. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  25632. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  25633. // push each facet index in each block containing the vertex
  25634. options.facetPartitioning[block_idx_v1].push(index);
  25635. if (block_idx_v2 != block_idx_v1) {
  25636. options.facetPartitioning[block_idx_v2].push(index);
  25637. }
  25638. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  25639. options.facetPartitioning[block_idx_v3].push(index);
  25640. }
  25641. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  25642. options.facetPartitioning[block_idx_o].push(index);
  25643. }
  25644. }
  25645. // compute the normals anyway
  25646. normals[v1x] += faceNormalx; // accumulate all the normals per face
  25647. normals[v1y] += faceNormaly;
  25648. normals[v1z] += faceNormalz;
  25649. normals[v2x] += faceNormalx;
  25650. normals[v2y] += faceNormaly;
  25651. normals[v2z] += faceNormalz;
  25652. normals[v3x] += faceNormalx;
  25653. normals[v3y] += faceNormaly;
  25654. normals[v3z] += faceNormalz;
  25655. }
  25656. // last normalization of each normal
  25657. for (index = 0; index < normals.length / 3; index++) {
  25658. faceNormalx = normals[index * 3];
  25659. faceNormaly = normals[index * 3 + 1];
  25660. faceNormalz = normals[index * 3 + 2];
  25661. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25662. length = (length === 0) ? 1.0 : length;
  25663. faceNormalx /= length;
  25664. faceNormaly /= length;
  25665. faceNormalz /= length;
  25666. normals[index * 3] = faceNormalx;
  25667. normals[index * 3 + 1] = faceNormaly;
  25668. normals[index * 3 + 2] = faceNormalz;
  25669. }
  25670. };
  25671. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25672. var li = indices.length;
  25673. var ln = normals.length;
  25674. var i;
  25675. var n;
  25676. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25677. switch (sideOrientation) {
  25678. case BABYLON.Mesh.FRONTSIDE:
  25679. // nothing changed
  25680. break;
  25681. case BABYLON.Mesh.BACKSIDE:
  25682. var tmp;
  25683. // indices
  25684. for (i = 0; i < li; i += 3) {
  25685. tmp = indices[i];
  25686. indices[i] = indices[i + 2];
  25687. indices[i + 2] = tmp;
  25688. }
  25689. // normals
  25690. for (n = 0; n < ln; n++) {
  25691. normals[n] = -normals[n];
  25692. }
  25693. break;
  25694. case BABYLON.Mesh.DOUBLESIDE:
  25695. // positions
  25696. var lp = positions.length;
  25697. var l = lp / 3;
  25698. for (var p = 0; p < lp; p++) {
  25699. positions[lp + p] = positions[p];
  25700. }
  25701. // indices
  25702. for (i = 0; i < li; i += 3) {
  25703. indices[i + li] = indices[i + 2] + l;
  25704. indices[i + 1 + li] = indices[i + 1] + l;
  25705. indices[i + 2 + li] = indices[i] + l;
  25706. }
  25707. // normals
  25708. for (n = 0; n < ln; n++) {
  25709. normals[ln + n] = -normals[n];
  25710. }
  25711. // uvs
  25712. var lu = uvs.length;
  25713. for (var u = 0; u < lu; u++) {
  25714. uvs[u + lu] = uvs[u];
  25715. }
  25716. break;
  25717. }
  25718. };
  25719. /**
  25720. * Creates a new VertexData from the imported parameters.
  25721. */
  25722. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  25723. var vertexData = new VertexData();
  25724. // positions
  25725. var positions = parsedVertexData.positions;
  25726. if (positions) {
  25727. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  25728. }
  25729. // normals
  25730. var normals = parsedVertexData.normals;
  25731. if (normals) {
  25732. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  25733. }
  25734. // tangents
  25735. var tangents = parsedVertexData.tangents;
  25736. if (tangents) {
  25737. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  25738. }
  25739. // uvs
  25740. var uvs = parsedVertexData.uvs;
  25741. if (uvs) {
  25742. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  25743. }
  25744. // uv2s
  25745. var uv2s = parsedVertexData.uv2s;
  25746. if (uv2s) {
  25747. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  25748. }
  25749. // uv3s
  25750. var uv3s = parsedVertexData.uv3s;
  25751. if (uv3s) {
  25752. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  25753. }
  25754. // uv4s
  25755. var uv4s = parsedVertexData.uv4s;
  25756. if (uv4s) {
  25757. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  25758. }
  25759. // uv5s
  25760. var uv5s = parsedVertexData.uv5s;
  25761. if (uv5s) {
  25762. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  25763. }
  25764. // uv6s
  25765. var uv6s = parsedVertexData.uv6s;
  25766. if (uv6s) {
  25767. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  25768. }
  25769. // colors
  25770. var colors = parsedVertexData.colors;
  25771. if (colors) {
  25772. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  25773. }
  25774. // matricesIndices
  25775. var matricesIndices = parsedVertexData.matricesIndices;
  25776. if (matricesIndices) {
  25777. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  25778. }
  25779. // matricesWeights
  25780. var matricesWeights = parsedVertexData.matricesWeights;
  25781. if (matricesWeights) {
  25782. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  25783. }
  25784. // indices
  25785. var indices = parsedVertexData.indices;
  25786. if (indices) {
  25787. vertexData.indices = indices;
  25788. }
  25789. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  25790. };
  25791. return VertexData;
  25792. }());
  25793. BABYLON.VertexData = VertexData;
  25794. })(BABYLON || (BABYLON = {}));
  25795. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  25796. var BABYLON;
  25797. (function (BABYLON) {
  25798. var Geometry = (function () {
  25799. function Geometry(id, scene, vertexData, updatable, mesh) {
  25800. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25801. this._totalVertices = 0;
  25802. this._isDisposed = false;
  25803. this.id = id;
  25804. this._engine = scene.getEngine();
  25805. this._meshes = [];
  25806. this._scene = scene;
  25807. //Init vertex buffer cache
  25808. this._vertexBuffers = {};
  25809. this._indices = [];
  25810. // vertexData
  25811. if (vertexData) {
  25812. this.setAllVerticesData(vertexData, updatable);
  25813. }
  25814. else {
  25815. this._totalVertices = 0;
  25816. this._indices = [];
  25817. }
  25818. if (this._engine.getCaps().vertexArrayObject) {
  25819. this._vertexArrayObjects = {};
  25820. }
  25821. // applyToMesh
  25822. if (mesh) {
  25823. if (mesh.getClassName() === "LinesMesh") {
  25824. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  25825. this.updateExtend();
  25826. }
  25827. this.applyToMesh(mesh);
  25828. mesh.computeWorldMatrix(true);
  25829. }
  25830. }
  25831. Object.defineProperty(Geometry.prototype, "boundingBias", {
  25832. /**
  25833. * 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
  25834. * @returns The Bias Vector
  25835. */
  25836. get: function () {
  25837. return this._boundingBias;
  25838. },
  25839. set: function (value) {
  25840. if (this._boundingBias && this._boundingBias.equals(value)) {
  25841. return;
  25842. }
  25843. this._boundingBias = value.clone();
  25844. this.updateBoundingInfo(true, null);
  25845. },
  25846. enumerable: true,
  25847. configurable: true
  25848. });
  25849. Object.defineProperty(Geometry.prototype, "extend", {
  25850. get: function () {
  25851. return this._extend;
  25852. },
  25853. enumerable: true,
  25854. configurable: true
  25855. });
  25856. Geometry.prototype.getScene = function () {
  25857. return this._scene;
  25858. };
  25859. Geometry.prototype.getEngine = function () {
  25860. return this._engine;
  25861. };
  25862. Geometry.prototype.isReady = function () {
  25863. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25864. };
  25865. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  25866. get: function () {
  25867. for (var index = 0; index < this._meshes.length; index++) {
  25868. if (!this._meshes[index].doNotSerialize) {
  25869. return false;
  25870. }
  25871. }
  25872. return true;
  25873. },
  25874. enumerable: true,
  25875. configurable: true
  25876. });
  25877. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25878. vertexData.applyToGeometry(this, updatable);
  25879. this.notifyUpdate();
  25880. };
  25881. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25882. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25883. this.setVerticesBuffer(buffer);
  25884. };
  25885. Geometry.prototype.removeVerticesData = function (kind) {
  25886. if (this._vertexBuffers[kind]) {
  25887. this._vertexBuffers[kind].dispose();
  25888. delete this._vertexBuffers[kind];
  25889. }
  25890. };
  25891. Geometry.prototype.setVerticesBuffer = function (buffer) {
  25892. var kind = buffer.getKind();
  25893. if (this._vertexBuffers[kind]) {
  25894. this._vertexBuffers[kind].dispose();
  25895. }
  25896. this._vertexBuffers[kind] = buffer;
  25897. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25898. var data = buffer.getData();
  25899. var stride = buffer.getStrideSize();
  25900. this._totalVertices = data.length / stride;
  25901. this.updateExtend(data, stride);
  25902. var meshes = this._meshes;
  25903. var numOfMeshes = meshes.length;
  25904. for (var index = 0; index < numOfMeshes; index++) {
  25905. var mesh = meshes[index];
  25906. mesh._resetPointsArrayCache();
  25907. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25908. mesh._createGlobalSubMesh();
  25909. mesh.computeWorldMatrix(true);
  25910. }
  25911. }
  25912. this.notifyUpdate(kind);
  25913. if (this._vertexArrayObjects) {
  25914. this._disposeVertexArrayObjects();
  25915. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  25916. }
  25917. };
  25918. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25919. var vertexBuffer = this.getVertexBuffer(kind);
  25920. if (!vertexBuffer) {
  25921. return;
  25922. }
  25923. vertexBuffer.updateDirectly(data, offset);
  25924. this.notifyUpdate(kind);
  25925. };
  25926. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25927. var vertexBuffer = this.getVertexBuffer(kind);
  25928. if (!vertexBuffer) {
  25929. return;
  25930. }
  25931. vertexBuffer.update(data);
  25932. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25933. var stride = vertexBuffer.getStrideSize();
  25934. this._totalVertices = data.length / stride;
  25935. this.updateBoundingInfo(updateExtends, data);
  25936. }
  25937. this.notifyUpdate(kind);
  25938. };
  25939. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  25940. if (updateExtends) {
  25941. this.updateExtend(data);
  25942. }
  25943. var meshes = this._meshes;
  25944. var numOfMeshes = meshes.length;
  25945. for (var index = 0; index < numOfMeshes; index++) {
  25946. var mesh = meshes[index];
  25947. mesh._resetPointsArrayCache();
  25948. if (updateExtends) {
  25949. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25950. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25951. var subMesh = mesh.subMeshes[subIndex];
  25952. subMesh.refreshBoundingInfo();
  25953. }
  25954. }
  25955. }
  25956. };
  25957. Geometry.prototype._bind = function (effect, indexToBind) {
  25958. if (indexToBind === void 0) { indexToBind = undefined; }
  25959. if (indexToBind === undefined) {
  25960. indexToBind = this._indexBuffer;
  25961. }
  25962. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  25963. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  25964. return;
  25965. }
  25966. // Using VAO
  25967. if (!this._vertexArrayObjects[effect.key]) {
  25968. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  25969. }
  25970. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  25971. };
  25972. Geometry.prototype.getTotalVertices = function () {
  25973. if (!this.isReady()) {
  25974. return 0;
  25975. }
  25976. return this._totalVertices;
  25977. };
  25978. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  25979. var vertexBuffer = this.getVertexBuffer(kind);
  25980. if (!vertexBuffer) {
  25981. return null;
  25982. }
  25983. var orig = vertexBuffer.getData();
  25984. if (!copyWhenShared || this._meshes.length === 1) {
  25985. return orig;
  25986. }
  25987. else {
  25988. var len = orig.length;
  25989. var copy = [];
  25990. for (var i = 0; i < len; i++) {
  25991. copy.push(orig[i]);
  25992. }
  25993. return copy;
  25994. }
  25995. };
  25996. Geometry.prototype.getVertexBuffer = function (kind) {
  25997. if (!this.isReady()) {
  25998. return null;
  25999. }
  26000. return this._vertexBuffers[kind];
  26001. };
  26002. Geometry.prototype.getVertexBuffers = function () {
  26003. if (!this.isReady()) {
  26004. return null;
  26005. }
  26006. return this._vertexBuffers;
  26007. };
  26008. Geometry.prototype.isVerticesDataPresent = function (kind) {
  26009. if (!this._vertexBuffers) {
  26010. if (this._delayInfo) {
  26011. return this._delayInfo.indexOf(kind) !== -1;
  26012. }
  26013. return false;
  26014. }
  26015. return this._vertexBuffers[kind] !== undefined;
  26016. };
  26017. Geometry.prototype.getVerticesDataKinds = function () {
  26018. var result = [];
  26019. var kind;
  26020. if (!this._vertexBuffers && this._delayInfo) {
  26021. for (kind in this._delayInfo) {
  26022. result.push(kind);
  26023. }
  26024. }
  26025. else {
  26026. for (kind in this._vertexBuffers) {
  26027. result.push(kind);
  26028. }
  26029. }
  26030. return result;
  26031. };
  26032. Geometry.prototype.setIndices = function (indices, totalVertices) {
  26033. if (this._indexBuffer) {
  26034. this._engine._releaseBuffer(this._indexBuffer);
  26035. }
  26036. this._disposeVertexArrayObjects();
  26037. this._indices = indices;
  26038. if (this._meshes.length !== 0 && this._indices) {
  26039. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26040. }
  26041. if (totalVertices !== undefined) {
  26042. this._totalVertices = totalVertices;
  26043. }
  26044. var meshes = this._meshes;
  26045. var numOfMeshes = meshes.length;
  26046. for (var index = 0; index < numOfMeshes; index++) {
  26047. meshes[index]._createGlobalSubMesh();
  26048. }
  26049. this.notifyUpdate();
  26050. };
  26051. Geometry.prototype.getTotalIndices = function () {
  26052. if (!this.isReady()) {
  26053. return 0;
  26054. }
  26055. return this._indices.length;
  26056. };
  26057. Geometry.prototype.getIndices = function (copyWhenShared) {
  26058. if (!this.isReady()) {
  26059. return null;
  26060. }
  26061. var orig = this._indices;
  26062. if (!copyWhenShared || this._meshes.length === 1) {
  26063. return orig;
  26064. }
  26065. else {
  26066. var len = orig.length;
  26067. var copy = [];
  26068. for (var i = 0; i < len; i++) {
  26069. copy.push(orig[i]);
  26070. }
  26071. return copy;
  26072. }
  26073. };
  26074. Geometry.prototype.getIndexBuffer = function () {
  26075. if (!this.isReady()) {
  26076. return null;
  26077. }
  26078. return this._indexBuffer;
  26079. };
  26080. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  26081. if (!effect || !this._vertexArrayObjects) {
  26082. return;
  26083. }
  26084. if (this._vertexArrayObjects[effect.key]) {
  26085. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  26086. delete this._vertexArrayObjects[effect.key];
  26087. }
  26088. };
  26089. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26090. var meshes = this._meshes;
  26091. var index = meshes.indexOf(mesh);
  26092. if (index === -1) {
  26093. return;
  26094. }
  26095. meshes.splice(index, 1);
  26096. mesh._geometry = null;
  26097. if (meshes.length === 0 && shouldDispose) {
  26098. this.dispose();
  26099. }
  26100. };
  26101. Geometry.prototype.applyToMesh = function (mesh) {
  26102. if (mesh._geometry === this) {
  26103. return;
  26104. }
  26105. var previousGeometry = mesh._geometry;
  26106. if (previousGeometry) {
  26107. previousGeometry.releaseForMesh(mesh);
  26108. }
  26109. var meshes = this._meshes;
  26110. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26111. mesh._geometry = this;
  26112. this._scene.pushGeometry(this);
  26113. meshes.push(mesh);
  26114. if (this.isReady()) {
  26115. this._applyToMesh(mesh);
  26116. }
  26117. else {
  26118. mesh._boundingInfo = this._boundingInfo;
  26119. }
  26120. };
  26121. Geometry.prototype.updateExtend = function (data, stride) {
  26122. if (data === void 0) { data = null; }
  26123. if (!data) {
  26124. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  26125. }
  26126. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  26127. };
  26128. Geometry.prototype._applyToMesh = function (mesh) {
  26129. var numOfMeshes = this._meshes.length;
  26130. // vertexBuffers
  26131. for (var kind in this._vertexBuffers) {
  26132. if (numOfMeshes === 1) {
  26133. this._vertexBuffers[kind].create();
  26134. }
  26135. var buffer = this._vertexBuffers[kind].getBuffer();
  26136. if (buffer)
  26137. buffer.references = numOfMeshes;
  26138. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26139. mesh._resetPointsArrayCache();
  26140. if (!this._extend) {
  26141. this.updateExtend(this._vertexBuffers[kind].getData());
  26142. }
  26143. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26144. mesh._createGlobalSubMesh();
  26145. //bounding info was just created again, world matrix should be applied again.
  26146. mesh._updateBoundingInfo();
  26147. }
  26148. }
  26149. // indexBuffer
  26150. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  26151. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26152. }
  26153. if (this._indexBuffer) {
  26154. this._indexBuffer.references = numOfMeshes;
  26155. }
  26156. };
  26157. Geometry.prototype.notifyUpdate = function (kind) {
  26158. if (this.onGeometryUpdated) {
  26159. this.onGeometryUpdated(this, kind);
  26160. }
  26161. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  26162. var mesh = _a[_i];
  26163. mesh._markSubMeshesAsAttributesDirty();
  26164. }
  26165. };
  26166. Geometry.prototype.load = function (scene, onLoaded) {
  26167. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26168. return;
  26169. }
  26170. if (this.isReady()) {
  26171. if (onLoaded) {
  26172. onLoaded();
  26173. }
  26174. return;
  26175. }
  26176. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26177. this._queueLoad(scene, onLoaded);
  26178. };
  26179. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  26180. var _this = this;
  26181. scene._addPendingData(this);
  26182. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26183. _this._delayLoadingFunction(JSON.parse(data), _this);
  26184. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26185. _this._delayInfo = [];
  26186. scene._removePendingData(_this);
  26187. var meshes = _this._meshes;
  26188. var numOfMeshes = meshes.length;
  26189. for (var index = 0; index < numOfMeshes; index++) {
  26190. _this._applyToMesh(meshes[index]);
  26191. }
  26192. if (onLoaded) {
  26193. onLoaded();
  26194. }
  26195. }, function () { }, scene.database);
  26196. };
  26197. /**
  26198. * Invert the geometry to move from a right handed system to a left handed one.
  26199. */
  26200. Geometry.prototype.toLeftHanded = function () {
  26201. // Flip faces
  26202. var tIndices = this.getIndices(false);
  26203. if (tIndices != null && tIndices.length > 0) {
  26204. for (var i = 0; i < tIndices.length; i += 3) {
  26205. var tTemp = tIndices[i + 0];
  26206. tIndices[i + 0] = tIndices[i + 2];
  26207. tIndices[i + 2] = tTemp;
  26208. }
  26209. this.setIndices(tIndices);
  26210. }
  26211. // Negate position.z
  26212. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  26213. if (tPositions != null && tPositions.length > 0) {
  26214. for (var i = 0; i < tPositions.length; i += 3) {
  26215. tPositions[i + 2] = -tPositions[i + 2];
  26216. }
  26217. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  26218. }
  26219. // Negate normal.z
  26220. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  26221. if (tNormals != null && tNormals.length > 0) {
  26222. for (var i = 0; i < tNormals.length; i += 3) {
  26223. tNormals[i + 2] = -tNormals[i + 2];
  26224. }
  26225. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  26226. }
  26227. };
  26228. Geometry.prototype.isDisposed = function () {
  26229. return this._isDisposed;
  26230. };
  26231. Geometry.prototype._disposeVertexArrayObjects = function () {
  26232. if (this._vertexArrayObjects) {
  26233. for (var kind in this._vertexArrayObjects) {
  26234. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  26235. }
  26236. this._vertexArrayObjects = {};
  26237. }
  26238. };
  26239. Geometry.prototype.dispose = function () {
  26240. var meshes = this._meshes;
  26241. var numOfMeshes = meshes.length;
  26242. var index;
  26243. for (index = 0; index < numOfMeshes; index++) {
  26244. this.releaseForMesh(meshes[index]);
  26245. }
  26246. this._meshes = [];
  26247. this._disposeVertexArrayObjects();
  26248. for (var kind in this._vertexBuffers) {
  26249. this._vertexBuffers[kind].dispose();
  26250. }
  26251. this._vertexBuffers = {};
  26252. this._totalVertices = 0;
  26253. if (this._indexBuffer) {
  26254. this._engine._releaseBuffer(this._indexBuffer);
  26255. }
  26256. this._indexBuffer = null;
  26257. this._indices = [];
  26258. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26259. this.delayLoadingFile = null;
  26260. this._delayLoadingFunction = null;
  26261. this._delayInfo = [];
  26262. this._boundingInfo = null;
  26263. this._scene.removeGeometry(this);
  26264. this._isDisposed = true;
  26265. };
  26266. Geometry.prototype.copy = function (id) {
  26267. var vertexData = new BABYLON.VertexData();
  26268. vertexData.indices = [];
  26269. var indices = this.getIndices();
  26270. for (var index = 0; index < indices.length; index++) {
  26271. vertexData.indices.push(indices[index]);
  26272. }
  26273. var updatable = false;
  26274. var stopChecking = false;
  26275. var kind;
  26276. for (kind in this._vertexBuffers) {
  26277. // using slice() to make a copy of the array and not just reference it
  26278. var data = this.getVerticesData(kind);
  26279. if (data instanceof Float32Array) {
  26280. vertexData.set(new Float32Array(data), kind);
  26281. }
  26282. else {
  26283. vertexData.set(data.slice(0), kind);
  26284. }
  26285. if (!stopChecking) {
  26286. updatable = this.getVertexBuffer(kind).isUpdatable();
  26287. stopChecking = !updatable;
  26288. }
  26289. }
  26290. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26291. geometry.delayLoadState = this.delayLoadState;
  26292. geometry.delayLoadingFile = this.delayLoadingFile;
  26293. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26294. for (kind in this._delayInfo) {
  26295. geometry._delayInfo = geometry._delayInfo || [];
  26296. geometry._delayInfo.push(kind);
  26297. }
  26298. // Bounding info
  26299. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26300. return geometry;
  26301. };
  26302. Geometry.prototype.serialize = function () {
  26303. var serializationObject = {};
  26304. serializationObject.id = this.id;
  26305. if (BABYLON.Tags.HasTags(this)) {
  26306. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26307. }
  26308. return serializationObject;
  26309. };
  26310. Geometry.prototype.serializeVerticeData = function () {
  26311. var serializationObject = this.serialize();
  26312. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26313. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26314. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  26315. serializationObject.positions._updatable = true;
  26316. }
  26317. }
  26318. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26319. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26320. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  26321. serializationObject.normals._updatable = true;
  26322. }
  26323. }
  26324. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26325. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26326. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  26327. serializationObject.uvs._updatable = true;
  26328. }
  26329. }
  26330. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26331. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  26332. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  26333. serializationObject.uv2s._updatable = true;
  26334. }
  26335. }
  26336. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26337. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  26338. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  26339. serializationObject.uv3s._updatable = true;
  26340. }
  26341. }
  26342. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26343. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  26344. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  26345. serializationObject.uv4s._updatable = true;
  26346. }
  26347. }
  26348. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26349. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  26350. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  26351. serializationObject.uv5s._updatable = true;
  26352. }
  26353. }
  26354. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26355. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  26356. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  26357. serializationObject.uv6s._updatable = true;
  26358. }
  26359. }
  26360. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26361. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26362. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  26363. serializationObject.colors._updatable = true;
  26364. }
  26365. }
  26366. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26367. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26368. serializationObject.matricesIndices._isExpanded = true;
  26369. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  26370. serializationObject.matricesIndices._updatable = true;
  26371. }
  26372. }
  26373. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26374. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26375. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  26376. serializationObject.matricesWeights._updatable = true;
  26377. }
  26378. }
  26379. serializationObject.indices = this.getIndices();
  26380. return serializationObject;
  26381. };
  26382. // Statics
  26383. Geometry.ExtractFromMesh = function (mesh, id) {
  26384. var geometry = mesh._geometry;
  26385. if (!geometry) {
  26386. return null;
  26387. }
  26388. return geometry.copy(id);
  26389. };
  26390. /**
  26391. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  26392. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26393. * Be aware Math.random() could cause collisions, but:
  26394. * "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"
  26395. */
  26396. Geometry.RandomId = function () {
  26397. return BABYLON.Tools.RandomId();
  26398. };
  26399. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  26400. var scene = mesh.getScene();
  26401. // Geometry
  26402. var geometryId = parsedGeometry.geometryId;
  26403. if (geometryId) {
  26404. var geometry = scene.getGeometryByID(geometryId);
  26405. if (geometry) {
  26406. geometry.applyToMesh(mesh);
  26407. }
  26408. }
  26409. else if (parsedGeometry instanceof ArrayBuffer) {
  26410. var binaryInfo = mesh._binaryInfo;
  26411. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  26412. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  26413. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  26414. }
  26415. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  26416. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  26417. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  26418. }
  26419. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  26420. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  26421. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  26422. }
  26423. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  26424. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  26425. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  26426. }
  26427. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  26428. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  26429. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  26430. }
  26431. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  26432. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  26433. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  26434. }
  26435. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  26436. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  26437. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  26438. }
  26439. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  26440. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  26441. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  26442. }
  26443. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  26444. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  26445. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  26446. }
  26447. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  26448. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  26449. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  26450. }
  26451. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  26452. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  26453. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  26454. }
  26455. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  26456. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  26457. mesh.setIndices(indicesData);
  26458. }
  26459. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  26460. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  26461. mesh.subMeshes = [];
  26462. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  26463. var materialIndex = subMeshesData[(i * 5) + 0];
  26464. var verticesStart = subMeshesData[(i * 5) + 1];
  26465. var verticesCount = subMeshesData[(i * 5) + 2];
  26466. var indexStart = subMeshesData[(i * 5) + 3];
  26467. var indexCount = subMeshesData[(i * 5) + 4];
  26468. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  26469. }
  26470. }
  26471. }
  26472. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  26473. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  26474. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  26475. if (parsedGeometry.uvs) {
  26476. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  26477. }
  26478. if (parsedGeometry.uvs2) {
  26479. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  26480. }
  26481. if (parsedGeometry.uvs3) {
  26482. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  26483. }
  26484. if (parsedGeometry.uvs4) {
  26485. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  26486. }
  26487. if (parsedGeometry.uvs5) {
  26488. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  26489. }
  26490. if (parsedGeometry.uvs6) {
  26491. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  26492. }
  26493. if (parsedGeometry.colors) {
  26494. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  26495. }
  26496. if (parsedGeometry.matricesIndices) {
  26497. if (!parsedGeometry.matricesIndices._isExpanded) {
  26498. var floatIndices = [];
  26499. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  26500. var matricesIndex = parsedGeometry.matricesIndices[i];
  26501. floatIndices.push(matricesIndex & 0x000000FF);
  26502. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26503. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26504. floatIndices.push(matricesIndex >> 24);
  26505. }
  26506. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  26507. }
  26508. else {
  26509. delete parsedGeometry.matricesIndices._isExpanded;
  26510. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  26511. }
  26512. }
  26513. if (parsedGeometry.matricesIndicesExtra) {
  26514. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  26515. var floatIndices = [];
  26516. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  26517. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  26518. floatIndices.push(matricesIndex & 0x000000FF);
  26519. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26520. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26521. floatIndices.push(matricesIndex >> 24);
  26522. }
  26523. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  26524. }
  26525. else {
  26526. delete parsedGeometry.matricesIndices._isExpanded;
  26527. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  26528. }
  26529. }
  26530. if (parsedGeometry.matricesWeights) {
  26531. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  26532. }
  26533. if (parsedGeometry.matricesWeightsExtra) {
  26534. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  26535. }
  26536. mesh.setIndices(parsedGeometry.indices);
  26537. }
  26538. // SubMeshes
  26539. if (parsedGeometry.subMeshes) {
  26540. mesh.subMeshes = [];
  26541. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  26542. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  26543. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  26544. }
  26545. }
  26546. // Flat shading
  26547. if (mesh._shouldGenerateFlatShading) {
  26548. mesh.convertToFlatShadedMesh();
  26549. delete mesh._shouldGenerateFlatShading;
  26550. }
  26551. // Update
  26552. mesh.computeWorldMatrix(true);
  26553. // Octree
  26554. if (scene['_selectionOctree']) {
  26555. scene['_selectionOctree'].addMesh(mesh);
  26556. }
  26557. };
  26558. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  26559. if (scene.getGeometryByID(parsedVertexData.id)) {
  26560. return null; // null since geometry could be something else than a box...
  26561. }
  26562. var geometry = new Geometry(parsedVertexData.id, scene);
  26563. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  26564. if (parsedVertexData.delayLoadingFile) {
  26565. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26566. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  26567. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  26568. geometry._delayInfo = [];
  26569. if (parsedVertexData.hasUVs) {
  26570. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26571. }
  26572. if (parsedVertexData.hasUVs2) {
  26573. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26574. }
  26575. if (parsedVertexData.hasUVs3) {
  26576. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26577. }
  26578. if (parsedVertexData.hasUVs4) {
  26579. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26580. }
  26581. if (parsedVertexData.hasUVs5) {
  26582. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26583. }
  26584. if (parsedVertexData.hasUVs6) {
  26585. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26586. }
  26587. if (parsedVertexData.hasColors) {
  26588. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26589. }
  26590. if (parsedVertexData.hasMatricesIndices) {
  26591. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26592. }
  26593. if (parsedVertexData.hasMatricesWeights) {
  26594. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26595. }
  26596. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  26597. }
  26598. else {
  26599. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  26600. }
  26601. scene.pushGeometry(geometry, true);
  26602. return geometry;
  26603. };
  26604. return Geometry;
  26605. }());
  26606. BABYLON.Geometry = Geometry;
  26607. /////// Primitives //////////////////////////////////////////////
  26608. (function (Geometry) {
  26609. var Primitives;
  26610. (function (Primitives) {
  26611. /// Abstract class
  26612. var _Primitive = (function (_super) {
  26613. __extends(_Primitive, _super);
  26614. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  26615. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  26616. _this._canBeRegenerated = _canBeRegenerated;
  26617. _this._beingRegenerated = true;
  26618. _this.regenerate();
  26619. _this._beingRegenerated = false;
  26620. return _this;
  26621. }
  26622. _Primitive.prototype.canBeRegenerated = function () {
  26623. return this._canBeRegenerated;
  26624. };
  26625. _Primitive.prototype.regenerate = function () {
  26626. if (!this._canBeRegenerated) {
  26627. return;
  26628. }
  26629. this._beingRegenerated = true;
  26630. this.setAllVerticesData(this._regenerateVertexData(), false);
  26631. this._beingRegenerated = false;
  26632. };
  26633. _Primitive.prototype.asNewGeometry = function (id) {
  26634. return _super.prototype.copy.call(this, id);
  26635. };
  26636. // overrides
  26637. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26638. if (!this._beingRegenerated) {
  26639. return;
  26640. }
  26641. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26642. };
  26643. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26644. if (!this._beingRegenerated) {
  26645. return;
  26646. }
  26647. _super.prototype.setVerticesData.call(this, kind, data, false);
  26648. };
  26649. // to override
  26650. // protected
  26651. _Primitive.prototype._regenerateVertexData = function () {
  26652. throw new Error("Abstract method");
  26653. };
  26654. _Primitive.prototype.copy = function (id) {
  26655. throw new Error("Must be overriden in sub-classes.");
  26656. };
  26657. _Primitive.prototype.serialize = function () {
  26658. var serializationObject = _super.prototype.serialize.call(this);
  26659. serializationObject.canBeRegenerated = this.canBeRegenerated();
  26660. return serializationObject;
  26661. };
  26662. return _Primitive;
  26663. }(Geometry));
  26664. Primitives._Primitive = _Primitive;
  26665. var Ribbon = (function (_super) {
  26666. __extends(Ribbon, _super);
  26667. // Members
  26668. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26669. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26670. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26671. _this.pathArray = pathArray;
  26672. _this.closeArray = closeArray;
  26673. _this.closePath = closePath;
  26674. _this.offset = offset;
  26675. _this.side = side;
  26676. return _this;
  26677. }
  26678. Ribbon.prototype._regenerateVertexData = function () {
  26679. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26680. };
  26681. Ribbon.prototype.copy = function (id) {
  26682. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26683. };
  26684. return Ribbon;
  26685. }(_Primitive));
  26686. Primitives.Ribbon = Ribbon;
  26687. var Box = (function (_super) {
  26688. __extends(Box, _super);
  26689. // Members
  26690. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26691. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26692. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26693. _this.size = size;
  26694. _this.side = side;
  26695. return _this;
  26696. }
  26697. Box.prototype._regenerateVertexData = function () {
  26698. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26699. };
  26700. Box.prototype.copy = function (id) {
  26701. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26702. };
  26703. Box.prototype.serialize = function () {
  26704. var serializationObject = _super.prototype.serialize.call(this);
  26705. serializationObject.size = this.size;
  26706. return serializationObject;
  26707. };
  26708. Box.Parse = function (parsedBox, scene) {
  26709. if (scene.getGeometryByID(parsedBox.id)) {
  26710. return null; // null since geometry could be something else than a box...
  26711. }
  26712. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  26713. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  26714. scene.pushGeometry(box, true);
  26715. return box;
  26716. };
  26717. return Box;
  26718. }(_Primitive));
  26719. Primitives.Box = Box;
  26720. var Sphere = (function (_super) {
  26721. __extends(Sphere, _super);
  26722. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26723. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26724. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26725. _this.segments = segments;
  26726. _this.diameter = diameter;
  26727. _this.side = side;
  26728. return _this;
  26729. }
  26730. Sphere.prototype._regenerateVertexData = function () {
  26731. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26732. };
  26733. Sphere.prototype.copy = function (id) {
  26734. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26735. };
  26736. Sphere.prototype.serialize = function () {
  26737. var serializationObject = _super.prototype.serialize.call(this);
  26738. serializationObject.segments = this.segments;
  26739. serializationObject.diameter = this.diameter;
  26740. return serializationObject;
  26741. };
  26742. Sphere.Parse = function (parsedSphere, scene) {
  26743. if (scene.getGeometryByID(parsedSphere.id)) {
  26744. return null; // null since geometry could be something else than a sphere...
  26745. }
  26746. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  26747. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  26748. scene.pushGeometry(sphere, true);
  26749. return sphere;
  26750. };
  26751. return Sphere;
  26752. }(_Primitive));
  26753. Primitives.Sphere = Sphere;
  26754. var Disc = (function (_super) {
  26755. __extends(Disc, _super);
  26756. // Members
  26757. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  26758. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26759. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26760. _this.radius = radius;
  26761. _this.tessellation = tessellation;
  26762. _this.side = side;
  26763. return _this;
  26764. }
  26765. Disc.prototype._regenerateVertexData = function () {
  26766. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26767. };
  26768. Disc.prototype.copy = function (id) {
  26769. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26770. };
  26771. return Disc;
  26772. }(_Primitive));
  26773. Primitives.Disc = Disc;
  26774. var Cylinder = (function (_super) {
  26775. __extends(Cylinder, _super);
  26776. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26777. if (subdivisions === void 0) { subdivisions = 1; }
  26778. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26779. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26780. _this.height = height;
  26781. _this.diameterTop = diameterTop;
  26782. _this.diameterBottom = diameterBottom;
  26783. _this.tessellation = tessellation;
  26784. _this.subdivisions = subdivisions;
  26785. _this.side = side;
  26786. return _this;
  26787. }
  26788. Cylinder.prototype._regenerateVertexData = function () {
  26789. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26790. };
  26791. Cylinder.prototype.copy = function (id) {
  26792. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26793. };
  26794. Cylinder.prototype.serialize = function () {
  26795. var serializationObject = _super.prototype.serialize.call(this);
  26796. serializationObject.height = this.height;
  26797. serializationObject.diameterTop = this.diameterTop;
  26798. serializationObject.diameterBottom = this.diameterBottom;
  26799. serializationObject.tessellation = this.tessellation;
  26800. return serializationObject;
  26801. };
  26802. Cylinder.Parse = function (parsedCylinder, scene) {
  26803. if (scene.getGeometryByID(parsedCylinder.id)) {
  26804. return null; // null since geometry could be something else than a cylinder...
  26805. }
  26806. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  26807. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  26808. scene.pushGeometry(cylinder, true);
  26809. return cylinder;
  26810. };
  26811. return Cylinder;
  26812. }(_Primitive));
  26813. Primitives.Cylinder = Cylinder;
  26814. var Torus = (function (_super) {
  26815. __extends(Torus, _super);
  26816. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26817. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26818. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26819. _this.diameter = diameter;
  26820. _this.thickness = thickness;
  26821. _this.tessellation = tessellation;
  26822. _this.side = side;
  26823. return _this;
  26824. }
  26825. Torus.prototype._regenerateVertexData = function () {
  26826. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26827. };
  26828. Torus.prototype.copy = function (id) {
  26829. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26830. };
  26831. Torus.prototype.serialize = function () {
  26832. var serializationObject = _super.prototype.serialize.call(this);
  26833. serializationObject.diameter = this.diameter;
  26834. serializationObject.thickness = this.thickness;
  26835. serializationObject.tessellation = this.tessellation;
  26836. return serializationObject;
  26837. };
  26838. Torus.Parse = function (parsedTorus, scene) {
  26839. if (scene.getGeometryByID(parsedTorus.id)) {
  26840. return null; // null since geometry could be something else than a torus...
  26841. }
  26842. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  26843. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  26844. scene.pushGeometry(torus, true);
  26845. return torus;
  26846. };
  26847. return Torus;
  26848. }(_Primitive));
  26849. Primitives.Torus = Torus;
  26850. var Ground = (function (_super) {
  26851. __extends(Ground, _super);
  26852. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26853. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26854. _this.width = width;
  26855. _this.height = height;
  26856. _this.subdivisions = subdivisions;
  26857. return _this;
  26858. }
  26859. Ground.prototype._regenerateVertexData = function () {
  26860. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26861. };
  26862. Ground.prototype.copy = function (id) {
  26863. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26864. };
  26865. Ground.prototype.serialize = function () {
  26866. var serializationObject = _super.prototype.serialize.call(this);
  26867. serializationObject.width = this.width;
  26868. serializationObject.height = this.height;
  26869. serializationObject.subdivisions = this.subdivisions;
  26870. return serializationObject;
  26871. };
  26872. Ground.Parse = function (parsedGround, scene) {
  26873. if (scene.getGeometryByID(parsedGround.id)) {
  26874. return null; // null since geometry could be something else than a ground...
  26875. }
  26876. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  26877. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  26878. scene.pushGeometry(ground, true);
  26879. return ground;
  26880. };
  26881. return Ground;
  26882. }(_Primitive));
  26883. Primitives.Ground = Ground;
  26884. var TiledGround = (function (_super) {
  26885. __extends(TiledGround, _super);
  26886. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26887. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26888. _this.xmin = xmin;
  26889. _this.zmin = zmin;
  26890. _this.xmax = xmax;
  26891. _this.zmax = zmax;
  26892. _this.subdivisions = subdivisions;
  26893. _this.precision = precision;
  26894. return _this;
  26895. }
  26896. TiledGround.prototype._regenerateVertexData = function () {
  26897. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26898. };
  26899. TiledGround.prototype.copy = function (id) {
  26900. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26901. };
  26902. return TiledGround;
  26903. }(_Primitive));
  26904. Primitives.TiledGround = TiledGround;
  26905. var Plane = (function (_super) {
  26906. __extends(Plane, _super);
  26907. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26908. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26909. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26910. _this.size = size;
  26911. _this.side = side;
  26912. return _this;
  26913. }
  26914. Plane.prototype._regenerateVertexData = function () {
  26915. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26916. };
  26917. Plane.prototype.copy = function (id) {
  26918. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26919. };
  26920. Plane.prototype.serialize = function () {
  26921. var serializationObject = _super.prototype.serialize.call(this);
  26922. serializationObject.size = this.size;
  26923. return serializationObject;
  26924. };
  26925. Plane.Parse = function (parsedPlane, scene) {
  26926. if (scene.getGeometryByID(parsedPlane.id)) {
  26927. return null; // null since geometry could be something else than a ground...
  26928. }
  26929. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  26930. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  26931. scene.pushGeometry(plane, true);
  26932. return plane;
  26933. };
  26934. return Plane;
  26935. }(_Primitive));
  26936. Primitives.Plane = Plane;
  26937. var TorusKnot = (function (_super) {
  26938. __extends(TorusKnot, _super);
  26939. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26940. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26941. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26942. _this.radius = radius;
  26943. _this.tube = tube;
  26944. _this.radialSegments = radialSegments;
  26945. _this.tubularSegments = tubularSegments;
  26946. _this.p = p;
  26947. _this.q = q;
  26948. _this.side = side;
  26949. return _this;
  26950. }
  26951. TorusKnot.prototype._regenerateVertexData = function () {
  26952. 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 });
  26953. };
  26954. TorusKnot.prototype.copy = function (id) {
  26955. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26956. };
  26957. TorusKnot.prototype.serialize = function () {
  26958. var serializationObject = _super.prototype.serialize.call(this);
  26959. serializationObject.radius = this.radius;
  26960. serializationObject.tube = this.tube;
  26961. serializationObject.radialSegments = this.radialSegments;
  26962. serializationObject.tubularSegments = this.tubularSegments;
  26963. serializationObject.p = this.p;
  26964. serializationObject.q = this.q;
  26965. return serializationObject;
  26966. };
  26967. ;
  26968. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  26969. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  26970. return null; // null since geometry could be something else than a ground...
  26971. }
  26972. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  26973. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  26974. scene.pushGeometry(torusKnot, true);
  26975. return torusKnot;
  26976. };
  26977. return TorusKnot;
  26978. }(_Primitive));
  26979. Primitives.TorusKnot = TorusKnot;
  26980. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26981. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26982. })(BABYLON || (BABYLON = {}));
  26983. //# sourceMappingURL=babylon.geometry.js.map
  26984. var BABYLON;
  26985. (function (BABYLON) {
  26986. var PostProcessManager = (function () {
  26987. function PostProcessManager(scene) {
  26988. this._vertexBuffers = {};
  26989. this._scene = scene;
  26990. }
  26991. PostProcessManager.prototype._prepareBuffers = function () {
  26992. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  26993. return;
  26994. }
  26995. // VBO
  26996. var vertices = [];
  26997. vertices.push(1, 1);
  26998. vertices.push(-1, 1);
  26999. vertices.push(-1, -1);
  27000. vertices.push(1, -1);
  27001. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27002. // Indices
  27003. var indices = [];
  27004. indices.push(0);
  27005. indices.push(1);
  27006. indices.push(2);
  27007. indices.push(0);
  27008. indices.push(2);
  27009. indices.push(3);
  27010. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  27011. };
  27012. // Methods
  27013. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  27014. var postProcesses = this._scene.activeCamera._postProcesses;
  27015. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27016. return false;
  27017. }
  27018. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  27019. return true;
  27020. };
  27021. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  27022. var engine = this._scene.getEngine();
  27023. for (var index = 0; index < postProcesses.length; index++) {
  27024. if (index < postProcesses.length - 1) {
  27025. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  27026. }
  27027. else {
  27028. if (targetTexture) {
  27029. engine.bindFramebuffer(targetTexture);
  27030. }
  27031. else {
  27032. engine.restoreDefaultFramebuffer();
  27033. }
  27034. }
  27035. var pp = postProcesses[index];
  27036. var effect = pp.apply();
  27037. if (effect) {
  27038. pp.onBeforeRenderObservable.notifyObservers(effect);
  27039. // VBOs
  27040. this._prepareBuffers();
  27041. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27042. // Draw order
  27043. engine.draw(true, 0, 6);
  27044. pp.onAfterRenderObservable.notifyObservers(effect);
  27045. }
  27046. }
  27047. // Restore depth buffer
  27048. engine.setDepthBuffer(true);
  27049. engine.setDepthWrite(true);
  27050. };
  27051. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  27052. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  27053. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  27054. return;
  27055. }
  27056. var engine = this._scene.getEngine();
  27057. for (var index = 0, len = postProcesses.length; index < len; index++) {
  27058. if (index < len - 1) {
  27059. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  27060. }
  27061. else {
  27062. if (targetTexture) {
  27063. engine.bindFramebuffer(targetTexture, faceIndex);
  27064. }
  27065. else {
  27066. engine.restoreDefaultFramebuffer();
  27067. }
  27068. }
  27069. if (doNotPresent) {
  27070. break;
  27071. }
  27072. var pp = postProcesses[index];
  27073. var effect = pp.apply();
  27074. if (effect) {
  27075. pp.onBeforeRenderObservable.notifyObservers(effect);
  27076. // VBOs
  27077. this._prepareBuffers();
  27078. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27079. // Draw order
  27080. engine.draw(true, 0, 6);
  27081. pp.onAfterRenderObservable.notifyObservers(effect);
  27082. }
  27083. }
  27084. // Restore depth buffer
  27085. engine.setDepthBuffer(true);
  27086. engine.setDepthWrite(true);
  27087. };
  27088. PostProcessManager.prototype.dispose = function () {
  27089. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27090. if (buffer) {
  27091. buffer.dispose();
  27092. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27093. }
  27094. if (this._indexBuffer) {
  27095. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27096. this._indexBuffer = null;
  27097. }
  27098. };
  27099. return PostProcessManager;
  27100. }());
  27101. BABYLON.PostProcessManager = PostProcessManager;
  27102. })(BABYLON || (BABYLON = {}));
  27103. //# sourceMappingURL=babylon.postProcessManager.js.map
  27104. var BABYLON;
  27105. (function (BABYLON) {
  27106. var StandardMaterialDefines = (function (_super) {
  27107. __extends(StandardMaterialDefines, _super);
  27108. function StandardMaterialDefines() {
  27109. var _this = _super.call(this) || this;
  27110. _this.DIFFUSE = false;
  27111. _this.AMBIENT = false;
  27112. _this.OPACITY = false;
  27113. _this.OPACITYRGB = false;
  27114. _this.REFLECTION = false;
  27115. _this.EMISSIVE = false;
  27116. _this.SPECULAR = false;
  27117. _this.BUMP = false;
  27118. _this.PARALLAX = false;
  27119. _this.PARALLAXOCCLUSION = false;
  27120. _this.SPECULAROVERALPHA = false;
  27121. _this.CLIPPLANE = false;
  27122. _this.ALPHATEST = false;
  27123. _this.ALPHAFROMDIFFUSE = false;
  27124. _this.POINTSIZE = false;
  27125. _this.FOG = false;
  27126. _this.SPECULARTERM = false;
  27127. _this.DIFFUSEFRESNEL = false;
  27128. _this.OPACITYFRESNEL = false;
  27129. _this.REFLECTIONFRESNEL = false;
  27130. _this.REFRACTIONFRESNEL = false;
  27131. _this.EMISSIVEFRESNEL = false;
  27132. _this.FRESNEL = false;
  27133. _this.NORMAL = false;
  27134. _this.UV1 = false;
  27135. _this.UV2 = false;
  27136. _this.VERTEXCOLOR = false;
  27137. _this.VERTEXALPHA = false;
  27138. _this.NUM_BONE_INFLUENCERS = 0;
  27139. _this.BonesPerMesh = 0;
  27140. _this.INSTANCES = false;
  27141. _this.GLOSSINESS = false;
  27142. _this.ROUGHNESS = false;
  27143. _this.EMISSIVEASILLUMINATION = false;
  27144. _this.LINKEMISSIVEWITHDIFFUSE = false;
  27145. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  27146. _this.LIGHTMAP = false;
  27147. _this.USELIGHTMAPASSHADOWMAP = false;
  27148. _this.REFLECTIONMAP_3D = false;
  27149. _this.REFLECTIONMAP_SPHERICAL = false;
  27150. _this.REFLECTIONMAP_PLANAR = false;
  27151. _this.REFLECTIONMAP_CUBIC = false;
  27152. _this.REFLECTIONMAP_PROJECTION = false;
  27153. _this.REFLECTIONMAP_SKYBOX = false;
  27154. _this.REFLECTIONMAP_EXPLICIT = false;
  27155. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  27156. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  27157. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  27158. _this.INVERTCUBICMAP = false;
  27159. _this.LOGARITHMICDEPTH = false;
  27160. _this.REFRACTION = false;
  27161. _this.REFRACTIONMAP_3D = false;
  27162. _this.REFLECTIONOVERALPHA = false;
  27163. _this.INVERTNORMALMAPX = false;
  27164. _this.INVERTNORMALMAPY = false;
  27165. _this.TWOSIDEDLIGHTING = false;
  27166. _this.SHADOWFULLFLOAT = false;
  27167. _this.CAMERACOLORGRADING = false;
  27168. _this.CAMERACOLORCURVES = false;
  27169. _this.MORPHTARGETS = false;
  27170. _this.MORPHTARGETS_NORMAL = false;
  27171. _this.MORPHTARGETS_TANGENT = false;
  27172. _this.NUM_MORPH_INFLUENCERS = 0;
  27173. _this.rebuild();
  27174. return _this;
  27175. }
  27176. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  27177. var modes = [
  27178. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  27179. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  27180. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  27181. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  27182. ];
  27183. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  27184. var mode = modes_1[_i];
  27185. this[mode] = (mode === modeToEnable);
  27186. }
  27187. };
  27188. return StandardMaterialDefines;
  27189. }(BABYLON.MaterialDefines));
  27190. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  27191. var StandardMaterial = (function (_super) {
  27192. __extends(StandardMaterial, _super);
  27193. function StandardMaterial(name, scene) {
  27194. var _this = _super.call(this, name, scene) || this;
  27195. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  27196. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  27197. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  27198. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  27199. _this.specularPower = 64;
  27200. _this._useAlphaFromDiffuseTexture = false;
  27201. _this._useEmissiveAsIllumination = false;
  27202. _this._linkEmissiveWithDiffuse = false;
  27203. _this._useSpecularOverAlpha = false;
  27204. _this._useReflectionOverAlpha = false;
  27205. _this._disableLighting = false;
  27206. _this._useParallax = false;
  27207. _this._useParallaxOcclusion = false;
  27208. _this.parallaxScaleBias = 0.05;
  27209. _this._roughness = 0;
  27210. _this.indexOfRefraction = 0.98;
  27211. _this.invertRefractionY = true;
  27212. _this._useLightmapAsShadowmap = false;
  27213. _this._useReflectionFresnelFromSpecular = false;
  27214. _this._useGlossinessFromSpecularMapAlpha = false;
  27215. _this._maxSimultaneousLights = 4;
  27216. /**
  27217. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  27218. */
  27219. _this._invertNormalMapX = false;
  27220. /**
  27221. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  27222. */
  27223. _this._invertNormalMapY = false;
  27224. /**
  27225. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  27226. */
  27227. _this._twoSidedLighting = false;
  27228. /**
  27229. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  27230. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  27231. * 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;
  27232. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  27233. */
  27234. _this._cameraColorCurves = null;
  27235. _this._renderTargets = new BABYLON.SmartArray(16);
  27236. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  27237. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  27238. _this.getRenderTargetTextures = function () {
  27239. _this._renderTargets.reset();
  27240. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  27241. _this._renderTargets.push(_this._reflectionTexture);
  27242. }
  27243. if (_this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  27244. _this._renderTargets.push(_this._refractionTexture);
  27245. }
  27246. return _this._renderTargets;
  27247. };
  27248. return _this;
  27249. }
  27250. StandardMaterial.prototype.getClassName = function () {
  27251. return "StandardMaterial";
  27252. };
  27253. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  27254. get: function () {
  27255. return this._useLogarithmicDepth;
  27256. },
  27257. set: function (value) {
  27258. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  27259. this._markAllSubMeshesAsMiscDirty();
  27260. },
  27261. enumerable: true,
  27262. configurable: true
  27263. });
  27264. StandardMaterial.prototype.needAlphaBlending = function () {
  27265. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  27266. };
  27267. StandardMaterial.prototype.needAlphaTesting = function () {
  27268. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  27269. };
  27270. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  27271. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  27272. };
  27273. StandardMaterial.prototype.getAlphaTestTexture = function () {
  27274. return this._diffuseTexture;
  27275. };
  27276. /**
  27277. * Child classes can use it to update shaders
  27278. */
  27279. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27280. if (this.isFrozen) {
  27281. if (this._wasPreviouslyReady && subMesh.effect) {
  27282. return true;
  27283. }
  27284. }
  27285. if (!subMesh._materialDefines) {
  27286. subMesh._materialDefines = new StandardMaterialDefines();
  27287. }
  27288. var scene = this.getScene();
  27289. var defines = subMesh._materialDefines;
  27290. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  27291. if (defines._renderId === scene.getRenderId()) {
  27292. return true;
  27293. }
  27294. }
  27295. var engine = scene.getEngine();
  27296. // Lights
  27297. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  27298. // Textures
  27299. if (defines._areTexturesDirty) {
  27300. defines._needUVs = false;
  27301. if (scene.texturesEnabled) {
  27302. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27303. if (!this._diffuseTexture.isReady()) {
  27304. return false;
  27305. }
  27306. else {
  27307. defines._needUVs = true;
  27308. defines.DIFFUSE = true;
  27309. }
  27310. }
  27311. else {
  27312. defines.DIFFUSE = false;
  27313. }
  27314. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27315. if (!this._ambientTexture.isReady()) {
  27316. return false;
  27317. }
  27318. else {
  27319. defines._needUVs = true;
  27320. defines.AMBIENT = true;
  27321. }
  27322. }
  27323. else {
  27324. defines.AMBIENT = false;
  27325. }
  27326. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27327. if (!this._opacityTexture.isReady()) {
  27328. return false;
  27329. }
  27330. else {
  27331. defines._needUVs = true;
  27332. defines.OPACITY = true;
  27333. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  27334. }
  27335. }
  27336. else {
  27337. defines.OPACITY = false;
  27338. }
  27339. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27340. if (!this._reflectionTexture.isReady()) {
  27341. return false;
  27342. }
  27343. else {
  27344. defines._needNormals = true;
  27345. defines.REFLECTION = true;
  27346. defines.ROUGHNESS = (this._roughness > 0);
  27347. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  27348. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  27349. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  27350. switch (this._reflectionTexture.coordinatesMode) {
  27351. case BABYLON.Texture.CUBIC_MODE:
  27352. case BABYLON.Texture.INVCUBIC_MODE:
  27353. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  27354. break;
  27355. case BABYLON.Texture.EXPLICIT_MODE:
  27356. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  27357. break;
  27358. case BABYLON.Texture.PLANAR_MODE:
  27359. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  27360. break;
  27361. case BABYLON.Texture.PROJECTION_MODE:
  27362. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  27363. break;
  27364. case BABYLON.Texture.SKYBOX_MODE:
  27365. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  27366. break;
  27367. case BABYLON.Texture.SPHERICAL_MODE:
  27368. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  27369. break;
  27370. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  27371. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  27372. break;
  27373. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  27374. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  27375. break;
  27376. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  27377. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  27378. break;
  27379. }
  27380. }
  27381. }
  27382. else {
  27383. defines.REFLECTION = false;
  27384. }
  27385. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27386. if (!this._emissiveTexture.isReady()) {
  27387. return false;
  27388. }
  27389. else {
  27390. defines._needUVs = true;
  27391. defines.EMISSIVE = true;
  27392. }
  27393. }
  27394. else {
  27395. defines.EMISSIVE = false;
  27396. }
  27397. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27398. if (!this._lightmapTexture.isReady()) {
  27399. return false;
  27400. }
  27401. else {
  27402. defines._needUVs = true;
  27403. defines.LIGHTMAP = true;
  27404. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  27405. }
  27406. }
  27407. else {
  27408. defines.LIGHTMAP = false;
  27409. }
  27410. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27411. if (!this._specularTexture.isReady()) {
  27412. return false;
  27413. }
  27414. else {
  27415. defines._needUVs = true;
  27416. defines.SPECULAR = true;
  27417. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  27418. }
  27419. }
  27420. else {
  27421. defines.SPECULAR = false;
  27422. }
  27423. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  27424. if (!this._bumpTexture.isReady()) {
  27425. return false;
  27426. }
  27427. else {
  27428. defines._needUVs = true;
  27429. defines.BUMP = true;
  27430. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  27431. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  27432. defines.PARALLAX = this._useParallax;
  27433. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  27434. }
  27435. }
  27436. else {
  27437. defines.BUMP = false;
  27438. }
  27439. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27440. if (!this._refractionTexture.isReady()) {
  27441. return false;
  27442. }
  27443. else {
  27444. defines._needUVs = true;
  27445. defines.REFRACTION = true;
  27446. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  27447. }
  27448. }
  27449. else {
  27450. defines.REFRACTION = false;
  27451. }
  27452. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27453. if (!this._cameraColorGradingTexture.isReady()) {
  27454. return false;
  27455. }
  27456. else {
  27457. defines.CAMERACOLORGRADING = true;
  27458. }
  27459. }
  27460. else {
  27461. defines.CAMERACOLORGRADING = false;
  27462. }
  27463. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  27464. }
  27465. else {
  27466. defines.DIFFUSE = false;
  27467. defines.AMBIENT = false;
  27468. defines.OPACITY = false;
  27469. defines.REFLECTION = false;
  27470. defines.EMISSIVE = false;
  27471. defines.LIGHTMAP = false;
  27472. defines.BUMP = false;
  27473. defines.REFRACTION = false;
  27474. defines.CAMERACOLORGRADING = false;
  27475. }
  27476. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  27477. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  27478. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  27479. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  27480. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  27481. }
  27482. if (defines._areFresnelDirty) {
  27483. if (StandardMaterial.FresnelEnabled) {
  27484. // Fresnel
  27485. if (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled ||
  27486. this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  27487. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled ||
  27488. this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled ||
  27489. this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled) {
  27490. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  27491. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  27492. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  27493. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  27494. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  27495. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  27496. defines._needNormals = true;
  27497. defines.FRESNEL = true;
  27498. }
  27499. }
  27500. else {
  27501. defines.FRESNEL = false;
  27502. }
  27503. }
  27504. // Misc.
  27505. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  27506. // Attribs
  27507. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  27508. // Values that need to be evaluated on every frame
  27509. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  27510. if (scene._mirroredCameraPosition && defines.BUMP) {
  27511. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  27512. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  27513. defines.markAsUnprocessed();
  27514. }
  27515. // Get correct effect
  27516. if (defines.isDirty) {
  27517. defines.markAsProcessed();
  27518. scene.resetCachedMaterial();
  27519. // Fallbacks
  27520. var fallbacks = new BABYLON.EffectFallbacks();
  27521. if (defines.REFLECTION) {
  27522. fallbacks.addFallback(0, "REFLECTION");
  27523. }
  27524. if (defines.SPECULAR) {
  27525. fallbacks.addFallback(0, "SPECULAR");
  27526. }
  27527. if (defines.BUMP) {
  27528. fallbacks.addFallback(0, "BUMP");
  27529. }
  27530. if (defines.PARALLAX) {
  27531. fallbacks.addFallback(1, "PARALLAX");
  27532. }
  27533. if (defines.PARALLAXOCCLUSION) {
  27534. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  27535. }
  27536. if (defines.SPECULAROVERALPHA) {
  27537. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  27538. }
  27539. if (defines.FOG) {
  27540. fallbacks.addFallback(1, "FOG");
  27541. }
  27542. if (defines.POINTSIZE) {
  27543. fallbacks.addFallback(0, "POINTSIZE");
  27544. }
  27545. if (defines.LOGARITHMICDEPTH) {
  27546. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  27547. }
  27548. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  27549. if (defines.SPECULARTERM) {
  27550. fallbacks.addFallback(0, "SPECULARTERM");
  27551. }
  27552. if (defines.DIFFUSEFRESNEL) {
  27553. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  27554. }
  27555. if (defines.OPACITYFRESNEL) {
  27556. fallbacks.addFallback(2, "OPACITYFRESNEL");
  27557. }
  27558. if (defines.REFLECTIONFRESNEL) {
  27559. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  27560. }
  27561. if (defines.EMISSIVEFRESNEL) {
  27562. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  27563. }
  27564. if (defines.FRESNEL) {
  27565. fallbacks.addFallback(4, "FRESNEL");
  27566. }
  27567. //Attributes
  27568. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27569. if (defines.NORMAL) {
  27570. attribs.push(BABYLON.VertexBuffer.NormalKind);
  27571. }
  27572. if (defines.UV1) {
  27573. attribs.push(BABYLON.VertexBuffer.UVKind);
  27574. }
  27575. if (defines.UV2) {
  27576. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27577. }
  27578. if (defines.VERTEXCOLOR) {
  27579. attribs.push(BABYLON.VertexBuffer.ColorKind);
  27580. }
  27581. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  27582. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  27583. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  27584. var shaderName = "default";
  27585. if (this.customShaderNameResolve) {
  27586. shaderName = this.customShaderNameResolve(shaderName);
  27587. }
  27588. var join = defines.toString();
  27589. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  27590. "vFogInfos", "vFogColor", "pointSize",
  27591. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  27592. "mBones",
  27593. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  27594. "depthValues",
  27595. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  27596. "logarithmicDepthConstant"
  27597. ];
  27598. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  27599. var uniformBuffers = ["Material", "Scene"];
  27600. if (defines.CAMERACOLORCURVES) {
  27601. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  27602. }
  27603. if (defines.CAMERACOLORGRADING) {
  27604. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  27605. }
  27606. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  27607. uniformsNames: uniforms,
  27608. uniformBuffersNames: uniformBuffers,
  27609. samplers: samplers,
  27610. defines: defines,
  27611. maxSimultaneousLights: this._maxSimultaneousLights
  27612. });
  27613. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  27614. attributes: attribs,
  27615. uniformsNames: uniforms,
  27616. uniformBuffersNames: uniformBuffers,
  27617. samplers: samplers,
  27618. defines: join,
  27619. fallbacks: fallbacks,
  27620. onCompiled: this.onCompiled,
  27621. onError: this.onError,
  27622. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  27623. }, engine), defines);
  27624. this.buildUniformLayout();
  27625. }
  27626. if (!subMesh.effect.isReady()) {
  27627. return false;
  27628. }
  27629. defines._renderId = scene.getRenderId();
  27630. this._wasPreviouslyReady = true;
  27631. return true;
  27632. };
  27633. StandardMaterial.prototype.buildUniformLayout = function () {
  27634. // Order is important !
  27635. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  27636. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  27637. this._uniformBuffer.addUniform("opacityParts", 4);
  27638. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  27639. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  27640. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  27641. this._uniformBuffer.addUniform("refractionRightColor", 4);
  27642. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  27643. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  27644. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  27645. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  27646. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  27647. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  27648. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  27649. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  27650. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  27651. this._uniformBuffer.addUniform("vBumpInfos", 3);
  27652. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  27653. this._uniformBuffer.addUniform("ambientMatrix", 16);
  27654. this._uniformBuffer.addUniform("opacityMatrix", 16);
  27655. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  27656. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  27657. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  27658. this._uniformBuffer.addUniform("specularMatrix", 16);
  27659. this._uniformBuffer.addUniform("bumpMatrix", 16);
  27660. this._uniformBuffer.addUniform("refractionMatrix", 16);
  27661. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  27662. this._uniformBuffer.addUniform("vSpecularColor", 4);
  27663. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  27664. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  27665. this._uniformBuffer.addUniform("pointSize", 1);
  27666. this._uniformBuffer.create();
  27667. };
  27668. StandardMaterial.prototype.unbind = function () {
  27669. if (this._activeEffect) {
  27670. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  27671. this._activeEffect.setTexture("reflection2DSampler", null);
  27672. }
  27673. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  27674. this._activeEffect.setTexture("refraction2DSampler", null);
  27675. }
  27676. }
  27677. _super.prototype.unbind.call(this);
  27678. };
  27679. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27680. var scene = this.getScene();
  27681. var defines = subMesh._materialDefines;
  27682. if (!defines) {
  27683. return;
  27684. }
  27685. var effect = subMesh.effect;
  27686. this._activeEffect = effect;
  27687. // Matrices
  27688. this.bindOnlyWorldMatrix(world);
  27689. // Bones
  27690. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  27691. if (this._mustRebind(scene, effect, mesh.visibility)) {
  27692. this._uniformBuffer.bindToEffect(effect, "Material");
  27693. this.bindViewProjection(effect);
  27694. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  27695. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  27696. // Fresnel
  27697. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  27698. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  27699. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  27700. }
  27701. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  27702. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  27703. }
  27704. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27705. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  27706. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  27707. }
  27708. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  27709. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  27710. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  27711. }
  27712. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  27713. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  27714. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  27715. }
  27716. }
  27717. // Textures
  27718. if (scene.texturesEnabled) {
  27719. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27720. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  27721. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  27722. }
  27723. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27724. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  27725. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  27726. }
  27727. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27728. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  27729. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  27730. }
  27731. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27732. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  27733. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  27734. }
  27735. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27736. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  27737. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  27738. }
  27739. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27740. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  27741. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  27742. }
  27743. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27744. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  27745. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  27746. }
  27747. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  27748. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  27749. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  27750. }
  27751. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27752. var depth = 1.0;
  27753. if (!this._refractionTexture.isCube) {
  27754. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  27755. if (this._refractionTexture.depth) {
  27756. depth = this._refractionTexture.depth;
  27757. }
  27758. }
  27759. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  27760. }
  27761. }
  27762. // Point size
  27763. if (this.pointsCloud) {
  27764. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  27765. }
  27766. if (defines.SPECULARTERM) {
  27767. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  27768. }
  27769. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  27770. // Diffuse
  27771. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  27772. }
  27773. // Textures
  27774. if (scene.texturesEnabled) {
  27775. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27776. effect.setTexture("diffuseSampler", this._diffuseTexture);
  27777. }
  27778. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27779. effect.setTexture("ambientSampler", this._ambientTexture);
  27780. }
  27781. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27782. effect.setTexture("opacitySampler", this._opacityTexture);
  27783. }
  27784. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27785. if (this._reflectionTexture.isCube) {
  27786. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  27787. }
  27788. else {
  27789. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  27790. }
  27791. }
  27792. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27793. effect.setTexture("emissiveSampler", this._emissiveTexture);
  27794. }
  27795. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27796. effect.setTexture("lightmapSampler", this._lightmapTexture);
  27797. }
  27798. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27799. effect.setTexture("specularSampler", this._specularTexture);
  27800. }
  27801. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  27802. effect.setTexture("bumpSampler", this._bumpTexture);
  27803. }
  27804. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27805. var depth = 1.0;
  27806. if (this._refractionTexture.isCube) {
  27807. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  27808. }
  27809. else {
  27810. effect.setTexture("refraction2DSampler", this._refractionTexture);
  27811. }
  27812. }
  27813. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27814. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  27815. }
  27816. }
  27817. // Clip plane
  27818. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  27819. // Colors
  27820. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  27821. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  27822. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  27823. }
  27824. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  27825. // Lights
  27826. if (scene.lightsEnabled && !this._disableLighting) {
  27827. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  27828. }
  27829. // View
  27830. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  27831. this.bindView(effect);
  27832. }
  27833. // Fog
  27834. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  27835. // Morph targets
  27836. if (defines.NUM_MORPH_INFLUENCERS) {
  27837. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  27838. }
  27839. // Log. depth
  27840. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  27841. // Color Curves
  27842. if (this._cameraColorCurves) {
  27843. BABYLON.ColorCurves.Bind(this._cameraColorCurves, effect);
  27844. }
  27845. }
  27846. this._uniformBuffer.update();
  27847. this._afterBind(mesh, this._activeEffect);
  27848. };
  27849. StandardMaterial.prototype.getAnimatables = function () {
  27850. var results = [];
  27851. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  27852. results.push(this._diffuseTexture);
  27853. }
  27854. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  27855. results.push(this._ambientTexture);
  27856. }
  27857. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  27858. results.push(this._opacityTexture);
  27859. }
  27860. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  27861. results.push(this._reflectionTexture);
  27862. }
  27863. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  27864. results.push(this._emissiveTexture);
  27865. }
  27866. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  27867. results.push(this._specularTexture);
  27868. }
  27869. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  27870. results.push(this._bumpTexture);
  27871. }
  27872. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  27873. results.push(this._lightmapTexture);
  27874. }
  27875. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  27876. results.push(this._refractionTexture);
  27877. }
  27878. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  27879. results.push(this._cameraColorGradingTexture);
  27880. }
  27881. return results;
  27882. };
  27883. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27884. if (forceDisposeTextures) {
  27885. if (this._diffuseTexture) {
  27886. this._diffuseTexture.dispose();
  27887. }
  27888. if (this._ambientTexture) {
  27889. this._ambientTexture.dispose();
  27890. }
  27891. if (this._opacityTexture) {
  27892. this._opacityTexture.dispose();
  27893. }
  27894. if (this._reflectionTexture) {
  27895. this._reflectionTexture.dispose();
  27896. }
  27897. if (this._emissiveTexture) {
  27898. this._emissiveTexture.dispose();
  27899. }
  27900. if (this._specularTexture) {
  27901. this._specularTexture.dispose();
  27902. }
  27903. if (this._bumpTexture) {
  27904. this._bumpTexture.dispose();
  27905. }
  27906. if (this._lightmapTexture) {
  27907. this._lightmapTexture.dispose();
  27908. }
  27909. if (this._refractionTexture) {
  27910. this._refractionTexture.dispose();
  27911. }
  27912. if (this._cameraColorGradingTexture) {
  27913. this._cameraColorGradingTexture.dispose();
  27914. }
  27915. }
  27916. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  27917. };
  27918. StandardMaterial.prototype.clone = function (name) {
  27919. var _this = this;
  27920. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  27921. result.name = name;
  27922. result.id = name;
  27923. return result;
  27924. };
  27925. StandardMaterial.prototype.serialize = function () {
  27926. return BABYLON.SerializationHelper.Serialize(this);
  27927. };
  27928. // Statics
  27929. StandardMaterial.Parse = function (source, scene, rootUrl) {
  27930. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  27931. };
  27932. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  27933. get: function () {
  27934. return StandardMaterial._DiffuseTextureEnabled;
  27935. },
  27936. set: function (value) {
  27937. if (StandardMaterial._DiffuseTextureEnabled === value) {
  27938. return;
  27939. }
  27940. StandardMaterial._DiffuseTextureEnabled = value;
  27941. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27942. },
  27943. enumerable: true,
  27944. configurable: true
  27945. });
  27946. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  27947. get: function () {
  27948. return StandardMaterial._AmbientTextureEnabled;
  27949. },
  27950. set: function (value) {
  27951. if (StandardMaterial._AmbientTextureEnabled === value) {
  27952. return;
  27953. }
  27954. StandardMaterial._AmbientTextureEnabled = value;
  27955. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27956. },
  27957. enumerable: true,
  27958. configurable: true
  27959. });
  27960. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  27961. get: function () {
  27962. return StandardMaterial._OpacityTextureEnabled;
  27963. },
  27964. set: function (value) {
  27965. if (StandardMaterial._OpacityTextureEnabled === value) {
  27966. return;
  27967. }
  27968. StandardMaterial._OpacityTextureEnabled = value;
  27969. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27970. },
  27971. enumerable: true,
  27972. configurable: true
  27973. });
  27974. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  27975. get: function () {
  27976. return StandardMaterial._ReflectionTextureEnabled;
  27977. },
  27978. set: function (value) {
  27979. if (StandardMaterial._ReflectionTextureEnabled === value) {
  27980. return;
  27981. }
  27982. StandardMaterial._ReflectionTextureEnabled = value;
  27983. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27984. },
  27985. enumerable: true,
  27986. configurable: true
  27987. });
  27988. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  27989. get: function () {
  27990. return StandardMaterial._EmissiveTextureEnabled;
  27991. },
  27992. set: function (value) {
  27993. if (StandardMaterial._EmissiveTextureEnabled === value) {
  27994. return;
  27995. }
  27996. StandardMaterial._EmissiveTextureEnabled = value;
  27997. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27998. },
  27999. enumerable: true,
  28000. configurable: true
  28001. });
  28002. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  28003. get: function () {
  28004. return StandardMaterial._SpecularTextureEnabled;
  28005. },
  28006. set: function (value) {
  28007. if (StandardMaterial._SpecularTextureEnabled === value) {
  28008. return;
  28009. }
  28010. StandardMaterial._SpecularTextureEnabled = value;
  28011. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28012. },
  28013. enumerable: true,
  28014. configurable: true
  28015. });
  28016. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  28017. get: function () {
  28018. return StandardMaterial._BumpTextureEnabled;
  28019. },
  28020. set: function (value) {
  28021. if (StandardMaterial._BumpTextureEnabled === value) {
  28022. return;
  28023. }
  28024. StandardMaterial._BumpTextureEnabled = value;
  28025. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28026. },
  28027. enumerable: true,
  28028. configurable: true
  28029. });
  28030. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  28031. get: function () {
  28032. return StandardMaterial._LightmapTextureEnabled;
  28033. },
  28034. set: function (value) {
  28035. if (StandardMaterial._LightmapTextureEnabled === value) {
  28036. return;
  28037. }
  28038. StandardMaterial._LightmapTextureEnabled = value;
  28039. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28040. },
  28041. enumerable: true,
  28042. configurable: true
  28043. });
  28044. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  28045. get: function () {
  28046. return StandardMaterial._RefractionTextureEnabled;
  28047. },
  28048. set: function (value) {
  28049. if (StandardMaterial._RefractionTextureEnabled === value) {
  28050. return;
  28051. }
  28052. StandardMaterial._RefractionTextureEnabled = value;
  28053. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28054. },
  28055. enumerable: true,
  28056. configurable: true
  28057. });
  28058. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  28059. get: function () {
  28060. return StandardMaterial._ColorGradingTextureEnabled;
  28061. },
  28062. set: function (value) {
  28063. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  28064. return;
  28065. }
  28066. StandardMaterial._ColorGradingTextureEnabled = value;
  28067. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28068. },
  28069. enumerable: true,
  28070. configurable: true
  28071. });
  28072. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  28073. get: function () {
  28074. return StandardMaterial._FresnelEnabled;
  28075. },
  28076. set: function (value) {
  28077. if (StandardMaterial._FresnelEnabled === value) {
  28078. return;
  28079. }
  28080. StandardMaterial._FresnelEnabled = value;
  28081. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  28082. },
  28083. enumerable: true,
  28084. configurable: true
  28085. });
  28086. return StandardMaterial;
  28087. }(BABYLON.PushMaterial));
  28088. // Flags used to enable or disable a type of texture for all Standard Materials
  28089. StandardMaterial._DiffuseTextureEnabled = true;
  28090. StandardMaterial._AmbientTextureEnabled = true;
  28091. StandardMaterial._OpacityTextureEnabled = true;
  28092. StandardMaterial._ReflectionTextureEnabled = true;
  28093. StandardMaterial._EmissiveTextureEnabled = true;
  28094. StandardMaterial._SpecularTextureEnabled = true;
  28095. StandardMaterial._BumpTextureEnabled = true;
  28096. StandardMaterial._LightmapTextureEnabled = true;
  28097. StandardMaterial._RefractionTextureEnabled = true;
  28098. StandardMaterial._ColorGradingTextureEnabled = true;
  28099. StandardMaterial._FresnelEnabled = true;
  28100. __decorate([
  28101. BABYLON.serializeAsTexture("diffuseTexture")
  28102. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  28103. __decorate([
  28104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28105. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  28106. __decorate([
  28107. BABYLON.serializeAsTexture("ambientTexture")
  28108. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  28109. __decorate([
  28110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28111. ], StandardMaterial.prototype, "ambientTexture", void 0);
  28112. __decorate([
  28113. BABYLON.serializeAsTexture("opacityTexture")
  28114. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  28115. __decorate([
  28116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28117. ], StandardMaterial.prototype, "opacityTexture", void 0);
  28118. __decorate([
  28119. BABYLON.serializeAsTexture("reflectionTexture")
  28120. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  28121. __decorate([
  28122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28123. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  28124. __decorate([
  28125. BABYLON.serializeAsTexture("emissiveTexture")
  28126. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  28127. __decorate([
  28128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28129. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  28130. __decorate([
  28131. BABYLON.serializeAsTexture("specularTexture")
  28132. ], StandardMaterial.prototype, "_specularTexture", void 0);
  28133. __decorate([
  28134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28135. ], StandardMaterial.prototype, "specularTexture", void 0);
  28136. __decorate([
  28137. BABYLON.serializeAsTexture("bumpTexture")
  28138. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  28139. __decorate([
  28140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28141. ], StandardMaterial.prototype, "bumpTexture", void 0);
  28142. __decorate([
  28143. BABYLON.serializeAsTexture("lightmapTexture")
  28144. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  28145. __decorate([
  28146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28147. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  28148. __decorate([
  28149. BABYLON.serializeAsTexture("refractionTexture")
  28150. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  28151. __decorate([
  28152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28153. ], StandardMaterial.prototype, "refractionTexture", void 0);
  28154. __decorate([
  28155. BABYLON.serializeAsColor3("ambient")
  28156. ], StandardMaterial.prototype, "ambientColor", void 0);
  28157. __decorate([
  28158. BABYLON.serializeAsColor3("diffuse")
  28159. ], StandardMaterial.prototype, "diffuseColor", void 0);
  28160. __decorate([
  28161. BABYLON.serializeAsColor3("specular")
  28162. ], StandardMaterial.prototype, "specularColor", void 0);
  28163. __decorate([
  28164. BABYLON.serializeAsColor3("emissive")
  28165. ], StandardMaterial.prototype, "emissiveColor", void 0);
  28166. __decorate([
  28167. BABYLON.serialize()
  28168. ], StandardMaterial.prototype, "specularPower", void 0);
  28169. __decorate([
  28170. BABYLON.serialize("useAlphaFromDiffuseTexture")
  28171. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  28172. __decorate([
  28173. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28174. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  28175. __decorate([
  28176. BABYLON.serialize("useEmissiveAsIllumination")
  28177. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  28178. __decorate([
  28179. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28180. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  28181. __decorate([
  28182. BABYLON.serialize("linkEmissiveWithDiffuse")
  28183. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  28184. __decorate([
  28185. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28186. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  28187. __decorate([
  28188. BABYLON.serialize("useSpecularOverAlpha")
  28189. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  28190. __decorate([
  28191. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28192. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  28193. __decorate([
  28194. BABYLON.serialize("useReflectionOverAlpha")
  28195. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  28196. __decorate([
  28197. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28198. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  28199. __decorate([
  28200. BABYLON.serialize("disableLighting")
  28201. ], StandardMaterial.prototype, "_disableLighting", void 0);
  28202. __decorate([
  28203. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  28204. ], StandardMaterial.prototype, "disableLighting", void 0);
  28205. __decorate([
  28206. BABYLON.serialize("useParallax")
  28207. ], StandardMaterial.prototype, "_useParallax", void 0);
  28208. __decorate([
  28209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28210. ], StandardMaterial.prototype, "useParallax", void 0);
  28211. __decorate([
  28212. BABYLON.serialize("useParallaxOcclusion")
  28213. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  28214. __decorate([
  28215. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28216. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  28217. __decorate([
  28218. BABYLON.serialize()
  28219. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  28220. __decorate([
  28221. BABYLON.serialize("roughness")
  28222. ], StandardMaterial.prototype, "_roughness", void 0);
  28223. __decorate([
  28224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28225. ], StandardMaterial.prototype, "roughness", void 0);
  28226. __decorate([
  28227. BABYLON.serialize()
  28228. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  28229. __decorate([
  28230. BABYLON.serialize()
  28231. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  28232. __decorate([
  28233. BABYLON.serialize("useLightmapAsShadowmap")
  28234. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  28235. __decorate([
  28236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28237. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  28238. __decorate([
  28239. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  28240. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  28241. __decorate([
  28242. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28243. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  28244. __decorate([
  28245. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  28246. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  28247. __decorate([
  28248. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28249. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  28250. __decorate([
  28251. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  28252. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  28253. __decorate([
  28254. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28255. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  28256. __decorate([
  28257. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  28258. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  28259. __decorate([
  28260. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28261. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  28262. __decorate([
  28263. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  28264. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  28265. __decorate([
  28266. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28267. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  28268. __decorate([
  28269. BABYLON.serialize("useReflectionFresnelFromSpecular")
  28270. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  28271. __decorate([
  28272. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28273. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  28274. __decorate([
  28275. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  28276. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  28277. __decorate([
  28278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28279. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  28280. __decorate([
  28281. BABYLON.serialize("maxSimultaneousLights")
  28282. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  28283. __decorate([
  28284. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  28285. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  28286. __decorate([
  28287. BABYLON.serialize("invertNormalMapX")
  28288. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  28289. __decorate([
  28290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28291. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  28292. __decorate([
  28293. BABYLON.serialize("invertNormalMapY")
  28294. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  28295. __decorate([
  28296. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28297. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  28298. __decorate([
  28299. BABYLON.serialize("twoSidedLighting")
  28300. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  28301. __decorate([
  28302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28303. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  28304. __decorate([
  28305. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  28306. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  28307. __decorate([
  28308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28309. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  28310. __decorate([
  28311. BABYLON.serializeAsColorCurves("cameraColorCurves")
  28312. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  28313. __decorate([
  28314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28315. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  28316. __decorate([
  28317. BABYLON.serialize()
  28318. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  28319. BABYLON.StandardMaterial = StandardMaterial;
  28320. })(BABYLON || (BABYLON = {}));
  28321. //# sourceMappingURL=babylon.standardMaterial.js.map
  28322. var BABYLON;
  28323. (function (BABYLON) {
  28324. var PBRMaterialDefines = (function (_super) {
  28325. __extends(PBRMaterialDefines, _super);
  28326. function PBRMaterialDefines() {
  28327. var _this = _super.call(this) || this;
  28328. _this.ALBEDO = false;
  28329. _this.AMBIENT = false;
  28330. _this.AMBIENTINGRAYSCALE = false;
  28331. _this.OPACITY = false;
  28332. _this.OPACITYRGB = false;
  28333. _this.REFLECTION = false;
  28334. _this.EMISSIVE = false;
  28335. _this.REFLECTIVITY = false;
  28336. _this.BUMP = false;
  28337. _this.PARALLAX = false;
  28338. _this.PARALLAXOCCLUSION = false;
  28339. _this.SPECULAROVERALPHA = false;
  28340. _this.CLIPPLANE = false;
  28341. _this.ALPHATEST = false;
  28342. _this.ALPHAFROMALBEDO = false;
  28343. _this.POINTSIZE = false;
  28344. _this.FOG = false;
  28345. _this.SPECULARTERM = false;
  28346. _this.OPACITYFRESNEL = false;
  28347. _this.EMISSIVEFRESNEL = false;
  28348. _this.FRESNEL = false;
  28349. _this.NORMAL = false;
  28350. _this.TANGENT = false;
  28351. _this.UV1 = false;
  28352. _this.UV2 = false;
  28353. _this.VERTEXCOLOR = false;
  28354. _this.VERTEXALPHA = false;
  28355. _this.NUM_BONE_INFLUENCERS = 0;
  28356. _this.BonesPerMesh = 0;
  28357. _this.INSTANCES = false;
  28358. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  28359. _this.MICROSURFACEAUTOMATIC = false;
  28360. _this.EMISSIVEASILLUMINATION = false;
  28361. _this.LINKEMISSIVEWITHALBEDO = false;
  28362. _this.LIGHTMAP = false;
  28363. _this.USELIGHTMAPASSHADOWMAP = false;
  28364. _this.REFLECTIONMAP_3D = false;
  28365. _this.REFLECTIONMAP_SPHERICAL = false;
  28366. _this.REFLECTIONMAP_PLANAR = false;
  28367. _this.REFLECTIONMAP_CUBIC = false;
  28368. _this.REFLECTIONMAP_PROJECTION = false;
  28369. _this.REFLECTIONMAP_SKYBOX = false;
  28370. _this.REFLECTIONMAP_EXPLICIT = false;
  28371. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  28372. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  28373. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  28374. _this.INVERTCUBICMAP = false;
  28375. _this.LOGARITHMICDEPTH = false;
  28376. _this.CAMERATONEMAP = false;
  28377. _this.CAMERACONTRAST = false;
  28378. _this.CAMERACOLORGRADING = false;
  28379. _this.CAMERACOLORCURVES = false;
  28380. _this.OVERLOADEDVALUES = false;
  28381. _this.OVERLOADEDSHADOWVALUES = false;
  28382. _this.USESPHERICALFROMREFLECTIONMAP = false;
  28383. _this.REFRACTION = false;
  28384. _this.REFRACTIONMAP_3D = false;
  28385. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  28386. _this.REFRACTIONMAPINLINEARSPACE = false;
  28387. _this.LODBASEDMICROSFURACE = false;
  28388. _this.USEPHYSICALLIGHTFALLOFF = false;
  28389. _this.RADIANCEOVERALPHA = false;
  28390. _this.USEPMREMREFLECTION = false;
  28391. _this.USEPMREMREFRACTION = false;
  28392. _this.INVERTNORMALMAPX = false;
  28393. _this.INVERTNORMALMAPY = false;
  28394. _this.TWOSIDEDLIGHTING = false;
  28395. _this.SHADOWFULLFLOAT = false;
  28396. _this.METALLICWORKFLOW = false;
  28397. _this.METALLICMAP = false;
  28398. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  28399. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  28400. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  28401. _this.AOSTOREINMETALMAPRED = false;
  28402. _this.MICROSURFACEMAP = false;
  28403. _this.MORPHTARGETS = false;
  28404. _this.MORPHTARGETS_NORMAL = false;
  28405. _this.MORPHTARGETS_TANGENT = false;
  28406. _this.NUM_MORPH_INFLUENCERS = 0;
  28407. _this.rebuild();
  28408. return _this;
  28409. }
  28410. return PBRMaterialDefines;
  28411. }(BABYLON.MaterialDefines));
  28412. /**
  28413. * The Physically based material of BJS.
  28414. *
  28415. * This offers the main features of a standard PBR material.
  28416. * For more information, please refer to the documentation :
  28417. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  28418. */
  28419. var PBRMaterial = (function (_super) {
  28420. __extends(PBRMaterial, _super);
  28421. /**
  28422. * Instantiates a new PBRMaterial instance.
  28423. *
  28424. * @param name The material name
  28425. * @param scene The scene the material will be use in.
  28426. */
  28427. function PBRMaterial(name, scene) {
  28428. var _this = _super.call(this, name, scene) || this;
  28429. /**
  28430. * Intensity of the direct lights e.g. the four lights available in your scene.
  28431. * This impacts both the direct diffuse and specular highlights.
  28432. */
  28433. _this.directIntensity = 1.0;
  28434. /**
  28435. * Intensity of the emissive part of the material.
  28436. * This helps controlling the emissive effect without modifying the emissive color.
  28437. */
  28438. _this.emissiveIntensity = 1.0;
  28439. /**
  28440. * Intensity of the environment e.g. how much the environment will light the object
  28441. * either through harmonics for rough material or through the refelction for shiny ones.
  28442. */
  28443. _this.environmentIntensity = 1.0;
  28444. /**
  28445. * This is a special control allowing the reduction of the specular highlights coming from the
  28446. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  28447. */
  28448. _this.specularIntensity = 1.0;
  28449. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  28450. /**
  28451. * Debug Control allowing disabling the bump map on this material.
  28452. */
  28453. _this.disableBumpMap = false;
  28454. /**
  28455. * Debug Control helping enforcing or dropping the darkness of shadows.
  28456. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  28457. */
  28458. _this.overloadedShadowIntensity = 1.0;
  28459. /**
  28460. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  28461. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  28462. */
  28463. _this.overloadedShadeIntensity = 1.0;
  28464. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  28465. /**
  28466. * The camera exposure used on this material.
  28467. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  28468. * This corresponds to a photographic exposure.
  28469. */
  28470. _this.cameraExposure = 1.0;
  28471. /**
  28472. * The camera contrast used on this material.
  28473. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  28474. */
  28475. _this.cameraContrast = 1.0;
  28476. /**
  28477. * Color Grading 2D Lookup Texture.
  28478. * This allows special effects like sepia, black and white to sixties rendering style.
  28479. */
  28480. _this.cameraColorGradingTexture = null;
  28481. /**
  28482. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  28483. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  28484. * 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;
  28485. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  28486. */
  28487. _this.cameraColorCurves = null;
  28488. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  28489. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  28490. /**
  28491. * Debug Control allowing to overload the ambient color.
  28492. * This as to be use with the overloadedAmbientIntensity parameter.
  28493. */
  28494. _this.overloadedAmbient = BABYLON.Color3.White();
  28495. /**
  28496. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  28497. */
  28498. _this.overloadedAmbientIntensity = 0.0;
  28499. /**
  28500. * Debug Control allowing to overload the albedo color.
  28501. * This as to be use with the overloadedAlbedoIntensity parameter.
  28502. */
  28503. _this.overloadedAlbedo = BABYLON.Color3.White();
  28504. /**
  28505. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  28506. */
  28507. _this.overloadedAlbedoIntensity = 0.0;
  28508. /**
  28509. * Debug Control allowing to overload the reflectivity color.
  28510. * This as to be use with the overloadedReflectivityIntensity parameter.
  28511. */
  28512. _this.overloadedReflectivity = new BABYLON.Color3(0.0, 0.0, 0.0);
  28513. /**
  28514. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  28515. */
  28516. _this.overloadedReflectivityIntensity = 0.0;
  28517. /**
  28518. * Debug Control allowing to overload the emissive color.
  28519. * This as to be use with the overloadedEmissiveIntensity parameter.
  28520. */
  28521. _this.overloadedEmissive = BABYLON.Color3.White();
  28522. /**
  28523. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  28524. */
  28525. _this.overloadedEmissiveIntensity = 0.0;
  28526. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  28527. /**
  28528. * Debug Control allowing to overload the reflection color.
  28529. * This as to be use with the overloadedReflectionIntensity parameter.
  28530. */
  28531. _this.overloadedReflection = BABYLON.Color3.White();
  28532. /**
  28533. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  28534. */
  28535. _this.overloadedReflectionIntensity = 0.0;
  28536. /**
  28537. * Debug Control allowing to overload the microsurface.
  28538. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  28539. */
  28540. _this.overloadedMicroSurface = 0.0;
  28541. /**
  28542. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  28543. */
  28544. _this.overloadedMicroSurfaceIntensity = 0.0;
  28545. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  28546. /**
  28547. * AKA Occlusion Texture Intensity in other nomenclature.
  28548. */
  28549. _this.ambientTextureStrength = 1.0;
  28550. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  28551. /**
  28552. * AKA Diffuse Color in other nomenclature.
  28553. */
  28554. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  28555. /**
  28556. * AKA Specular Color in other nomenclature.
  28557. */
  28558. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  28559. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  28560. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  28561. /**
  28562. * AKA Glossiness in other nomenclature.
  28563. */
  28564. _this.microSurface = 0.9;
  28565. /**
  28566. * source material index of refraction (IOR)' / 'destination material IOR.
  28567. */
  28568. _this.indexOfRefraction = 0.66;
  28569. /**
  28570. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  28571. */
  28572. _this.invertRefractionY = false;
  28573. /**
  28574. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  28575. * Materials half opaque for instance using refraction could benefit from this control.
  28576. */
  28577. _this.linkRefractionWithTransparency = false;
  28578. /**
  28579. * The emissive and albedo are linked to never be more than one (Energy conservation).
  28580. */
  28581. _this.linkEmissiveWithAlbedo = false;
  28582. _this.useLightmapAsShadowmap = false;
  28583. /**
  28584. * In this mode, the emissive informtaion will always be added to the lighting once.
  28585. * A light for instance can be thought as emissive.
  28586. */
  28587. _this.useEmissiveAsIllumination = false;
  28588. /**
  28589. * Secifies that the alpha is coming form the albedo channel alpha channel.
  28590. */
  28591. _this.useAlphaFromAlbedoTexture = false;
  28592. /**
  28593. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  28594. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  28595. */
  28596. _this.useSpecularOverAlpha = true;
  28597. /**
  28598. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  28599. */
  28600. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  28601. /**
  28602. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  28603. */
  28604. _this.useRoughnessFromMetallicTextureAlpha = true;
  28605. /**
  28606. * Specifies if the metallic texture contains the roughness information in its green channel.
  28607. */
  28608. _this.useRoughnessFromMetallicTextureGreen = false;
  28609. /**
  28610. * Specifies if the metallic texture contains the metallness information in its blue channel.
  28611. */
  28612. _this.useMetallnessFromMetallicTextureBlue = false;
  28613. /**
  28614. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  28615. */
  28616. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  28617. /**
  28618. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  28619. */
  28620. _this.useAmbientInGrayScale = false;
  28621. /**
  28622. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  28623. * The material will try to infer what glossiness each pixel should be.
  28624. */
  28625. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  28626. /**
  28627. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  28628. * the creation of the material.
  28629. */
  28630. _this.useScalarInLinearSpace = false;
  28631. /**
  28632. * BJS is using an harcoded light falloff based on a manually sets up range.
  28633. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  28634. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  28635. */
  28636. _this.usePhysicalLightFalloff = true;
  28637. /**
  28638. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  28639. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  28640. */
  28641. _this.useRadianceOverAlpha = true;
  28642. /**
  28643. * Allows using the bump map in parallax mode.
  28644. */
  28645. _this.useParallax = false;
  28646. /**
  28647. * Allows using the bump map in parallax occlusion mode.
  28648. */
  28649. _this.useParallaxOcclusion = false;
  28650. /**
  28651. * Controls the scale bias of the parallax mode.
  28652. */
  28653. _this.parallaxScaleBias = 0.05;
  28654. /**
  28655. * If sets to true, disables all the lights affecting the material.
  28656. */
  28657. _this.disableLighting = false;
  28658. /**
  28659. * Number of Simultaneous lights allowed on the material.
  28660. */
  28661. _this.maxSimultaneousLights = 4;
  28662. /**
  28663. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  28664. */
  28665. _this.invertNormalMapX = false;
  28666. /**
  28667. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  28668. */
  28669. _this.invertNormalMapY = false;
  28670. /**
  28671. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  28672. */
  28673. _this.twoSidedLighting = false;
  28674. _this._renderTargets = new BABYLON.SmartArray(16);
  28675. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  28676. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  28677. _this._tempColor = new BABYLON.Color3();
  28678. _this._defines = new PBRMaterialDefines();
  28679. _this._cachedDefines = new PBRMaterialDefines();
  28680. _this._myScene = null;
  28681. _this._myShadowGenerator = null;
  28682. _this._cachedDefines.BonesPerMesh = -1;
  28683. _this.getRenderTargetTextures = function () {
  28684. _this._renderTargets.reset();
  28685. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  28686. _this._renderTargets.push(_this.reflectionTexture);
  28687. }
  28688. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  28689. _this._renderTargets.push(_this.refractionTexture);
  28690. }
  28691. return _this._renderTargets;
  28692. };
  28693. return _this;
  28694. }
  28695. PBRMaterial.prototype.getClassName = function () {
  28696. return "PBRMaterial";
  28697. };
  28698. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  28699. get: function () {
  28700. return this._useLogarithmicDepth;
  28701. },
  28702. set: function (value) {
  28703. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  28704. },
  28705. enumerable: true,
  28706. configurable: true
  28707. });
  28708. PBRMaterial.prototype.needAlphaBlending = function () {
  28709. if (this.linkRefractionWithTransparency) {
  28710. return false;
  28711. }
  28712. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  28713. };
  28714. PBRMaterial.prototype.needAlphaTesting = function () {
  28715. if (this.linkRefractionWithTransparency) {
  28716. return false;
  28717. }
  28718. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  28719. };
  28720. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  28721. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  28722. };
  28723. PBRMaterial.prototype.getAlphaTestTexture = function () {
  28724. return this.albedoTexture;
  28725. };
  28726. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  28727. if (!mesh) {
  28728. return true;
  28729. }
  28730. if (this._defines.INSTANCES !== useInstances) {
  28731. return false;
  28732. }
  28733. return false;
  28734. };
  28735. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  28736. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  28737. };
  28738. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  28739. if (!useScalarInLinear) {
  28740. color.toLinearSpaceToRef(ref);
  28741. }
  28742. else {
  28743. ref.r = color.r;
  28744. ref.g = color.g;
  28745. ref.b = color.b;
  28746. }
  28747. };
  28748. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  28749. var lightIndex = 0;
  28750. var depthValuesAlreadySet = false;
  28751. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  28752. var light = _a[_i];
  28753. var useUbo = light._uniformBuffer.useUbo;
  28754. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  28755. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  28756. // GAMMA CORRECTION.
  28757. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  28758. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  28759. light._uniformBuffer.updateColor4(useUbo ? "vLightDiffuse" : "vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  28760. if (defines["SPECULARTERM"]) {
  28761. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  28762. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  28763. light._uniformBuffer.updateColor3(useUbo ? "vLightSpecular" : "vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  28764. }
  28765. // Shadows
  28766. if (scene.shadowsEnabled) {
  28767. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  28768. }
  28769. light._uniformBuffer.update();
  28770. lightIndex++;
  28771. if (lightIndex === maxSimultaneousLights)
  28772. break;
  28773. }
  28774. };
  28775. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  28776. if (this.isFrozen) {
  28777. if (this._wasPreviouslyReady) {
  28778. return true;
  28779. }
  28780. }
  28781. var scene = this.getScene();
  28782. var engine = scene.getEngine();
  28783. var needUVs = false;
  28784. this._defines.reset();
  28785. if (scene.lightsEnabled && !this.disableLighting) {
  28786. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, true, this.maxSimultaneousLights);
  28787. }
  28788. if (!this.checkReadyOnEveryCall) {
  28789. if (this._renderId === scene.getRenderId()) {
  28790. if (this._checkCache(scene, mesh, useInstances)) {
  28791. return true;
  28792. }
  28793. }
  28794. }
  28795. if (scene.texturesEnabled) {
  28796. if (scene.getEngine().getCaps().textureLOD) {
  28797. this._defines.LODBASEDMICROSFURACE = true;
  28798. }
  28799. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  28800. if (!this.albedoTexture.isReady()) {
  28801. return false;
  28802. }
  28803. needUVs = true;
  28804. this._defines.ALBEDO = true;
  28805. }
  28806. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  28807. if (!this.ambientTexture.isReady()) {
  28808. return false;
  28809. }
  28810. needUVs = true;
  28811. this._defines.AMBIENT = true;
  28812. this._defines.AMBIENTINGRAYSCALE = this.useAmbientInGrayScale;
  28813. }
  28814. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  28815. if (!this.opacityTexture.isReady()) {
  28816. return false;
  28817. }
  28818. needUVs = true;
  28819. this._defines.OPACITY = true;
  28820. if (this.opacityTexture.getAlphaFromRGB) {
  28821. this._defines.OPACITYRGB = true;
  28822. }
  28823. }
  28824. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  28825. if (!this.reflectionTexture.isReady()) {
  28826. return false;
  28827. }
  28828. this._defines.REFLECTION = true;
  28829. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  28830. this._defines.INVERTCUBICMAP = true;
  28831. }
  28832. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  28833. switch (this.reflectionTexture.coordinatesMode) {
  28834. case BABYLON.Texture.CUBIC_MODE:
  28835. case BABYLON.Texture.INVCUBIC_MODE:
  28836. this._defines.REFLECTIONMAP_CUBIC = true;
  28837. break;
  28838. case BABYLON.Texture.EXPLICIT_MODE:
  28839. this._defines.REFLECTIONMAP_EXPLICIT = true;
  28840. break;
  28841. case BABYLON.Texture.PLANAR_MODE:
  28842. this._defines.REFLECTIONMAP_PLANAR = true;
  28843. break;
  28844. case BABYLON.Texture.PROJECTION_MODE:
  28845. this._defines.REFLECTIONMAP_PROJECTION = true;
  28846. break;
  28847. case BABYLON.Texture.SKYBOX_MODE:
  28848. this._defines.REFLECTIONMAP_SKYBOX = true;
  28849. break;
  28850. case BABYLON.Texture.SPHERICAL_MODE:
  28851. this._defines.REFLECTIONMAP_SPHERICAL = true;
  28852. break;
  28853. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  28854. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  28855. break;
  28856. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  28857. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  28858. break;
  28859. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  28860. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  28861. break;
  28862. }
  28863. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  28864. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  28865. if (this.reflectionTexture.isPMREM) {
  28866. this._defines.USEPMREMREFLECTION = true;
  28867. }
  28868. }
  28869. }
  28870. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  28871. if (!this.lightmapTexture.isReady()) {
  28872. return false;
  28873. }
  28874. needUVs = true;
  28875. this._defines.LIGHTMAP = true;
  28876. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  28877. }
  28878. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  28879. if (!this.emissiveTexture.isReady()) {
  28880. return false;
  28881. }
  28882. needUVs = true;
  28883. this._defines.EMISSIVE = true;
  28884. }
  28885. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  28886. if (this.metallicTexture) {
  28887. if (!this.metallicTexture.isReady()) {
  28888. return false;
  28889. }
  28890. needUVs = true;
  28891. this._defines.METALLICWORKFLOW = true;
  28892. this._defines.METALLICMAP = true;
  28893. this._defines.ROUGHNESSSTOREINMETALMAPALPHA = this.useRoughnessFromMetallicTextureAlpha;
  28894. this._defines.ROUGHNESSSTOREINMETALMAPGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  28895. this._defines.METALLNESSSTOREINMETALMAPBLUE = this.useMetallnessFromMetallicTextureBlue;
  28896. this._defines.AOSTOREINMETALMAPRED = this.useAmbientOcclusionFromMetallicTextureRed;
  28897. }
  28898. else if (this.reflectivityTexture) {
  28899. if (!this.reflectivityTexture.isReady()) {
  28900. return false;
  28901. }
  28902. needUVs = true;
  28903. this._defines.REFLECTIVITY = true;
  28904. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  28905. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  28906. }
  28907. if (this.microSurfaceTexture) {
  28908. if (!this.microSurfaceTexture.isReady()) {
  28909. return false;
  28910. }
  28911. needUVs = true;
  28912. this._defines.MICROSURFACEMAP = true;
  28913. }
  28914. }
  28915. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  28916. if (!this.bumpTexture.isReady()) {
  28917. return false;
  28918. }
  28919. needUVs = true;
  28920. this._defines.BUMP = true;
  28921. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  28922. this._defines.PARALLAX = true;
  28923. if (this.useParallaxOcclusion) {
  28924. this._defines.PARALLAXOCCLUSION = true;
  28925. }
  28926. }
  28927. if (this.invertNormalMapX) {
  28928. this._defines.INVERTNORMALMAPX = true;
  28929. }
  28930. if (this.invertNormalMapY) {
  28931. this._defines.INVERTNORMALMAPY = true;
  28932. }
  28933. if (scene._mirroredCameraPosition) {
  28934. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  28935. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  28936. }
  28937. }
  28938. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  28939. if (!this.refractionTexture.isReady()) {
  28940. return false;
  28941. }
  28942. needUVs = true;
  28943. this._defines.REFRACTION = true;
  28944. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  28945. if (this.linkRefractionWithTransparency) {
  28946. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  28947. }
  28948. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  28949. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  28950. if (this.refractionTexture.isPMREM) {
  28951. this._defines.USEPMREMREFRACTION = true;
  28952. }
  28953. }
  28954. }
  28955. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  28956. if (!this.cameraColorGradingTexture.isReady()) {
  28957. return false;
  28958. }
  28959. this._defines.CAMERACOLORGRADING = true;
  28960. }
  28961. if (!this.backFaceCulling && this.twoSidedLighting) {
  28962. this._defines.TWOSIDEDLIGHTING = true;
  28963. }
  28964. }
  28965. // Effect
  28966. if (scene.clipPlane) {
  28967. this._defines.CLIPPLANE = true;
  28968. }
  28969. if (engine.getAlphaTesting()) {
  28970. this._defines.ALPHATEST = true;
  28971. }
  28972. if (this._shouldUseAlphaFromAlbedoTexture()) {
  28973. this._defines.ALPHAFROMALBEDO = true;
  28974. }
  28975. if (this.useEmissiveAsIllumination) {
  28976. this._defines.EMISSIVEASILLUMINATION = true;
  28977. }
  28978. if (this.linkEmissiveWithAlbedo) {
  28979. this._defines.LINKEMISSIVEWITHALBEDO = true;
  28980. }
  28981. if (this.useLogarithmicDepth) {
  28982. this._defines.LOGARITHMICDEPTH = true;
  28983. }
  28984. if (this.cameraContrast != 1) {
  28985. this._defines.CAMERACONTRAST = true;
  28986. }
  28987. if (this.cameraExposure != 1) {
  28988. this._defines.CAMERATONEMAP = true;
  28989. }
  28990. if (this.cameraColorCurves) {
  28991. this._defines.CAMERACOLORCURVES = true;
  28992. }
  28993. if (this.overloadedShadeIntensity != 1 ||
  28994. this.overloadedShadowIntensity != 1) {
  28995. this._defines.OVERLOADEDSHADOWVALUES = true;
  28996. }
  28997. if (this.overloadedMicroSurfaceIntensity > 0 ||
  28998. this.overloadedEmissiveIntensity > 0 ||
  28999. this.overloadedReflectivityIntensity > 0 ||
  29000. this.overloadedAlbedoIntensity > 0 ||
  29001. this.overloadedAmbientIntensity > 0 ||
  29002. this.overloadedReflectionIntensity > 0) {
  29003. this._defines.OVERLOADEDVALUES = true;
  29004. }
  29005. // Point size
  29006. if (this.pointsCloud || scene.forcePointsCloud) {
  29007. this._defines.POINTSIZE = true;
  29008. }
  29009. // Fog
  29010. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  29011. this._defines.FOG = true;
  29012. }
  29013. if (BABYLON.StandardMaterial.FresnelEnabled) {
  29014. // Fresnel
  29015. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  29016. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29017. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29018. this._defines.OPACITYFRESNEL = true;
  29019. }
  29020. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29021. this._defines.EMISSIVEFRESNEL = true;
  29022. }
  29023. this._defines.FRESNEL = true;
  29024. }
  29025. }
  29026. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  29027. this._defines.SPECULAROVERALPHA = true;
  29028. }
  29029. if (this.usePhysicalLightFalloff) {
  29030. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  29031. }
  29032. if (this.useRadianceOverAlpha) {
  29033. this._defines.RADIANCEOVERALPHA = true;
  29034. }
  29035. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  29036. this._defines.METALLICWORKFLOW = true;
  29037. }
  29038. // Attribs
  29039. if (mesh) {
  29040. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29041. mesh.createNormals(true);
  29042. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  29043. }
  29044. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29045. this._defines.NORMAL = true;
  29046. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29047. this._defines.TANGENT = true;
  29048. }
  29049. }
  29050. if (needUVs) {
  29051. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29052. this._defines.UV1 = true;
  29053. }
  29054. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29055. this._defines.UV2 = true;
  29056. }
  29057. }
  29058. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29059. this._defines.VERTEXCOLOR = true;
  29060. if (mesh.hasVertexAlpha) {
  29061. this._defines.VERTEXALPHA = true;
  29062. }
  29063. }
  29064. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  29065. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  29066. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  29067. }
  29068. // Instances
  29069. if (useInstances) {
  29070. this._defines.INSTANCES = true;
  29071. }
  29072. if (mesh.morphTargetManager) {
  29073. var manager = mesh.morphTargetManager;
  29074. this._defines.MORPHTARGETS_TANGENT = manager.supportsTangents && this._defines.TANGENT;
  29075. this._defines.MORPHTARGETS_NORMAL = manager.supportsNormals && this._defines.NORMAL;
  29076. this._defines.MORPHTARGETS = (manager.numInfluencers > 0);
  29077. this._defines.NUM_MORPH_INFLUENCERS = manager.numInfluencers;
  29078. }
  29079. }
  29080. // Get correct effect
  29081. if (!this._defines.isEqual(this._cachedDefines)) {
  29082. this._defines.cloneTo(this._cachedDefines);
  29083. scene.resetCachedMaterial();
  29084. // Fallbacks
  29085. var fallbacks = new BABYLON.EffectFallbacks();
  29086. if (this._defines.REFLECTION) {
  29087. fallbacks.addFallback(0, "REFLECTION");
  29088. }
  29089. if (this._defines.REFRACTION) {
  29090. fallbacks.addFallback(0, "REFRACTION");
  29091. }
  29092. if (this._defines.REFLECTIVITY) {
  29093. fallbacks.addFallback(0, "REFLECTIVITY");
  29094. }
  29095. if (this._defines.BUMP) {
  29096. fallbacks.addFallback(0, "BUMP");
  29097. }
  29098. if (this._defines.PARALLAX) {
  29099. fallbacks.addFallback(1, "PARALLAX");
  29100. }
  29101. if (this._defines.PARALLAXOCCLUSION) {
  29102. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  29103. }
  29104. if (this._defines.SPECULAROVERALPHA) {
  29105. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  29106. }
  29107. if (this._defines.FOG) {
  29108. fallbacks.addFallback(1, "FOG");
  29109. }
  29110. if (this._defines.POINTSIZE) {
  29111. fallbacks.addFallback(0, "POINTSIZE");
  29112. }
  29113. if (this._defines.LOGARITHMICDEPTH) {
  29114. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  29115. }
  29116. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  29117. if (this._defines.SPECULARTERM) {
  29118. fallbacks.addFallback(0, "SPECULARTERM");
  29119. }
  29120. if (this._defines.OPACITYFRESNEL) {
  29121. fallbacks.addFallback(1, "OPACITYFRESNEL");
  29122. }
  29123. if (this._defines.EMISSIVEFRESNEL) {
  29124. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  29125. }
  29126. if (this._defines.FRESNEL) {
  29127. fallbacks.addFallback(3, "FRESNEL");
  29128. }
  29129. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  29130. fallbacks.addCPUSkinningFallback(0, mesh);
  29131. }
  29132. //Attributes
  29133. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29134. if (this._defines.NORMAL) {
  29135. attribs.push(BABYLON.VertexBuffer.NormalKind);
  29136. }
  29137. if (this._defines.TANGENT) {
  29138. attribs.push(BABYLON.VertexBuffer.TangentKind);
  29139. }
  29140. if (this._defines.UV1) {
  29141. attribs.push(BABYLON.VertexBuffer.UVKind);
  29142. }
  29143. if (this._defines.UV2) {
  29144. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29145. }
  29146. if (this._defines.VERTEXCOLOR) {
  29147. attribs.push(BABYLON.VertexBuffer.ColorKind);
  29148. }
  29149. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  29150. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  29151. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, this._defines);
  29152. // Legacy browser patch
  29153. var join = this._defines.toString();
  29154. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  29155. "vFogInfos", "vFogColor", "pointSize",
  29156. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  29157. "mBones",
  29158. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  29159. "depthValues",
  29160. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  29161. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  29162. "logarithmicDepthConstant",
  29163. "vSphericalX", "vSphericalY", "vSphericalZ",
  29164. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  29165. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  29166. "vMicrosurfaceTextureLods",
  29167. "vCameraInfos"
  29168. ];
  29169. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  29170. var uniformBuffers = ["Material", "Scene"];
  29171. if (this._defines.CAMERACOLORCURVES) {
  29172. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  29173. }
  29174. if (this._defines.CAMERACOLORGRADING) {
  29175. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  29176. }
  29177. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  29178. uniformsNames: uniforms,
  29179. uniformBuffersNames: uniformBuffers,
  29180. samplers: samplers,
  29181. defines: this._defines,
  29182. maxSimultaneousLights: this.maxSimultaneousLights
  29183. });
  29184. var onCompiled = function (effect) {
  29185. if (this.onCompiled) {
  29186. this.onCompiled(effect);
  29187. }
  29188. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  29189. }.bind(this);
  29190. this._effect = scene.getEngine().createEffect("pbr", {
  29191. attributes: attribs,
  29192. uniformsNames: uniforms,
  29193. uniformBuffersNames: uniformBuffers,
  29194. samplers: samplers,
  29195. defines: join,
  29196. fallbacks: fallbacks,
  29197. onCompiled: onCompiled,
  29198. onError: this.onError,
  29199. indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: this._defines.NUM_MORPH_INFLUENCERS }
  29200. }, engine);
  29201. this.buildUniformLayout();
  29202. }
  29203. if (!this._effect.isReady()) {
  29204. return false;
  29205. }
  29206. this._renderId = scene.getRenderId();
  29207. this._wasPreviouslyReady = true;
  29208. return true;
  29209. };
  29210. PBRMaterial.prototype.buildUniformLayout = function () {
  29211. // Order is important !
  29212. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  29213. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  29214. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  29215. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  29216. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  29217. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  29218. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  29219. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  29220. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  29221. this._uniformBuffer.addUniform("vBumpInfos", 3);
  29222. this._uniformBuffer.addUniform("albedoMatrix", 16);
  29223. this._uniformBuffer.addUniform("ambientMatrix", 16);
  29224. this._uniformBuffer.addUniform("opacityMatrix", 16);
  29225. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  29226. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  29227. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  29228. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  29229. this._uniformBuffer.addUniform("bumpMatrix", 16);
  29230. this._uniformBuffer.addUniform("refractionMatrix", 16);
  29231. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  29232. this._uniformBuffer.addUniform("vReflectionColor", 3);
  29233. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  29234. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  29235. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  29236. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  29237. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  29238. this._uniformBuffer.addUniform("opacityParts", 4);
  29239. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  29240. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  29241. this._uniformBuffer.addUniform("vOverloadedIntensity", 4);
  29242. this._uniformBuffer.addUniform("vOverloadedAmbient", 3);
  29243. this._uniformBuffer.addUniform("vOverloadedAlbedo", 3);
  29244. this._uniformBuffer.addUniform("vOverloadedReflectivity", 3);
  29245. this._uniformBuffer.addUniform("vOverloadedEmissive", 3);
  29246. this._uniformBuffer.addUniform("vOverloadedReflection", 3);
  29247. this._uniformBuffer.addUniform("vOverloadedMicroSurface", 3);
  29248. this._uniformBuffer.addUniform("vOverloadedShadowIntensity", 4);
  29249. this._uniformBuffer.addUniform("pointSize", 1);
  29250. this._uniformBuffer.create();
  29251. };
  29252. PBRMaterial.prototype.unbind = function () {
  29253. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  29254. this._uniformBuffer.setTexture("reflection2DSampler", null);
  29255. }
  29256. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  29257. this._uniformBuffer.setTexture("refraction2DSampler", null);
  29258. }
  29259. _super.prototype.unbind.call(this);
  29260. };
  29261. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  29262. this._effect.setMatrix("world", world);
  29263. };
  29264. PBRMaterial.prototype.bind = function (world, mesh) {
  29265. this._myScene = this.getScene();
  29266. var effect = this._effect;
  29267. // Matrices
  29268. this.bindOnlyWorldMatrix(world);
  29269. // Bones
  29270. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  29271. if (this._myScene.getCachedMaterial() !== this) {
  29272. this._uniformBuffer.bindToEffect(effect, "Material");
  29273. this.bindViewProjection(effect);
  29274. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  29275. // Fresnel
  29276. if (BABYLON.StandardMaterial.FresnelEnabled) {
  29277. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29278. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  29279. }
  29280. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29281. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  29282. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  29283. }
  29284. }
  29285. // Texture uniforms
  29286. if (this._myScene.texturesEnabled) {
  29287. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29288. this._uniformBuffer.updateFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  29289. this._uniformBuffer.updateMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  29290. }
  29291. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  29292. this._uniformBuffer.updateFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  29293. this._uniformBuffer.updateMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  29294. }
  29295. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  29296. this._uniformBuffer.updateFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  29297. this._uniformBuffer.updateMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  29298. }
  29299. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  29300. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  29301. this._uniformBuffer.updateMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  29302. this._uniformBuffer.updateFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  29303. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  29304. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  29305. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  29306. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  29307. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  29308. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  29309. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  29310. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  29311. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  29312. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  29313. }
  29314. }
  29315. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  29316. this._uniformBuffer.updateFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  29317. this._uniformBuffer.updateMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  29318. }
  29319. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  29320. this._uniformBuffer.updateFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  29321. this._uniformBuffer.updateMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  29322. }
  29323. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  29324. if (this.metallicTexture) {
  29325. this._uniformBuffer.updateFloat3("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level, this.ambientTextureStrength);
  29326. this._uniformBuffer.updateMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  29327. }
  29328. else if (this.reflectivityTexture) {
  29329. this._uniformBuffer.updateFloat3("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level, 1.0);
  29330. this._uniformBuffer.updateMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  29331. }
  29332. if (this.microSurfaceTexture) {
  29333. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this.microSurfaceTexture.coordinatesIndex, this.microSurfaceTexture.level);
  29334. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this.microSurfaceTexture.getTextureMatrix());
  29335. }
  29336. }
  29337. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  29338. this._uniformBuffer.updateFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  29339. this._uniformBuffer.updateMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  29340. }
  29341. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  29342. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  29343. var depth = 1.0;
  29344. if (!this.refractionTexture.isCube) {
  29345. this._uniformBuffer.updateMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  29346. if (this.refractionTexture.depth) {
  29347. depth = this.refractionTexture.depth;
  29348. }
  29349. }
  29350. this._uniformBuffer.updateFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  29351. }
  29352. if ((this.reflectionTexture || this.refractionTexture)) {
  29353. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  29354. }
  29355. }
  29356. // Point size
  29357. if (this.pointsCloud) {
  29358. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  29359. }
  29360. // Colors
  29361. if (this._defines.METALLICWORKFLOW) {
  29362. PBRMaterial._scaledReflectivity.r = (this.metallic === undefined || this.metallic === null) ? 1 : this.metallic;
  29363. PBRMaterial._scaledReflectivity.g = (this.roughness === undefined || this.roughness === null) ? 1 : this.roughness;
  29364. this._uniformBuffer.updateColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  29365. }
  29366. else {
  29367. // GAMMA CORRECTION.
  29368. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  29369. this._uniformBuffer.updateColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  29370. }
  29371. // GAMMA CORRECTION.
  29372. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  29373. this._uniformBuffer.updateColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  29374. // GAMMA CORRECTION.
  29375. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  29376. this._uniformBuffer.updateColor3("vReflectionColor", PBRMaterial._scaledReflection);
  29377. // GAMMA CORRECTION.
  29378. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  29379. this._uniformBuffer.updateColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  29380. // Misc
  29381. this._lightingInfos.x = this.directIntensity;
  29382. this._lightingInfos.y = this.emissiveIntensity;
  29383. this._lightingInfos.z = this.environmentIntensity;
  29384. this._lightingInfos.w = this.specularIntensity;
  29385. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  29386. // Overloaded params
  29387. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  29388. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  29389. this._uniformBuffer.updateVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  29390. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  29391. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  29392. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  29393. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  29394. this._uniformBuffer.updateVector4("vOverloadedIntensity", this._overloadedIntensity);
  29395. this._uniformBuffer.updateColor3("vOverloadedAmbient", this.overloadedAmbient);
  29396. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  29397. this._uniformBuffer.updateColor3("vOverloadedAlbedo", this._tempColor);
  29398. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  29399. this._uniformBuffer.updateColor3("vOverloadedReflectivity", this._tempColor);
  29400. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  29401. this._uniformBuffer.updateColor3("vOverloadedEmissive", this._tempColor);
  29402. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  29403. this._uniformBuffer.updateColor3("vOverloadedReflection", this._tempColor);
  29404. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  29405. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  29406. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  29407. this._uniformBuffer.updateVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  29408. }
  29409. // Textures
  29410. if (this._myScene.texturesEnabled) {
  29411. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29412. this._uniformBuffer.setTexture("albedoSampler", this.albedoTexture);
  29413. }
  29414. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  29415. this._uniformBuffer.setTexture("ambientSampler", this.ambientTexture);
  29416. }
  29417. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  29418. this._uniformBuffer.setTexture("opacitySampler", this.opacityTexture);
  29419. }
  29420. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  29421. if (this.reflectionTexture.isCube) {
  29422. this._uniformBuffer.setTexture("reflectionCubeSampler", this.reflectionTexture);
  29423. }
  29424. else {
  29425. this._uniformBuffer.setTexture("reflection2DSampler", this.reflectionTexture);
  29426. }
  29427. }
  29428. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  29429. this._uniformBuffer.setTexture("emissiveSampler", this.emissiveTexture);
  29430. }
  29431. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  29432. this._uniformBuffer.setTexture("lightmapSampler", this.lightmapTexture);
  29433. }
  29434. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  29435. if (this.metallicTexture) {
  29436. this._uniformBuffer.setTexture("reflectivitySampler", this.metallicTexture);
  29437. }
  29438. else if (this.reflectivityTexture) {
  29439. this._uniformBuffer.setTexture("reflectivitySampler", this.reflectivityTexture);
  29440. }
  29441. if (this.microSurfaceTexture) {
  29442. this._uniformBuffer.setTexture("microSurfaceSampler", this.microSurfaceTexture);
  29443. }
  29444. }
  29445. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  29446. this._uniformBuffer.setTexture("bumpSampler", this.bumpTexture);
  29447. }
  29448. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  29449. if (this.refractionTexture.isCube) {
  29450. this._uniformBuffer.setTexture("refractionCubeSampler", this.refractionTexture);
  29451. }
  29452. else {
  29453. this._uniformBuffer.setTexture("refraction2DSampler", this.refractionTexture);
  29454. }
  29455. }
  29456. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  29457. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  29458. }
  29459. }
  29460. // Clip plane
  29461. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  29462. // Colors
  29463. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  29464. effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  29465. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  29466. }
  29467. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  29468. // Lights
  29469. if (this._myScene.lightsEnabled && !this.disableLighting) {
  29470. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  29471. }
  29472. // View
  29473. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  29474. this.bindView(effect);
  29475. }
  29476. // Fog
  29477. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  29478. // Morph targets
  29479. if (this._defines.NUM_MORPH_INFLUENCERS) {
  29480. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  29481. }
  29482. this._cameraInfos.x = this.cameraExposure;
  29483. this._cameraInfos.y = this.cameraContrast;
  29484. effect.setVector4("vCameraInfos", this._cameraInfos);
  29485. if (this.cameraColorCurves) {
  29486. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  29487. }
  29488. // Log. depth
  29489. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  29490. }
  29491. this._uniformBuffer.update();
  29492. this._afterBind(mesh);
  29493. this._myScene = null;
  29494. };
  29495. PBRMaterial.prototype.getAnimatables = function () {
  29496. var results = [];
  29497. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  29498. results.push(this.albedoTexture);
  29499. }
  29500. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  29501. results.push(this.ambientTexture);
  29502. }
  29503. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  29504. results.push(this.opacityTexture);
  29505. }
  29506. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  29507. results.push(this.reflectionTexture);
  29508. }
  29509. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  29510. results.push(this.emissiveTexture);
  29511. }
  29512. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  29513. results.push(this.metallicTexture);
  29514. }
  29515. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  29516. results.push(this.reflectivityTexture);
  29517. }
  29518. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  29519. results.push(this.bumpTexture);
  29520. }
  29521. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  29522. results.push(this.lightmapTexture);
  29523. }
  29524. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  29525. results.push(this.refractionTexture);
  29526. }
  29527. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  29528. results.push(this.cameraColorGradingTexture);
  29529. }
  29530. return results;
  29531. };
  29532. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29533. if (forceDisposeTextures) {
  29534. if (this.albedoTexture) {
  29535. this.albedoTexture.dispose();
  29536. }
  29537. if (this.ambientTexture) {
  29538. this.ambientTexture.dispose();
  29539. }
  29540. if (this.opacityTexture) {
  29541. this.opacityTexture.dispose();
  29542. }
  29543. if (this.reflectionTexture) {
  29544. this.reflectionTexture.dispose();
  29545. }
  29546. if (this.emissiveTexture) {
  29547. this.emissiveTexture.dispose();
  29548. }
  29549. if (this.metallicTexture) {
  29550. this.metallicTexture.dispose();
  29551. }
  29552. if (this.reflectivityTexture) {
  29553. this.reflectivityTexture.dispose();
  29554. }
  29555. if (this.bumpTexture) {
  29556. this.bumpTexture.dispose();
  29557. }
  29558. if (this.lightmapTexture) {
  29559. this.lightmapTexture.dispose();
  29560. }
  29561. if (this.refractionTexture) {
  29562. this.refractionTexture.dispose();
  29563. }
  29564. if (this.cameraColorGradingTexture) {
  29565. this.cameraColorGradingTexture.dispose();
  29566. }
  29567. }
  29568. this._renderTargets.dispose();
  29569. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  29570. };
  29571. PBRMaterial.prototype.clone = function (name) {
  29572. var _this = this;
  29573. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  29574. };
  29575. PBRMaterial.prototype.serialize = function () {
  29576. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29577. serializationObject.customType = "BABYLON.PBRMaterial";
  29578. return serializationObject;
  29579. };
  29580. // Statics
  29581. PBRMaterial.Parse = function (source, scene, rootUrl) {
  29582. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  29583. };
  29584. return PBRMaterial;
  29585. }(BABYLON.Material));
  29586. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  29587. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  29588. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  29589. PBRMaterial._scaledReflection = new BABYLON.Color3();
  29590. __decorate([
  29591. BABYLON.serialize()
  29592. ], PBRMaterial.prototype, "directIntensity", void 0);
  29593. __decorate([
  29594. BABYLON.serialize()
  29595. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  29596. __decorate([
  29597. BABYLON.serialize()
  29598. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  29599. __decorate([
  29600. BABYLON.serialize()
  29601. ], PBRMaterial.prototype, "specularIntensity", void 0);
  29602. __decorate([
  29603. BABYLON.serialize()
  29604. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  29605. __decorate([
  29606. BABYLON.serialize()
  29607. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  29608. __decorate([
  29609. BABYLON.serialize()
  29610. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  29611. __decorate([
  29612. BABYLON.serialize()
  29613. ], PBRMaterial.prototype, "cameraExposure", void 0);
  29614. __decorate([
  29615. BABYLON.serialize()
  29616. ], PBRMaterial.prototype, "cameraContrast", void 0);
  29617. __decorate([
  29618. BABYLON.serializeAsTexture()
  29619. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  29620. __decorate([
  29621. BABYLON.serializeAsColorCurves()
  29622. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  29623. __decorate([
  29624. BABYLON.serializeAsColor3()
  29625. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  29626. __decorate([
  29627. BABYLON.serialize()
  29628. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  29629. __decorate([
  29630. BABYLON.serializeAsColor3()
  29631. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  29632. __decorate([
  29633. BABYLON.serialize()
  29634. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  29635. __decorate([
  29636. BABYLON.serializeAsColor3()
  29637. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  29638. __decorate([
  29639. BABYLON.serialize()
  29640. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  29641. __decorate([
  29642. BABYLON.serializeAsColor3()
  29643. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  29644. __decorate([
  29645. BABYLON.serialize()
  29646. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  29647. __decorate([
  29648. BABYLON.serializeAsColor3()
  29649. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  29650. __decorate([
  29651. BABYLON.serialize()
  29652. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  29653. __decorate([
  29654. BABYLON.serialize()
  29655. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  29656. __decorate([
  29657. BABYLON.serialize()
  29658. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  29659. __decorate([
  29660. BABYLON.serializeAsTexture()
  29661. ], PBRMaterial.prototype, "albedoTexture", void 0);
  29662. __decorate([
  29663. BABYLON.serializeAsTexture()
  29664. ], PBRMaterial.prototype, "ambientTexture", void 0);
  29665. __decorate([
  29666. BABYLON.serialize()
  29667. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  29668. __decorate([
  29669. BABYLON.serializeAsTexture()
  29670. ], PBRMaterial.prototype, "opacityTexture", void 0);
  29671. __decorate([
  29672. BABYLON.serializeAsTexture()
  29673. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  29674. __decorate([
  29675. BABYLON.serializeAsTexture()
  29676. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  29677. __decorate([
  29678. BABYLON.serializeAsTexture()
  29679. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  29680. __decorate([
  29681. BABYLON.serializeAsTexture()
  29682. ], PBRMaterial.prototype, "metallicTexture", void 0);
  29683. __decorate([
  29684. BABYLON.serialize()
  29685. ], PBRMaterial.prototype, "metallic", void 0);
  29686. __decorate([
  29687. BABYLON.serialize()
  29688. ], PBRMaterial.prototype, "roughness", void 0);
  29689. __decorate([
  29690. BABYLON.serializeAsTexture()
  29691. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  29692. __decorate([
  29693. BABYLON.serializeAsTexture()
  29694. ], PBRMaterial.prototype, "bumpTexture", void 0);
  29695. __decorate([
  29696. BABYLON.serializeAsTexture()
  29697. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  29698. __decorate([
  29699. BABYLON.serializeAsTexture()
  29700. ], PBRMaterial.prototype, "refractionTexture", void 0);
  29701. __decorate([
  29702. BABYLON.serializeAsColor3("ambient")
  29703. ], PBRMaterial.prototype, "ambientColor", void 0);
  29704. __decorate([
  29705. BABYLON.serializeAsColor3("albedo")
  29706. ], PBRMaterial.prototype, "albedoColor", void 0);
  29707. __decorate([
  29708. BABYLON.serializeAsColor3("reflectivity")
  29709. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  29710. __decorate([
  29711. BABYLON.serializeAsColor3("reflection")
  29712. ], PBRMaterial.prototype, "reflectionColor", void 0);
  29713. __decorate([
  29714. BABYLON.serializeAsColor3("emissive")
  29715. ], PBRMaterial.prototype, "emissiveColor", void 0);
  29716. __decorate([
  29717. BABYLON.serialize()
  29718. ], PBRMaterial.prototype, "microSurface", void 0);
  29719. __decorate([
  29720. BABYLON.serialize()
  29721. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  29722. __decorate([
  29723. BABYLON.serialize()
  29724. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  29725. __decorate([
  29726. BABYLON.serializeAsFresnelParameters()
  29727. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  29728. __decorate([
  29729. BABYLON.serializeAsFresnelParameters()
  29730. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  29731. __decorate([
  29732. BABYLON.serialize()
  29733. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  29734. __decorate([
  29735. BABYLON.serialize()
  29736. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  29737. __decorate([
  29738. BABYLON.serialize()
  29739. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  29740. __decorate([
  29741. BABYLON.serialize()
  29742. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  29743. __decorate([
  29744. BABYLON.serialize()
  29745. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  29746. __decorate([
  29747. BABYLON.serialize()
  29748. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  29749. __decorate([
  29750. BABYLON.serialize()
  29751. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  29752. __decorate([
  29753. BABYLON.serialize()
  29754. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  29755. __decorate([
  29756. BABYLON.serialize()
  29757. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  29758. __decorate([
  29759. BABYLON.serialize()
  29760. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  29761. __decorate([
  29762. BABYLON.serialize()
  29763. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  29764. __decorate([
  29765. BABYLON.serialize()
  29766. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  29767. __decorate([
  29768. BABYLON.serialize()
  29769. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  29770. __decorate([
  29771. BABYLON.serialize()
  29772. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  29773. __decorate([
  29774. BABYLON.serialize()
  29775. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  29776. __decorate([
  29777. BABYLON.serialize()
  29778. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  29779. __decorate([
  29780. BABYLON.serialize()
  29781. ], PBRMaterial.prototype, "useParallax", void 0);
  29782. __decorate([
  29783. BABYLON.serialize()
  29784. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  29785. __decorate([
  29786. BABYLON.serialize()
  29787. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  29788. __decorate([
  29789. BABYLON.serialize()
  29790. ], PBRMaterial.prototype, "disableLighting", void 0);
  29791. __decorate([
  29792. BABYLON.serialize()
  29793. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  29794. __decorate([
  29795. BABYLON.serialize()
  29796. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  29797. __decorate([
  29798. BABYLON.serialize()
  29799. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  29800. __decorate([
  29801. BABYLON.serialize()
  29802. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  29803. __decorate([
  29804. BABYLON.serialize()
  29805. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  29806. BABYLON.PBRMaterial = PBRMaterial;
  29807. })(BABYLON || (BABYLON = {}));
  29808. //# sourceMappingURL=babylon.pbrMaterial.js.map
  29809. var BABYLON;
  29810. (function (BABYLON) {
  29811. BABYLON.CameraInputTypes = {};
  29812. var CameraInputsManager = (function () {
  29813. function CameraInputsManager(camera) {
  29814. this.attached = {};
  29815. this.camera = camera;
  29816. this.checkInputs = function () { };
  29817. }
  29818. CameraInputsManager.prototype.add = function (input) {
  29819. var type = input.getSimpleName();
  29820. if (this.attached[type]) {
  29821. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  29822. return;
  29823. }
  29824. this.attached[type] = input;
  29825. input.camera = this.camera;
  29826. //for checkInputs, we are dynamically creating a function
  29827. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  29828. if (input.checkInputs) {
  29829. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29830. }
  29831. if (this.attachedElement) {
  29832. input.attachControl(this.attachedElement);
  29833. }
  29834. };
  29835. CameraInputsManager.prototype.remove = function (inputToRemove) {
  29836. for (var cam in this.attached) {
  29837. var input = this.attached[cam];
  29838. if (input === inputToRemove) {
  29839. input.detachControl(this.attachedElement);
  29840. delete this.attached[cam];
  29841. this.rebuildInputCheck();
  29842. }
  29843. }
  29844. };
  29845. CameraInputsManager.prototype.removeByType = function (inputType) {
  29846. for (var cam in this.attached) {
  29847. var input = this.attached[cam];
  29848. if (input.getTypeName() === inputType) {
  29849. input.detachControl(this.attachedElement);
  29850. delete this.attached[cam];
  29851. this.rebuildInputCheck();
  29852. }
  29853. }
  29854. };
  29855. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  29856. var current = this.checkInputs;
  29857. return function () {
  29858. current();
  29859. fn();
  29860. };
  29861. };
  29862. CameraInputsManager.prototype.attachInput = function (input) {
  29863. input.attachControl(this.attachedElement, this.noPreventDefault);
  29864. };
  29865. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  29866. if (this.attachedElement) {
  29867. return;
  29868. }
  29869. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  29870. this.attachedElement = element;
  29871. this.noPreventDefault = noPreventDefault;
  29872. for (var cam in this.attached) {
  29873. var input = this.attached[cam];
  29874. this.attached[cam].attachControl(element, noPreventDefault);
  29875. }
  29876. };
  29877. CameraInputsManager.prototype.detachElement = function (element) {
  29878. if (this.attachedElement !== element) {
  29879. return;
  29880. }
  29881. for (var cam in this.attached) {
  29882. var input = this.attached[cam];
  29883. this.attached[cam].detachControl(element);
  29884. }
  29885. this.attachedElement = null;
  29886. };
  29887. CameraInputsManager.prototype.rebuildInputCheck = function () {
  29888. this.checkInputs = function () { };
  29889. for (var cam in this.attached) {
  29890. var input = this.attached[cam];
  29891. if (input.checkInputs) {
  29892. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29893. }
  29894. }
  29895. };
  29896. CameraInputsManager.prototype.clear = function () {
  29897. if (this.attachedElement) {
  29898. this.detachElement(this.attachedElement);
  29899. }
  29900. this.attached = {};
  29901. this.attachedElement = null;
  29902. this.checkInputs = function () { };
  29903. };
  29904. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  29905. var inputs = {};
  29906. for (var cam in this.attached) {
  29907. var input = this.attached[cam];
  29908. var res = BABYLON.SerializationHelper.Serialize(input);
  29909. inputs[input.getTypeName()] = res;
  29910. }
  29911. serializedCamera.inputsmgr = inputs;
  29912. };
  29913. CameraInputsManager.prototype.parse = function (parsedCamera) {
  29914. var parsedInputs = parsedCamera.inputsmgr;
  29915. if (parsedInputs) {
  29916. this.clear();
  29917. for (var n in parsedInputs) {
  29918. var construct = BABYLON.CameraInputTypes[n];
  29919. if (construct) {
  29920. var parsedinput = parsedInputs[n];
  29921. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  29922. this.add(input);
  29923. }
  29924. }
  29925. }
  29926. else {
  29927. //2016-03-08 this part is for managing backward compatibility
  29928. for (var n in this.attached) {
  29929. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  29930. if (construct) {
  29931. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  29932. this.remove(this.attached[n]);
  29933. this.add(input);
  29934. }
  29935. }
  29936. }
  29937. };
  29938. return CameraInputsManager;
  29939. }());
  29940. BABYLON.CameraInputsManager = CameraInputsManager;
  29941. })(BABYLON || (BABYLON = {}));
  29942. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  29943. var BABYLON;
  29944. (function (BABYLON) {
  29945. var FreeCameraMouseInput = (function () {
  29946. function FreeCameraMouseInput(touchEnabled) {
  29947. if (touchEnabled === void 0) { touchEnabled = true; }
  29948. this.touchEnabled = touchEnabled;
  29949. this.buttons = [0, 1, 2];
  29950. this.angularSensibility = 2000.0;
  29951. }
  29952. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  29953. var _this = this;
  29954. var engine = this.camera.getEngine();
  29955. if (!this._pointerInput) {
  29956. this._pointerInput = function (p, s) {
  29957. var evt = p.event;
  29958. if (!_this.touchEnabled && evt.pointerType === "touch") {
  29959. return;
  29960. }
  29961. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  29962. return;
  29963. }
  29964. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  29965. try {
  29966. evt.srcElement.setPointerCapture(evt.pointerId);
  29967. }
  29968. catch (e) {
  29969. //Nothing to do with the error. Execution will continue.
  29970. }
  29971. _this.previousPosition = {
  29972. x: evt.clientX,
  29973. y: evt.clientY
  29974. };
  29975. if (!noPreventDefault) {
  29976. evt.preventDefault();
  29977. element.focus();
  29978. }
  29979. }
  29980. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  29981. try {
  29982. evt.srcElement.releasePointerCapture(evt.pointerId);
  29983. }
  29984. catch (e) {
  29985. //Nothing to do with the error.
  29986. }
  29987. _this.previousPosition = null;
  29988. if (!noPreventDefault) {
  29989. evt.preventDefault();
  29990. }
  29991. }
  29992. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  29993. if (!_this.previousPosition || engine.isPointerLock) {
  29994. return;
  29995. }
  29996. var offsetX = evt.clientX - _this.previousPosition.x;
  29997. var offsetY = evt.clientY - _this.previousPosition.y;
  29998. if (_this.camera.getScene().useRightHandedSystem) {
  29999. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  30000. }
  30001. else {
  30002. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  30003. }
  30004. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  30005. _this.previousPosition = {
  30006. x: evt.clientX,
  30007. y: evt.clientY
  30008. };
  30009. if (!noPreventDefault) {
  30010. evt.preventDefault();
  30011. }
  30012. }
  30013. };
  30014. }
  30015. this._onMouseMove = function (evt) {
  30016. if (!engine.isPointerLock) {
  30017. return;
  30018. }
  30019. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  30020. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  30021. if (_this.camera.getScene().useRightHandedSystem) {
  30022. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  30023. }
  30024. else {
  30025. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  30026. }
  30027. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  30028. _this.previousPosition = null;
  30029. if (!noPreventDefault) {
  30030. evt.preventDefault();
  30031. }
  30032. };
  30033. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  30034. element.addEventListener("mousemove", this._onMouseMove, false);
  30035. };
  30036. FreeCameraMouseInput.prototype.detachControl = function (element) {
  30037. if (this._observer && element) {
  30038. this.camera.getScene().onPointerObservable.remove(this._observer);
  30039. element.removeEventListener("mousemove", this._onMouseMove);
  30040. this._observer = null;
  30041. this._onMouseMove = null;
  30042. this.previousPosition = null;
  30043. }
  30044. };
  30045. FreeCameraMouseInput.prototype.getTypeName = function () {
  30046. return "FreeCameraMouseInput";
  30047. };
  30048. FreeCameraMouseInput.prototype.getSimpleName = function () {
  30049. return "mouse";
  30050. };
  30051. return FreeCameraMouseInput;
  30052. }());
  30053. __decorate([
  30054. BABYLON.serialize()
  30055. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  30056. __decorate([
  30057. BABYLON.serialize()
  30058. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  30059. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  30060. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  30061. })(BABYLON || (BABYLON = {}));
  30062. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  30063. var BABYLON;
  30064. (function (BABYLON) {
  30065. var FreeCameraKeyboardMoveInput = (function () {
  30066. function FreeCameraKeyboardMoveInput() {
  30067. this._keys = [];
  30068. this.keysUp = [38];
  30069. this.keysDown = [40];
  30070. this.keysLeft = [37];
  30071. this.keysRight = [39];
  30072. }
  30073. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  30074. var _this = this;
  30075. if (!this._onKeyDown) {
  30076. element.tabIndex = 1;
  30077. this._onKeyDown = function (evt) {
  30078. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30079. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30080. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30081. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30082. var index = _this._keys.indexOf(evt.keyCode);
  30083. if (index === -1) {
  30084. _this._keys.push(evt.keyCode);
  30085. }
  30086. if (!noPreventDefault) {
  30087. evt.preventDefault();
  30088. }
  30089. }
  30090. };
  30091. this._onKeyUp = function (evt) {
  30092. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30093. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30094. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30095. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30096. var index = _this._keys.indexOf(evt.keyCode);
  30097. if (index >= 0) {
  30098. _this._keys.splice(index, 1);
  30099. }
  30100. if (!noPreventDefault) {
  30101. evt.preventDefault();
  30102. }
  30103. }
  30104. };
  30105. element.addEventListener("keydown", this._onKeyDown, false);
  30106. element.addEventListener("keyup", this._onKeyUp, false);
  30107. BABYLON.Tools.RegisterTopRootEvents([
  30108. { name: "blur", handler: this._onLostFocus }
  30109. ]);
  30110. }
  30111. };
  30112. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  30113. if (this._onKeyDown) {
  30114. element.removeEventListener("keydown", this._onKeyDown);
  30115. element.removeEventListener("keyup", this._onKeyUp);
  30116. BABYLON.Tools.UnregisterTopRootEvents([
  30117. { name: "blur", handler: this._onLostFocus }
  30118. ]);
  30119. this._keys = [];
  30120. this._onKeyDown = null;
  30121. this._onKeyUp = null;
  30122. }
  30123. };
  30124. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  30125. if (this._onKeyDown) {
  30126. var camera = this.camera;
  30127. // Keyboard
  30128. for (var index = 0; index < this._keys.length; index++) {
  30129. var keyCode = this._keys[index];
  30130. var speed = camera._computeLocalCameraSpeed();
  30131. if (this.keysLeft.indexOf(keyCode) !== -1) {
  30132. camera._localDirection.copyFromFloats(-speed, 0, 0);
  30133. }
  30134. else if (this.keysUp.indexOf(keyCode) !== -1) {
  30135. camera._localDirection.copyFromFloats(0, 0, speed);
  30136. }
  30137. else if (this.keysRight.indexOf(keyCode) !== -1) {
  30138. camera._localDirection.copyFromFloats(speed, 0, 0);
  30139. }
  30140. else if (this.keysDown.indexOf(keyCode) !== -1) {
  30141. camera._localDirection.copyFromFloats(0, 0, -speed);
  30142. }
  30143. if (camera.getScene().useRightHandedSystem) {
  30144. camera._localDirection.z *= -1;
  30145. }
  30146. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  30147. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  30148. camera.cameraDirection.addInPlace(camera._transformedDirection);
  30149. }
  30150. }
  30151. };
  30152. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  30153. return "FreeCameraKeyboardMoveInput";
  30154. };
  30155. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  30156. this._keys = [];
  30157. };
  30158. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  30159. return "keyboard";
  30160. };
  30161. return FreeCameraKeyboardMoveInput;
  30162. }());
  30163. __decorate([
  30164. BABYLON.serialize()
  30165. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  30166. __decorate([
  30167. BABYLON.serialize()
  30168. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  30169. __decorate([
  30170. BABYLON.serialize()
  30171. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  30172. __decorate([
  30173. BABYLON.serialize()
  30174. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  30175. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  30176. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  30177. })(BABYLON || (BABYLON = {}));
  30178. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  30179. var BABYLON;
  30180. (function (BABYLON) {
  30181. var FreeCameraInputsManager = (function (_super) {
  30182. __extends(FreeCameraInputsManager, _super);
  30183. function FreeCameraInputsManager(camera) {
  30184. return _super.call(this, camera) || this;
  30185. }
  30186. FreeCameraInputsManager.prototype.addKeyboard = function () {
  30187. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  30188. return this;
  30189. };
  30190. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  30191. if (touchEnabled === void 0) { touchEnabled = true; }
  30192. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  30193. return this;
  30194. };
  30195. FreeCameraInputsManager.prototype.addGamepad = function () {
  30196. this.add(new BABYLON.FreeCameraGamepadInput());
  30197. return this;
  30198. };
  30199. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  30200. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  30201. return this;
  30202. };
  30203. FreeCameraInputsManager.prototype.addTouch = function () {
  30204. this.add(new BABYLON.FreeCameraTouchInput());
  30205. return this;
  30206. };
  30207. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  30208. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  30209. return this;
  30210. };
  30211. return FreeCameraInputsManager;
  30212. }(BABYLON.CameraInputsManager));
  30213. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  30214. })(BABYLON || (BABYLON = {}));
  30215. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  30216. /// <reference path="babylon.camera.ts" />
  30217. var BABYLON;
  30218. (function (BABYLON) {
  30219. var TargetCamera = (function (_super) {
  30220. __extends(TargetCamera, _super);
  30221. function TargetCamera(name, position, scene) {
  30222. var _this = _super.call(this, name, position, scene) || this;
  30223. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  30224. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  30225. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  30226. _this.speed = 2.0;
  30227. _this.noRotationConstraint = false;
  30228. _this.lockedTarget = null;
  30229. _this._currentTarget = BABYLON.Vector3.Zero();
  30230. _this._viewMatrix = BABYLON.Matrix.Zero();
  30231. _this._camMatrix = BABYLON.Matrix.Zero();
  30232. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  30233. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  30234. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  30235. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  30236. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  30237. _this._lookAtTemp = BABYLON.Matrix.Zero();
  30238. _this._tempMatrix = BABYLON.Matrix.Zero();
  30239. return _this;
  30240. }
  30241. TargetCamera.prototype.getFrontPosition = function (distance) {
  30242. var direction = this.getTarget().subtract(this.position);
  30243. direction.normalize();
  30244. direction.scaleInPlace(distance);
  30245. return this.globalPosition.add(direction);
  30246. };
  30247. TargetCamera.prototype._getLockedTargetPosition = function () {
  30248. if (!this.lockedTarget) {
  30249. return null;
  30250. }
  30251. if (this.lockedTarget.absolutePosition) {
  30252. this.lockedTarget.computeWorldMatrix();
  30253. }
  30254. return this.lockedTarget.absolutePosition || this.lockedTarget;
  30255. };
  30256. // Cache
  30257. TargetCamera.prototype._initCache = function () {
  30258. _super.prototype._initCache.call(this);
  30259. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30260. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30261. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30262. };
  30263. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  30264. if (!ignoreParentClass) {
  30265. _super.prototype._updateCache.call(this);
  30266. }
  30267. var lockedTargetPosition = this._getLockedTargetPosition();
  30268. if (!lockedTargetPosition) {
  30269. this._cache.lockedTarget = null;
  30270. }
  30271. else {
  30272. if (!this._cache.lockedTarget) {
  30273. this._cache.lockedTarget = lockedTargetPosition.clone();
  30274. }
  30275. else {
  30276. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  30277. }
  30278. }
  30279. this._cache.rotation.copyFrom(this.rotation);
  30280. if (this.rotationQuaternion)
  30281. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30282. };
  30283. // Synchronized
  30284. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  30285. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  30286. return false;
  30287. }
  30288. var lockedTargetPosition = this._getLockedTargetPosition();
  30289. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  30290. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  30291. };
  30292. // Methods
  30293. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  30294. var engine = this.getEngine();
  30295. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  30296. };
  30297. // Target
  30298. TargetCamera.prototype.setTarget = function (target) {
  30299. this.upVector.normalize();
  30300. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  30301. this._camMatrix.invert();
  30302. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  30303. var vDir = target.subtract(this.position);
  30304. if (vDir.x >= 0.0) {
  30305. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  30306. }
  30307. else {
  30308. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  30309. }
  30310. this.rotation.z = 0;
  30311. if (isNaN(this.rotation.x)) {
  30312. this.rotation.x = 0;
  30313. }
  30314. if (isNaN(this.rotation.y)) {
  30315. this.rotation.y = 0;
  30316. }
  30317. if (isNaN(this.rotation.z)) {
  30318. this.rotation.z = 0;
  30319. }
  30320. if (this.rotationQuaternion) {
  30321. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  30322. }
  30323. };
  30324. /**
  30325. * Return the current target position of the camera. This value is expressed in local space.
  30326. */
  30327. TargetCamera.prototype.getTarget = function () {
  30328. return this._currentTarget;
  30329. };
  30330. TargetCamera.prototype._decideIfNeedsToMove = function () {
  30331. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  30332. };
  30333. TargetCamera.prototype._updatePosition = function () {
  30334. if (this.parent) {
  30335. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  30336. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  30337. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  30338. return;
  30339. }
  30340. this.position.addInPlace(this.cameraDirection);
  30341. };
  30342. TargetCamera.prototype._checkInputs = function () {
  30343. var needToMove = this._decideIfNeedsToMove();
  30344. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  30345. // Move
  30346. if (needToMove) {
  30347. this._updatePosition();
  30348. }
  30349. // Rotate
  30350. if (needToRotate) {
  30351. this.rotation.x += this.cameraRotation.x;
  30352. this.rotation.y += this.cameraRotation.y;
  30353. //rotate, if quaternion is set and rotation was used
  30354. if (this.rotationQuaternion) {
  30355. var len = this.rotation.lengthSquared();
  30356. if (len) {
  30357. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  30358. }
  30359. }
  30360. if (!this.noRotationConstraint) {
  30361. var limit = (Math.PI / 2) * 0.95;
  30362. if (this.rotation.x > limit)
  30363. this.rotation.x = limit;
  30364. if (this.rotation.x < -limit)
  30365. this.rotation.x = -limit;
  30366. }
  30367. }
  30368. // Inertia
  30369. if (needToMove) {
  30370. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  30371. this.cameraDirection.x = 0;
  30372. }
  30373. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  30374. this.cameraDirection.y = 0;
  30375. }
  30376. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  30377. this.cameraDirection.z = 0;
  30378. }
  30379. this.cameraDirection.scaleInPlace(this.inertia);
  30380. }
  30381. if (needToRotate) {
  30382. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  30383. this.cameraRotation.x = 0;
  30384. }
  30385. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  30386. this.cameraRotation.y = 0;
  30387. }
  30388. this.cameraRotation.scaleInPlace(this.inertia);
  30389. }
  30390. _super.prototype._checkInputs.call(this);
  30391. };
  30392. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  30393. if (this.rotationQuaternion) {
  30394. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  30395. //update the up vector!
  30396. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  30397. }
  30398. else {
  30399. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  30400. }
  30401. };
  30402. TargetCamera.prototype._getViewMatrix = function () {
  30403. if (!this.lockedTarget) {
  30404. // Compute
  30405. this._updateCameraRotationMatrix();
  30406. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  30407. // Computing target and final matrix
  30408. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  30409. }
  30410. else {
  30411. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  30412. }
  30413. if (this.getScene().useRightHandedSystem) {
  30414. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  30415. }
  30416. else {
  30417. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  30418. }
  30419. return this._viewMatrix;
  30420. };
  30421. /**
  30422. * @override
  30423. * Override Camera.createRigCamera
  30424. */
  30425. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  30426. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  30427. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  30428. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  30429. if (!this.rotationQuaternion) {
  30430. this.rotationQuaternion = new BABYLON.Quaternion();
  30431. }
  30432. rigCamera._cameraRigParams = {};
  30433. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  30434. }
  30435. return rigCamera;
  30436. }
  30437. return null;
  30438. };
  30439. /**
  30440. * @override
  30441. * Override Camera._updateRigCameras
  30442. */
  30443. TargetCamera.prototype._updateRigCameras = function () {
  30444. var camLeft = this._rigCameras[0];
  30445. var camRight = this._rigCameras[1];
  30446. switch (this.cameraRigMode) {
  30447. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30448. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30449. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30450. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30451. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  30452. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  30453. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  30454. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  30455. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  30456. camLeft.setTarget(this.getTarget());
  30457. camRight.setTarget(this.getTarget());
  30458. break;
  30459. case BABYLON.Camera.RIG_MODE_VR:
  30460. if (camLeft.rotationQuaternion) {
  30461. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30462. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30463. }
  30464. else {
  30465. camLeft.rotation.copyFrom(this.rotation);
  30466. camRight.rotation.copyFrom(this.rotation);
  30467. }
  30468. camLeft.position.copyFrom(this.position);
  30469. camRight.position.copyFrom(this.position);
  30470. break;
  30471. }
  30472. _super.prototype._updateRigCameras.call(this);
  30473. };
  30474. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  30475. if (!this._rigCamTransformMatrix) {
  30476. this._rigCamTransformMatrix = new BABYLON.Matrix();
  30477. }
  30478. var target = this.getTarget();
  30479. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  30480. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  30481. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  30482. };
  30483. TargetCamera.prototype.getClassName = function () {
  30484. return "TargetCamera";
  30485. };
  30486. return TargetCamera;
  30487. }(BABYLON.Camera));
  30488. __decorate([
  30489. BABYLON.serializeAsVector3()
  30490. ], TargetCamera.prototype, "rotation", void 0);
  30491. __decorate([
  30492. BABYLON.serialize()
  30493. ], TargetCamera.prototype, "speed", void 0);
  30494. __decorate([
  30495. BABYLON.serializeAsMeshReference("lockedTargetId")
  30496. ], TargetCamera.prototype, "lockedTarget", void 0);
  30497. BABYLON.TargetCamera = TargetCamera;
  30498. })(BABYLON || (BABYLON = {}));
  30499. //# sourceMappingURL=babylon.targetCamera.js.map
  30500. var BABYLON;
  30501. (function (BABYLON) {
  30502. var FreeCamera = (function (_super) {
  30503. __extends(FreeCamera, _super);
  30504. function FreeCamera(name, position, scene) {
  30505. var _this = _super.call(this, name, position, scene) || this;
  30506. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  30507. _this.checkCollisions = false;
  30508. _this.applyGravity = false;
  30509. _this._needMoveForGravity = false;
  30510. _this._oldPosition = BABYLON.Vector3.Zero();
  30511. _this._diffPosition = BABYLON.Vector3.Zero();
  30512. _this._newPosition = BABYLON.Vector3.Zero();
  30513. // Collisions
  30514. _this._collisionMask = -1;
  30515. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  30516. if (collidedMesh === void 0) { collidedMesh = null; }
  30517. //TODO move this to the collision coordinator!
  30518. if (_this.getScene().workerCollisions)
  30519. newPosition.multiplyInPlace(_this._collider.radius);
  30520. var updatePosition = function (newPos) {
  30521. _this._newPosition.copyFrom(newPos);
  30522. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  30523. var oldPosition = _this.position.clone();
  30524. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  30525. _this.position.addInPlace(_this._diffPosition);
  30526. if (_this.onCollide && collidedMesh) {
  30527. _this.onCollide(collidedMesh);
  30528. }
  30529. }
  30530. };
  30531. updatePosition(newPosition);
  30532. };
  30533. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  30534. _this.inputs.addKeyboard().addMouse();
  30535. return _this;
  30536. }
  30537. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  30538. //-- begin properties for backward compatibility for inputs
  30539. get: function () {
  30540. var mouse = this.inputs.attached["mouse"];
  30541. if (mouse)
  30542. return mouse.angularSensibility;
  30543. },
  30544. set: function (value) {
  30545. var mouse = this.inputs.attached["mouse"];
  30546. if (mouse)
  30547. mouse.angularSensibility = value;
  30548. },
  30549. enumerable: true,
  30550. configurable: true
  30551. });
  30552. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  30553. get: function () {
  30554. var keyboard = this.inputs.attached["keyboard"];
  30555. if (keyboard)
  30556. return keyboard.keysUp;
  30557. },
  30558. set: function (value) {
  30559. var keyboard = this.inputs.attached["keyboard"];
  30560. if (keyboard)
  30561. keyboard.keysUp = value;
  30562. },
  30563. enumerable: true,
  30564. configurable: true
  30565. });
  30566. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  30567. get: function () {
  30568. var keyboard = this.inputs.attached["keyboard"];
  30569. if (keyboard)
  30570. return keyboard.keysDown;
  30571. },
  30572. set: function (value) {
  30573. var keyboard = this.inputs.attached["keyboard"];
  30574. if (keyboard)
  30575. keyboard.keysDown = value;
  30576. },
  30577. enumerable: true,
  30578. configurable: true
  30579. });
  30580. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  30581. get: function () {
  30582. var keyboard = this.inputs.attached["keyboard"];
  30583. if (keyboard)
  30584. return keyboard.keysLeft;
  30585. },
  30586. set: function (value) {
  30587. var keyboard = this.inputs.attached["keyboard"];
  30588. if (keyboard)
  30589. keyboard.keysLeft = value;
  30590. },
  30591. enumerable: true,
  30592. configurable: true
  30593. });
  30594. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  30595. get: function () {
  30596. var keyboard = this.inputs.attached["keyboard"];
  30597. if (keyboard)
  30598. return keyboard.keysRight;
  30599. },
  30600. set: function (value) {
  30601. var keyboard = this.inputs.attached["keyboard"];
  30602. if (keyboard)
  30603. keyboard.keysRight = value;
  30604. },
  30605. enumerable: true,
  30606. configurable: true
  30607. });
  30608. // Controls
  30609. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30610. this.inputs.attachElement(element, noPreventDefault);
  30611. };
  30612. FreeCamera.prototype.detachControl = function (element) {
  30613. this.inputs.detachElement(element);
  30614. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  30615. this.cameraRotation = new BABYLON.Vector2(0, 0);
  30616. };
  30617. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  30618. get: function () {
  30619. return this._collisionMask;
  30620. },
  30621. set: function (mask) {
  30622. this._collisionMask = !isNaN(mask) ? mask : -1;
  30623. },
  30624. enumerable: true,
  30625. configurable: true
  30626. });
  30627. FreeCamera.prototype._collideWithWorld = function (velocity) {
  30628. var globalPosition;
  30629. if (this.parent) {
  30630. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  30631. }
  30632. else {
  30633. globalPosition = this.position;
  30634. }
  30635. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  30636. if (!this._collider) {
  30637. this._collider = new BABYLON.Collider();
  30638. }
  30639. this._collider.radius = this.ellipsoid;
  30640. this._collider.collisionMask = this._collisionMask;
  30641. //no need for clone, as long as gravity is not on.
  30642. var actualVelocity = velocity;
  30643. //add gravity to the velocity to prevent the dual-collision checking
  30644. if (this.applyGravity) {
  30645. //this prevents mending with cameraDirection, a global variable of the free camera class.
  30646. actualVelocity = velocity.add(this.getScene().gravity);
  30647. }
  30648. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  30649. };
  30650. FreeCamera.prototype._checkInputs = function () {
  30651. if (!this._localDirection) {
  30652. this._localDirection = BABYLON.Vector3.Zero();
  30653. this._transformedDirection = BABYLON.Vector3.Zero();
  30654. }
  30655. this.inputs.checkInputs();
  30656. _super.prototype._checkInputs.call(this);
  30657. };
  30658. FreeCamera.prototype._decideIfNeedsToMove = function () {
  30659. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  30660. };
  30661. FreeCamera.prototype._updatePosition = function () {
  30662. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  30663. this._collideWithWorld(this.cameraDirection);
  30664. }
  30665. else {
  30666. _super.prototype._updatePosition.call(this);
  30667. }
  30668. };
  30669. FreeCamera.prototype.dispose = function () {
  30670. this.inputs.clear();
  30671. _super.prototype.dispose.call(this);
  30672. };
  30673. FreeCamera.prototype.getClassName = function () {
  30674. return "FreeCamera";
  30675. };
  30676. return FreeCamera;
  30677. }(BABYLON.TargetCamera));
  30678. __decorate([
  30679. BABYLON.serializeAsVector3()
  30680. ], FreeCamera.prototype, "ellipsoid", void 0);
  30681. __decorate([
  30682. BABYLON.serialize()
  30683. ], FreeCamera.prototype, "checkCollisions", void 0);
  30684. __decorate([
  30685. BABYLON.serialize()
  30686. ], FreeCamera.prototype, "applyGravity", void 0);
  30687. BABYLON.FreeCamera = FreeCamera;
  30688. })(BABYLON || (BABYLON = {}));
  30689. //# sourceMappingURL=babylon.freeCamera.js.map
  30690. var BABYLON;
  30691. (function (BABYLON) {
  30692. var ArcRotateCameraKeyboardMoveInput = (function () {
  30693. function ArcRotateCameraKeyboardMoveInput() {
  30694. this._keys = [];
  30695. this.keysUp = [38];
  30696. this.keysDown = [40];
  30697. this.keysLeft = [37];
  30698. this.keysRight = [39];
  30699. }
  30700. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  30701. var _this = this;
  30702. element.tabIndex = 1;
  30703. this._onKeyDown = function (evt) {
  30704. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30705. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30706. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30707. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30708. var index = _this._keys.indexOf(evt.keyCode);
  30709. if (index === -1) {
  30710. _this._keys.push(evt.keyCode);
  30711. }
  30712. if (evt.preventDefault) {
  30713. if (!noPreventDefault) {
  30714. evt.preventDefault();
  30715. }
  30716. }
  30717. }
  30718. };
  30719. this._onKeyUp = function (evt) {
  30720. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30721. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30722. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30723. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30724. var index = _this._keys.indexOf(evt.keyCode);
  30725. if (index >= 0) {
  30726. _this._keys.splice(index, 1);
  30727. }
  30728. if (evt.preventDefault) {
  30729. if (!noPreventDefault) {
  30730. evt.preventDefault();
  30731. }
  30732. }
  30733. }
  30734. };
  30735. this._onLostFocus = function () {
  30736. _this._keys = [];
  30737. };
  30738. element.addEventListener("keydown", this._onKeyDown, false);
  30739. element.addEventListener("keyup", this._onKeyUp, false);
  30740. BABYLON.Tools.RegisterTopRootEvents([
  30741. { name: "blur", handler: this._onLostFocus }
  30742. ]);
  30743. };
  30744. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  30745. if (element) {
  30746. element.removeEventListener("keydown", this._onKeyDown);
  30747. element.removeEventListener("keyup", this._onKeyUp);
  30748. }
  30749. BABYLON.Tools.UnregisterTopRootEvents([
  30750. { name: "blur", handler: this._onLostFocus }
  30751. ]);
  30752. this._keys = [];
  30753. this._onKeyDown = null;
  30754. this._onKeyUp = null;
  30755. this._onLostFocus = null;
  30756. };
  30757. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  30758. if (this._onKeyDown) {
  30759. var camera = this.camera;
  30760. for (var index = 0; index < this._keys.length; index++) {
  30761. var keyCode = this._keys[index];
  30762. if (this.keysLeft.indexOf(keyCode) !== -1) {
  30763. camera.inertialAlphaOffset -= 0.01;
  30764. }
  30765. else if (this.keysUp.indexOf(keyCode) !== -1) {
  30766. camera.inertialBetaOffset -= 0.01;
  30767. }
  30768. else if (this.keysRight.indexOf(keyCode) !== -1) {
  30769. camera.inertialAlphaOffset += 0.01;
  30770. }
  30771. else if (this.keysDown.indexOf(keyCode) !== -1) {
  30772. camera.inertialBetaOffset += 0.01;
  30773. }
  30774. }
  30775. }
  30776. };
  30777. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  30778. return "ArcRotateCameraKeyboardMoveInput";
  30779. };
  30780. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  30781. return "keyboard";
  30782. };
  30783. return ArcRotateCameraKeyboardMoveInput;
  30784. }());
  30785. __decorate([
  30786. BABYLON.serialize()
  30787. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  30788. __decorate([
  30789. BABYLON.serialize()
  30790. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  30791. __decorate([
  30792. BABYLON.serialize()
  30793. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  30794. __decorate([
  30795. BABYLON.serialize()
  30796. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  30797. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  30798. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  30799. })(BABYLON || (BABYLON = {}));
  30800. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  30801. var BABYLON;
  30802. (function (BABYLON) {
  30803. var ArcRotateCameraMouseWheelInput = (function () {
  30804. function ArcRotateCameraMouseWheelInput() {
  30805. this.wheelPrecision = 3.0;
  30806. }
  30807. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  30808. var _this = this;
  30809. this._wheel = function (p, s) {
  30810. //sanity check - this should be a PointerWheel event.
  30811. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  30812. return;
  30813. var event = p.event;
  30814. var delta = 0;
  30815. if (event.wheelDelta) {
  30816. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  30817. }
  30818. else if (event.detail) {
  30819. delta = -event.detail / _this.wheelPrecision;
  30820. }
  30821. if (delta)
  30822. _this.camera.inertialRadiusOffset += delta;
  30823. if (event.preventDefault) {
  30824. if (!noPreventDefault) {
  30825. event.preventDefault();
  30826. }
  30827. }
  30828. };
  30829. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  30830. };
  30831. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  30832. if (this._observer && element) {
  30833. this.camera.getScene().onPointerObservable.remove(this._observer);
  30834. this._observer = null;
  30835. this._wheel = null;
  30836. }
  30837. };
  30838. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  30839. return "ArcRotateCameraMouseWheelInput";
  30840. };
  30841. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  30842. return "mousewheel";
  30843. };
  30844. return ArcRotateCameraMouseWheelInput;
  30845. }());
  30846. __decorate([
  30847. BABYLON.serialize()
  30848. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  30849. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  30850. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  30851. })(BABYLON || (BABYLON = {}));
  30852. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  30853. var BABYLON;
  30854. (function (BABYLON) {
  30855. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  30856. var ArcRotateCameraPointersInput = (function () {
  30857. function ArcRotateCameraPointersInput() {
  30858. this.buttons = [0, 1, 2];
  30859. this.angularSensibilityX = 1000.0;
  30860. this.angularSensibilityY = 1000.0;
  30861. this.pinchPrecision = 6.0;
  30862. this.panningSensibility = 50.0;
  30863. this._isPanClick = false;
  30864. this.pinchInwards = true;
  30865. }
  30866. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  30867. var _this = this;
  30868. var engine = this.camera.getEngine();
  30869. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  30870. var pointA, pointB;
  30871. var previousPinchDistance = 0;
  30872. this._pointerInput = function (p, s) {
  30873. var evt = p.event;
  30874. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  30875. return;
  30876. }
  30877. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  30878. try {
  30879. evt.srcElement.setPointerCapture(evt.pointerId);
  30880. }
  30881. catch (e) {
  30882. //Nothing to do with the error. Execution will continue.
  30883. }
  30884. // Manage panning with pan button click
  30885. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  30886. // manage pointers
  30887. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  30888. if (pointA === undefined) {
  30889. pointA = cacheSoloPointer;
  30890. }
  30891. else if (pointB === undefined) {
  30892. pointB = cacheSoloPointer;
  30893. }
  30894. if (!noPreventDefault) {
  30895. evt.preventDefault();
  30896. element.focus();
  30897. }
  30898. }
  30899. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  30900. try {
  30901. evt.srcElement.releasePointerCapture(evt.pointerId);
  30902. }
  30903. catch (e) {
  30904. //Nothing to do with the error.
  30905. }
  30906. cacheSoloPointer = null;
  30907. previousPinchDistance = 0;
  30908. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  30909. //but emptying completly pointers collection is required to fix a bug on iPhone :
  30910. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  30911. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  30912. pointA = pointB = undefined;
  30913. if (!noPreventDefault) {
  30914. evt.preventDefault();
  30915. }
  30916. }
  30917. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  30918. if (!noPreventDefault) {
  30919. evt.preventDefault();
  30920. }
  30921. // One button down
  30922. if (pointA && pointB === undefined) {
  30923. if (_this.panningSensibility !== 0 &&
  30924. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  30925. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  30926. _this.camera
  30927. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  30928. _this.camera
  30929. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  30930. }
  30931. else {
  30932. var offsetX = evt.clientX - cacheSoloPointer.x;
  30933. var offsetY = evt.clientY - cacheSoloPointer.y;
  30934. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30935. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30936. }
  30937. cacheSoloPointer.x = evt.clientX;
  30938. cacheSoloPointer.y = evt.clientY;
  30939. }
  30940. else if (pointA && pointB) {
  30941. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  30942. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  30943. ed.x = evt.clientX;
  30944. ed.y = evt.clientY;
  30945. var direction = _this.pinchInwards ? 1 : -1;
  30946. var distX = pointA.x - pointB.x;
  30947. var distY = pointA.y - pointB.y;
  30948. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  30949. if (previousPinchDistance === 0) {
  30950. previousPinchDistance = pinchSquaredDistance;
  30951. return;
  30952. }
  30953. if (pinchSquaredDistance !== previousPinchDistance) {
  30954. _this.camera
  30955. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  30956. (_this.pinchPrecision *
  30957. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  30958. direction);
  30959. previousPinchDistance = pinchSquaredDistance;
  30960. }
  30961. }
  30962. }
  30963. };
  30964. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  30965. this._onContextMenu = function (evt) {
  30966. evt.preventDefault();
  30967. };
  30968. if (!this.camera._useCtrlForPanning) {
  30969. element.addEventListener("contextmenu", this._onContextMenu, false);
  30970. }
  30971. this._onLostFocus = function () {
  30972. //this._keys = [];
  30973. pointA = pointB = undefined;
  30974. previousPinchDistance = 0;
  30975. cacheSoloPointer = null;
  30976. };
  30977. this._onMouseMove = function (evt) {
  30978. if (!engine.isPointerLock) {
  30979. return;
  30980. }
  30981. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  30982. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  30983. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30984. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30985. if (!noPreventDefault) {
  30986. evt.preventDefault();
  30987. }
  30988. };
  30989. this._onGestureStart = function (e) {
  30990. if (window.MSGesture === undefined) {
  30991. return;
  30992. }
  30993. if (!_this._MSGestureHandler) {
  30994. _this._MSGestureHandler = new MSGesture();
  30995. _this._MSGestureHandler.target = element;
  30996. }
  30997. _this._MSGestureHandler.addPointer(e.pointerId);
  30998. };
  30999. this._onGesture = function (e) {
  31000. _this.camera.radius *= e.scale;
  31001. if (e.preventDefault) {
  31002. if (!noPreventDefault) {
  31003. e.stopPropagation();
  31004. e.preventDefault();
  31005. }
  31006. }
  31007. };
  31008. element.addEventListener("mousemove", this._onMouseMove, false);
  31009. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  31010. element.addEventListener("MSGestureChange", this._onGesture, false);
  31011. element.addEventListener("keydown", this._onKeyDown, false);
  31012. element.addEventListener("keyup", this._onKeyUp, false);
  31013. BABYLON.Tools.RegisterTopRootEvents([
  31014. { name: "blur", handler: this._onLostFocus }
  31015. ]);
  31016. };
  31017. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  31018. if (element && this._observer) {
  31019. this.camera.getScene().onPointerObservable.remove(this._observer);
  31020. this._observer = null;
  31021. element.removeEventListener("contextmenu", this._onContextMenu);
  31022. element.removeEventListener("mousemove", this._onMouseMove);
  31023. element.removeEventListener("MSPointerDown", this._onGestureStart);
  31024. element.removeEventListener("MSGestureChange", this._onGesture);
  31025. element.removeEventListener("keydown", this._onKeyDown);
  31026. element.removeEventListener("keyup", this._onKeyUp);
  31027. this._isPanClick = false;
  31028. this.pinchInwards = true;
  31029. this._onKeyDown = null;
  31030. this._onKeyUp = null;
  31031. this._onMouseMove = null;
  31032. this._onGestureStart = null;
  31033. this._onGesture = null;
  31034. this._MSGestureHandler = null;
  31035. this._onLostFocus = null;
  31036. this._onContextMenu = null;
  31037. }
  31038. BABYLON.Tools.UnregisterTopRootEvents([
  31039. { name: "blur", handler: this._onLostFocus }
  31040. ]);
  31041. };
  31042. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  31043. return "ArcRotateCameraPointersInput";
  31044. };
  31045. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  31046. return "pointers";
  31047. };
  31048. return ArcRotateCameraPointersInput;
  31049. }());
  31050. __decorate([
  31051. BABYLON.serialize()
  31052. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  31053. __decorate([
  31054. BABYLON.serialize()
  31055. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  31056. __decorate([
  31057. BABYLON.serialize()
  31058. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  31059. __decorate([
  31060. BABYLON.serialize()
  31061. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  31062. __decorate([
  31063. BABYLON.serialize()
  31064. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  31065. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  31066. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  31067. })(BABYLON || (BABYLON = {}));
  31068. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  31069. /// <reference path="babylon.targetCamera.ts" />
  31070. /// <reference path="..\Tools\babylon.tools.ts" />
  31071. var BABYLON;
  31072. (function (BABYLON) {
  31073. var ArcRotateCamera = (function (_super) {
  31074. __extends(ArcRotateCamera, _super);
  31075. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  31076. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  31077. _this.inertialAlphaOffset = 0;
  31078. _this.inertialBetaOffset = 0;
  31079. _this.inertialRadiusOffset = 0;
  31080. _this.lowerAlphaLimit = null;
  31081. _this.upperAlphaLimit = null;
  31082. _this.lowerBetaLimit = 0.01;
  31083. _this.upperBetaLimit = Math.PI;
  31084. _this.lowerRadiusLimit = null;
  31085. _this.upperRadiusLimit = null;
  31086. _this.inertialPanningX = 0;
  31087. _this.inertialPanningY = 0;
  31088. //-- end properties for backward compatibility for inputs
  31089. _this.zoomOnFactor = 1;
  31090. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  31091. _this.allowUpsideDown = true;
  31092. _this._viewMatrix = new BABYLON.Matrix();
  31093. // Panning
  31094. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  31095. _this.checkCollisions = false;
  31096. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  31097. _this._previousPosition = BABYLON.Vector3.Zero();
  31098. _this._collisionVelocity = BABYLON.Vector3.Zero();
  31099. _this._newPosition = BABYLON.Vector3.Zero();
  31100. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  31101. if (collidedMesh === void 0) { collidedMesh = null; }
  31102. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  31103. newPosition.multiplyInPlace(_this._collider.radius);
  31104. }
  31105. if (!collidedMesh) {
  31106. _this._previousPosition.copyFrom(_this.position);
  31107. }
  31108. else {
  31109. _this.setPosition(newPosition);
  31110. if (_this.onCollide) {
  31111. _this.onCollide(collidedMesh);
  31112. }
  31113. }
  31114. // Recompute because of constraints
  31115. var cosa = Math.cos(_this.alpha);
  31116. var sina = Math.sin(_this.alpha);
  31117. var cosb = Math.cos(_this.beta);
  31118. var sinb = Math.sin(_this.beta);
  31119. if (sinb === 0) {
  31120. sinb = 0.0001;
  31121. }
  31122. var target = _this._getTargetPosition();
  31123. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  31124. _this.position.copyFrom(_this._newPosition);
  31125. var up = _this.upVector;
  31126. if (_this.allowUpsideDown && _this.beta < 0) {
  31127. up = up.clone();
  31128. up = up.negate();
  31129. }
  31130. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  31131. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  31132. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  31133. _this._collisionTriggered = false;
  31134. };
  31135. _this._target = BABYLON.Vector3.Zero();
  31136. if (target) {
  31137. _this.setTarget(target);
  31138. }
  31139. _this.alpha = alpha;
  31140. _this.beta = beta;
  31141. _this.radius = radius;
  31142. _this.getViewMatrix();
  31143. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  31144. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  31145. return _this;
  31146. }
  31147. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  31148. get: function () {
  31149. return this._target;
  31150. },
  31151. set: function (value) {
  31152. this.setTarget(value);
  31153. },
  31154. enumerable: true,
  31155. configurable: true
  31156. });
  31157. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  31158. //-- begin properties for backward compatibility for inputs
  31159. get: function () {
  31160. var pointers = this.inputs.attached["pointers"];
  31161. if (pointers)
  31162. return pointers.angularSensibilityX;
  31163. },
  31164. set: function (value) {
  31165. var pointers = this.inputs.attached["pointers"];
  31166. if (pointers) {
  31167. pointers.angularSensibilityX = value;
  31168. }
  31169. },
  31170. enumerable: true,
  31171. configurable: true
  31172. });
  31173. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  31174. get: function () {
  31175. var pointers = this.inputs.attached["pointers"];
  31176. if (pointers)
  31177. return pointers.angularSensibilityY;
  31178. },
  31179. set: function (value) {
  31180. var pointers = this.inputs.attached["pointers"];
  31181. if (pointers) {
  31182. pointers.angularSensibilityY = value;
  31183. }
  31184. },
  31185. enumerable: true,
  31186. configurable: true
  31187. });
  31188. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  31189. get: function () {
  31190. var pointers = this.inputs.attached["pointers"];
  31191. if (pointers)
  31192. return pointers.pinchPrecision;
  31193. },
  31194. set: function (value) {
  31195. var pointers = this.inputs.attached["pointers"];
  31196. if (pointers) {
  31197. pointers.pinchPrecision = value;
  31198. }
  31199. },
  31200. enumerable: true,
  31201. configurable: true
  31202. });
  31203. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  31204. get: function () {
  31205. var pointers = this.inputs.attached["pointers"];
  31206. if (pointers)
  31207. return pointers.panningSensibility;
  31208. },
  31209. set: function (value) {
  31210. var pointers = this.inputs.attached["pointers"];
  31211. if (pointers) {
  31212. pointers.panningSensibility = value;
  31213. }
  31214. },
  31215. enumerable: true,
  31216. configurable: true
  31217. });
  31218. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  31219. get: function () {
  31220. var keyboard = this.inputs.attached["keyboard"];
  31221. if (keyboard)
  31222. return keyboard.keysUp;
  31223. },
  31224. set: function (value) {
  31225. var keyboard = this.inputs.attached["keyboard"];
  31226. if (keyboard)
  31227. keyboard.keysUp = value;
  31228. },
  31229. enumerable: true,
  31230. configurable: true
  31231. });
  31232. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  31233. get: function () {
  31234. var keyboard = this.inputs.attached["keyboard"];
  31235. if (keyboard)
  31236. return keyboard.keysDown;
  31237. },
  31238. set: function (value) {
  31239. var keyboard = this.inputs.attached["keyboard"];
  31240. if (keyboard)
  31241. keyboard.keysDown = value;
  31242. },
  31243. enumerable: true,
  31244. configurable: true
  31245. });
  31246. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  31247. get: function () {
  31248. var keyboard = this.inputs.attached["keyboard"];
  31249. if (keyboard)
  31250. return keyboard.keysLeft;
  31251. },
  31252. set: function (value) {
  31253. var keyboard = this.inputs.attached["keyboard"];
  31254. if (keyboard)
  31255. keyboard.keysLeft = value;
  31256. },
  31257. enumerable: true,
  31258. configurable: true
  31259. });
  31260. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  31261. get: function () {
  31262. var keyboard = this.inputs.attached["keyboard"];
  31263. if (keyboard)
  31264. return keyboard.keysRight;
  31265. },
  31266. set: function (value) {
  31267. var keyboard = this.inputs.attached["keyboard"];
  31268. if (keyboard)
  31269. keyboard.keysRight = value;
  31270. },
  31271. enumerable: true,
  31272. configurable: true
  31273. });
  31274. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  31275. get: function () {
  31276. var mousewheel = this.inputs.attached["mousewheel"];
  31277. if (mousewheel)
  31278. return mousewheel.wheelPrecision;
  31279. },
  31280. set: function (value) {
  31281. var mousewheel = this.inputs.attached["mousewheel"];
  31282. if (mousewheel)
  31283. mousewheel.wheelPrecision = value;
  31284. },
  31285. enumerable: true,
  31286. configurable: true
  31287. });
  31288. // Cache
  31289. ArcRotateCamera.prototype._initCache = function () {
  31290. _super.prototype._initCache.call(this);
  31291. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31292. this._cache.alpha = undefined;
  31293. this._cache.beta = undefined;
  31294. this._cache.radius = undefined;
  31295. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  31296. };
  31297. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  31298. if (!ignoreParentClass) {
  31299. _super.prototype._updateCache.call(this);
  31300. }
  31301. this._cache._target.copyFrom(this._getTargetPosition());
  31302. this._cache.alpha = this.alpha;
  31303. this._cache.beta = this.beta;
  31304. this._cache.radius = this.radius;
  31305. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  31306. };
  31307. ArcRotateCamera.prototype._getTargetPosition = function () {
  31308. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  31309. var pos = this._targetHost.getAbsolutePosition();
  31310. if (this._targetBoundingCenter) {
  31311. pos.addToRef(this._targetBoundingCenter, this._target);
  31312. }
  31313. else {
  31314. this._target.copyFrom(pos);
  31315. }
  31316. }
  31317. return this._target;
  31318. };
  31319. // Synchronized
  31320. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  31321. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  31322. return false;
  31323. return this._cache._target.equals(this._target)
  31324. && this._cache.alpha === this.alpha
  31325. && this._cache.beta === this.beta
  31326. && this._cache.radius === this.radius
  31327. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  31328. };
  31329. // Methods
  31330. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  31331. var _this = this;
  31332. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  31333. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  31334. this._useCtrlForPanning = useCtrlForPanning;
  31335. this._panningMouseButton = panningMouseButton;
  31336. this.inputs.attachElement(element, noPreventDefault);
  31337. this._reset = function () {
  31338. _this.inertialAlphaOffset = 0;
  31339. _this.inertialBetaOffset = 0;
  31340. _this.inertialRadiusOffset = 0;
  31341. };
  31342. };
  31343. ArcRotateCamera.prototype.detachControl = function (element) {
  31344. this.inputs.detachElement(element);
  31345. if (this._reset) {
  31346. this._reset();
  31347. }
  31348. };
  31349. ArcRotateCamera.prototype._checkInputs = function () {
  31350. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  31351. if (this._collisionTriggered) {
  31352. return;
  31353. }
  31354. this.inputs.checkInputs();
  31355. // Inertia
  31356. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  31357. if (this.getScene().useRightHandedSystem) {
  31358. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  31359. }
  31360. else {
  31361. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  31362. }
  31363. this.beta += this.inertialBetaOffset;
  31364. this.radius -= this.inertialRadiusOffset;
  31365. this.inertialAlphaOffset *= this.inertia;
  31366. this.inertialBetaOffset *= this.inertia;
  31367. this.inertialRadiusOffset *= this.inertia;
  31368. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  31369. this.inertialAlphaOffset = 0;
  31370. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  31371. this.inertialBetaOffset = 0;
  31372. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  31373. this.inertialRadiusOffset = 0;
  31374. }
  31375. // Panning inertia
  31376. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  31377. if (!this._localDirection) {
  31378. this._localDirection = BABYLON.Vector3.Zero();
  31379. this._transformedDirection = BABYLON.Vector3.Zero();
  31380. }
  31381. this.inertialPanningX *= this.inertia;
  31382. this.inertialPanningY *= this.inertia;
  31383. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  31384. this.inertialPanningX = 0;
  31385. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  31386. this.inertialPanningY = 0;
  31387. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  31388. this._localDirection.multiplyInPlace(this.panningAxis);
  31389. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  31390. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  31391. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  31392. if (!this.panningAxis.y) {
  31393. this._transformedDirection.y = 0;
  31394. }
  31395. if (!this._targetHost) {
  31396. this._target.addInPlace(this._transformedDirection);
  31397. }
  31398. }
  31399. // Limits
  31400. this._checkLimits();
  31401. _super.prototype._checkInputs.call(this);
  31402. };
  31403. ArcRotateCamera.prototype._checkLimits = function () {
  31404. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  31405. if (this.allowUpsideDown && this.beta > Math.PI) {
  31406. this.beta = this.beta - (2 * Math.PI);
  31407. }
  31408. }
  31409. else {
  31410. if (this.beta < this.lowerBetaLimit) {
  31411. this.beta = this.lowerBetaLimit;
  31412. }
  31413. }
  31414. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  31415. if (this.allowUpsideDown && this.beta < -Math.PI) {
  31416. this.beta = this.beta + (2 * Math.PI);
  31417. }
  31418. }
  31419. else {
  31420. if (this.beta > this.upperBetaLimit) {
  31421. this.beta = this.upperBetaLimit;
  31422. }
  31423. }
  31424. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  31425. this.alpha = this.lowerAlphaLimit;
  31426. }
  31427. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  31428. this.alpha = this.upperAlphaLimit;
  31429. }
  31430. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  31431. this.radius = this.lowerRadiusLimit;
  31432. }
  31433. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  31434. this.radius = this.upperRadiusLimit;
  31435. }
  31436. };
  31437. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  31438. var radiusv3 = this.position.subtract(this._getTargetPosition());
  31439. this.radius = radiusv3.length();
  31440. // Alpha
  31441. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  31442. if (radiusv3.z < 0) {
  31443. this.alpha = 2 * Math.PI - this.alpha;
  31444. }
  31445. // Beta
  31446. this.beta = Math.acos(radiusv3.y / this.radius);
  31447. this._checkLimits();
  31448. };
  31449. ArcRotateCamera.prototype.setPosition = function (position) {
  31450. if (this.position.equals(position)) {
  31451. return;
  31452. }
  31453. this.position.copyFrom(position);
  31454. this.rebuildAnglesAndRadius();
  31455. };
  31456. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  31457. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  31458. if (allowSamePosition === void 0) { allowSamePosition = false; }
  31459. if (target.getBoundingInfo) {
  31460. if (toBoundingCenter) {
  31461. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  31462. }
  31463. else {
  31464. this._targetBoundingCenter = null;
  31465. }
  31466. this._targetHost = target;
  31467. this._target = this._getTargetPosition();
  31468. }
  31469. else {
  31470. var newTarget = target;
  31471. var currentTarget = this._getTargetPosition();
  31472. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  31473. return;
  31474. }
  31475. this._target = newTarget;
  31476. this._targetBoundingCenter = null;
  31477. }
  31478. this.rebuildAnglesAndRadius();
  31479. };
  31480. ArcRotateCamera.prototype._getViewMatrix = function () {
  31481. // Compute
  31482. var cosa = Math.cos(this.alpha);
  31483. var sina = Math.sin(this.alpha);
  31484. var cosb = Math.cos(this.beta);
  31485. var sinb = Math.sin(this.beta);
  31486. if (sinb === 0) {
  31487. sinb = 0.0001;
  31488. }
  31489. var target = this._getTargetPosition();
  31490. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  31491. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  31492. if (!this._collider) {
  31493. this._collider = new BABYLON.Collider();
  31494. }
  31495. this._collider.radius = this.collisionRadius;
  31496. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  31497. this._collisionTriggered = true;
  31498. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  31499. }
  31500. else {
  31501. this.position.copyFrom(this._newPosition);
  31502. var up = this.upVector;
  31503. if (this.allowUpsideDown && sinb < 0) {
  31504. up = up.clone();
  31505. up = up.negate();
  31506. }
  31507. if (this.getScene().useRightHandedSystem) {
  31508. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  31509. }
  31510. else {
  31511. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  31512. }
  31513. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  31514. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  31515. }
  31516. this._currentTarget = target;
  31517. return this._viewMatrix;
  31518. };
  31519. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  31520. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  31521. meshes = meshes || this.getScene().meshes;
  31522. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  31523. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  31524. this.radius = distance * this.zoomOnFactor;
  31525. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  31526. };
  31527. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  31528. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  31529. var meshesOrMinMaxVector;
  31530. var distance;
  31531. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  31532. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  31533. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  31534. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  31535. }
  31536. else {
  31537. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  31538. distance = meshesOrMinMaxVectorAndDistance.distance;
  31539. }
  31540. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  31541. if (!doNotUpdateMaxZ) {
  31542. this.maxZ = distance * 2;
  31543. }
  31544. };
  31545. /**
  31546. * @override
  31547. * Override Camera.createRigCamera
  31548. */
  31549. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31550. var alphaShift;
  31551. switch (this.cameraRigMode) {
  31552. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31553. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31554. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31555. case BABYLON.Camera.RIG_MODE_VR:
  31556. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  31557. break;
  31558. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31559. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  31560. break;
  31561. }
  31562. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  31563. rigCam._cameraRigParams = {};
  31564. return rigCam;
  31565. };
  31566. /**
  31567. * @override
  31568. * Override Camera._updateRigCameras
  31569. */
  31570. ArcRotateCamera.prototype._updateRigCameras = function () {
  31571. var camLeft = this._rigCameras[0];
  31572. var camRight = this._rigCameras[1];
  31573. camLeft.beta = camRight.beta = this.beta;
  31574. camLeft.radius = camRight.radius = this.radius;
  31575. switch (this.cameraRigMode) {
  31576. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31577. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31578. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31579. case BABYLON.Camera.RIG_MODE_VR:
  31580. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  31581. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  31582. break;
  31583. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31584. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  31585. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  31586. break;
  31587. }
  31588. _super.prototype._updateRigCameras.call(this);
  31589. };
  31590. ArcRotateCamera.prototype.dispose = function () {
  31591. this.inputs.clear();
  31592. _super.prototype.dispose.call(this);
  31593. };
  31594. ArcRotateCamera.prototype.getClassName = function () {
  31595. return "ArcRotateCamera";
  31596. };
  31597. return ArcRotateCamera;
  31598. }(BABYLON.TargetCamera));
  31599. __decorate([
  31600. BABYLON.serialize()
  31601. ], ArcRotateCamera.prototype, "alpha", void 0);
  31602. __decorate([
  31603. BABYLON.serialize()
  31604. ], ArcRotateCamera.prototype, "beta", void 0);
  31605. __decorate([
  31606. BABYLON.serialize()
  31607. ], ArcRotateCamera.prototype, "radius", void 0);
  31608. __decorate([
  31609. BABYLON.serializeAsVector3("target")
  31610. ], ArcRotateCamera.prototype, "_target", void 0);
  31611. __decorate([
  31612. BABYLON.serialize()
  31613. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  31614. __decorate([
  31615. BABYLON.serialize()
  31616. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  31617. __decorate([
  31618. BABYLON.serialize()
  31619. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  31620. __decorate([
  31621. BABYLON.serialize()
  31622. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  31623. __decorate([
  31624. BABYLON.serialize()
  31625. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  31626. __decorate([
  31627. BABYLON.serialize()
  31628. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  31629. __decorate([
  31630. BABYLON.serialize()
  31631. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  31632. __decorate([
  31633. BABYLON.serialize()
  31634. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  31635. __decorate([
  31636. BABYLON.serialize()
  31637. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  31638. __decorate([
  31639. BABYLON.serialize()
  31640. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  31641. __decorate([
  31642. BABYLON.serialize()
  31643. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  31644. __decorate([
  31645. BABYLON.serialize()
  31646. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  31647. __decorate([
  31648. BABYLON.serialize()
  31649. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  31650. BABYLON.ArcRotateCamera = ArcRotateCamera;
  31651. })(BABYLON || (BABYLON = {}));
  31652. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  31653. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  31654. var BABYLON;
  31655. (function (BABYLON) {
  31656. var ArcRotateCameraInputsManager = (function (_super) {
  31657. __extends(ArcRotateCameraInputsManager, _super);
  31658. function ArcRotateCameraInputsManager(camera) {
  31659. return _super.call(this, camera) || this;
  31660. }
  31661. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  31662. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  31663. return this;
  31664. };
  31665. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  31666. this.add(new BABYLON.ArcRotateCameraPointersInput());
  31667. return this;
  31668. };
  31669. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  31670. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  31671. return this;
  31672. };
  31673. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  31674. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  31675. return this;
  31676. };
  31677. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  31678. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  31679. return this;
  31680. };
  31681. return ArcRotateCameraInputsManager;
  31682. }(BABYLON.CameraInputsManager));
  31683. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  31684. })(BABYLON || (BABYLON = {}));
  31685. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  31686. var BABYLON;
  31687. (function (BABYLON) {
  31688. var HemisphericLight = (function (_super) {
  31689. __extends(HemisphericLight, _super);
  31690. /**
  31691. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  31692. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  31693. * The HemisphericLight can't cast shadows.
  31694. * Documentation : http://doc.babylonjs.com/tutorials/lights
  31695. */
  31696. function HemisphericLight(name, direction, scene) {
  31697. var _this = _super.call(this, name, scene) || this;
  31698. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  31699. _this.direction = direction || BABYLON.Vector3.Up();
  31700. return _this;
  31701. }
  31702. HemisphericLight.prototype._buildUniformLayout = function () {
  31703. this._uniformBuffer.addUniform("vLightData", 4);
  31704. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  31705. this._uniformBuffer.addUniform("vLightSpecular", 3);
  31706. this._uniformBuffer.addUniform("vLightGround", 3);
  31707. this._uniformBuffer.addUniform("shadowsInfo", 3);
  31708. this._uniformBuffer.create();
  31709. };
  31710. /**
  31711. * Returns the string "HemisphericLight".
  31712. */
  31713. HemisphericLight.prototype.getClassName = function () {
  31714. return "HemisphericLight";
  31715. };
  31716. /**
  31717. * Sets the HemisphericLight direction towards the passed target (Vector3).
  31718. * Returns the updated direction.
  31719. */
  31720. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  31721. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  31722. return this.direction;
  31723. };
  31724. HemisphericLight.prototype.getShadowGenerator = function () {
  31725. return null;
  31726. };
  31727. /**
  31728. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  31729. * Returns the HemisphericLight.
  31730. */
  31731. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  31732. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  31733. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  31734. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  31735. return this;
  31736. };
  31737. HemisphericLight.prototype._getWorldMatrix = function () {
  31738. if (!this._worldMatrix) {
  31739. this._worldMatrix = BABYLON.Matrix.Identity();
  31740. }
  31741. return this._worldMatrix;
  31742. };
  31743. /**
  31744. * Returns the integer 3.
  31745. */
  31746. HemisphericLight.prototype.getTypeID = function () {
  31747. return 3;
  31748. };
  31749. return HemisphericLight;
  31750. }(BABYLON.Light));
  31751. __decorate([
  31752. BABYLON.serializeAsColor3()
  31753. ], HemisphericLight.prototype, "groundColor", void 0);
  31754. __decorate([
  31755. BABYLON.serializeAsVector3()
  31756. ], HemisphericLight.prototype, "direction", void 0);
  31757. BABYLON.HemisphericLight = HemisphericLight;
  31758. })(BABYLON || (BABYLON = {}));
  31759. //# sourceMappingURL=babylon.hemisphericLight.js.map
  31760. var BABYLON;
  31761. (function (BABYLON) {
  31762. var PointLight = (function (_super) {
  31763. __extends(PointLight, _super);
  31764. /**
  31765. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  31766. * A PointLight emits the light in every direction.
  31767. * It can cast shadows.
  31768. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  31769. * ```javascript
  31770. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  31771. * ```
  31772. * Documentation : http://doc.babylonjs.com/tutorials/lights
  31773. */
  31774. function PointLight(name, position, scene) {
  31775. var _this = _super.call(this, name, scene) || this;
  31776. _this.position = position;
  31777. return _this;
  31778. }
  31779. PointLight.prototype._buildUniformLayout = function () {
  31780. this._uniformBuffer.addUniform("vLightData", 4);
  31781. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  31782. this._uniformBuffer.addUniform("vLightSpecular", 3);
  31783. this._uniformBuffer.addUniform("shadowsInfo", 3);
  31784. this._uniformBuffer.create();
  31785. };
  31786. /**
  31787. * Returns the string "PointLight"
  31788. */
  31789. PointLight.prototype.getClassName = function () {
  31790. return "PointLight";
  31791. };
  31792. /**
  31793. * Returns a Vector3, the PointLight absolute position in the World.
  31794. */
  31795. PointLight.prototype.getAbsolutePosition = function () {
  31796. return this.transformedPosition ? this.transformedPosition : this.position;
  31797. };
  31798. /**
  31799. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  31800. */
  31801. PointLight.prototype.computeTransformedPosition = function () {
  31802. if (this.parent && this.parent.getWorldMatrix) {
  31803. if (!this.transformedPosition) {
  31804. this.transformedPosition = BABYLON.Vector3.Zero();
  31805. }
  31806. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  31807. return true;
  31808. }
  31809. return false;
  31810. };
  31811. /**
  31812. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  31813. * Returns the PointLight.
  31814. */
  31815. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  31816. if (this.parent && this.parent.getWorldMatrix) {
  31817. this.computeTransformedPosition();
  31818. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  31819. return this;
  31820. }
  31821. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  31822. return this;
  31823. };
  31824. /**
  31825. * Boolean : returns true by default.
  31826. */
  31827. PointLight.prototype.needCube = function () {
  31828. return true;
  31829. };
  31830. /**
  31831. * Boolean : returns false by default.
  31832. */
  31833. PointLight.prototype.needRefreshPerFrame = function () {
  31834. return false;
  31835. };
  31836. /**
  31837. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  31838. */
  31839. PointLight.prototype.getShadowDirection = function (faceIndex) {
  31840. switch (faceIndex) {
  31841. case 0:
  31842. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  31843. case 1:
  31844. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  31845. case 2:
  31846. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  31847. case 3:
  31848. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  31849. case 4:
  31850. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  31851. case 5:
  31852. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  31853. }
  31854. return BABYLON.Vector3.Zero();
  31855. };
  31856. /**
  31857. * Return the depth scale used for the shadow map.
  31858. */
  31859. PointLight.prototype.getDepthScale = function () {
  31860. return 30.0;
  31861. };
  31862. /**
  31863. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  31864. * - fov = PI / 2
  31865. * - aspect ratio : 1.0
  31866. * - z-near and far equal to the active camera minZ and maxZ.
  31867. * Returns the PointLight.
  31868. */
  31869. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  31870. if (this.customProjectionMatrixBuilder) {
  31871. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  31872. }
  31873. else {
  31874. var activeCamera = this.getScene().activeCamera;
  31875. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  31876. }
  31877. return this;
  31878. };
  31879. PointLight.prototype._getWorldMatrix = function () {
  31880. if (!this._worldMatrix) {
  31881. this._worldMatrix = BABYLON.Matrix.Identity();
  31882. }
  31883. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  31884. return this._worldMatrix;
  31885. };
  31886. /**
  31887. * Returns the integer 0.
  31888. */
  31889. PointLight.prototype.getTypeID = function () {
  31890. return 0;
  31891. };
  31892. return PointLight;
  31893. }(BABYLON.Light));
  31894. __decorate([
  31895. BABYLON.serializeAsVector3()
  31896. ], PointLight.prototype, "position", void 0);
  31897. __decorate([
  31898. BABYLON.serialize()
  31899. ], PointLight.prototype, "shadowMinZ", void 0);
  31900. __decorate([
  31901. BABYLON.serialize()
  31902. ], PointLight.prototype, "shadowMaxZ", void 0);
  31903. BABYLON.PointLight = PointLight;
  31904. })(BABYLON || (BABYLON = {}));
  31905. //# sourceMappingURL=babylon.pointLight.js.map
  31906. /// <reference path="babylon.light.ts" />
  31907. var BABYLON;
  31908. (function (BABYLON) {
  31909. var DirectionalLight = (function (_super) {
  31910. __extends(DirectionalLight, _super);
  31911. /**
  31912. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  31913. * The directional light is emitted from everywhere in the given direction.
  31914. * It can cast shawdows.
  31915. * Documentation : http://doc.babylonjs.com/tutorials/lights
  31916. */
  31917. function DirectionalLight(name, direction, scene) {
  31918. var _this = _super.call(this, name, scene) || this;
  31919. _this.shadowOrthoScale = 0.5;
  31920. _this.autoUpdateExtends = true;
  31921. // Cache
  31922. _this._orthoLeft = Number.MAX_VALUE;
  31923. _this._orthoRight = Number.MIN_VALUE;
  31924. _this._orthoTop = Number.MIN_VALUE;
  31925. _this._orthoBottom = Number.MAX_VALUE;
  31926. _this.position = direction.scale(-1.0);
  31927. _this.direction = direction;
  31928. return _this;
  31929. }
  31930. DirectionalLight.prototype._buildUniformLayout = function () {
  31931. this._uniformBuffer.addUniform("vLightData", 4);
  31932. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  31933. this._uniformBuffer.addUniform("vLightSpecular", 3);
  31934. this._uniformBuffer.addUniform("shadowsInfo", 3);
  31935. this._uniformBuffer.create();
  31936. };
  31937. /**
  31938. * Returns the string "DirectionalLight".
  31939. */
  31940. DirectionalLight.prototype.getClassName = function () {
  31941. return "DirectionalLight";
  31942. };
  31943. /**
  31944. * Returns the DirectionalLight absolute position in the World.
  31945. */
  31946. DirectionalLight.prototype.getAbsolutePosition = function () {
  31947. return this.transformedPosition ? this.transformedPosition : this.position;
  31948. };
  31949. /**
  31950. * Sets the DirectionalLight direction toward the passed target (Vector3).
  31951. * Returns the updated DirectionalLight direction (Vector3).
  31952. */
  31953. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  31954. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  31955. return this.direction;
  31956. };
  31957. /**
  31958. * Return the depth scale used for the shadow map.
  31959. */
  31960. DirectionalLight.prototype.getDepthScale = function () {
  31961. return 30.0;
  31962. };
  31963. /**
  31964. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  31965. * Returns the DirectionalLight.
  31966. */
  31967. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  31968. if (this.customProjectionMatrixBuilder) {
  31969. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  31970. }
  31971. else {
  31972. var activeCamera = this.getScene().activeCamera;
  31973. // Check extends
  31974. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  31975. var tempVector3 = BABYLON.Vector3.Zero();
  31976. this._orthoLeft = Number.MAX_VALUE;
  31977. this._orthoRight = Number.MIN_VALUE;
  31978. this._orthoTop = Number.MIN_VALUE;
  31979. this._orthoBottom = Number.MAX_VALUE;
  31980. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  31981. var mesh = renderList[meshIndex];
  31982. if (!mesh) {
  31983. continue;
  31984. }
  31985. var boundingInfo = mesh.getBoundingInfo();
  31986. if (!boundingInfo) {
  31987. continue;
  31988. }
  31989. var boundingBox = boundingInfo.boundingBox;
  31990. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  31991. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  31992. if (tempVector3.x < this._orthoLeft)
  31993. this._orthoLeft = tempVector3.x;
  31994. if (tempVector3.y < this._orthoBottom)
  31995. this._orthoBottom = tempVector3.y;
  31996. if (tempVector3.x > this._orthoRight)
  31997. this._orthoRight = tempVector3.x;
  31998. if (tempVector3.y > this._orthoTop)
  31999. this._orthoTop = tempVector3.y;
  32000. }
  32001. }
  32002. }
  32003. var xOffset = this._orthoRight - this._orthoLeft;
  32004. var yOffset = this._orthoTop - this._orthoBottom;
  32005. 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);
  32006. }
  32007. return this;
  32008. };
  32009. /**
  32010. * Boolean : true by default.
  32011. */
  32012. DirectionalLight.prototype.needRefreshPerFrame = function () {
  32013. return true;
  32014. };
  32015. /**
  32016. * Boolean : false by default.
  32017. */
  32018. DirectionalLight.prototype.needCube = function () {
  32019. return false;
  32020. };
  32021. /**
  32022. * Returns the light direction (Vector3) for any passed face index.
  32023. */
  32024. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  32025. return this.direction;
  32026. };
  32027. /**
  32028. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  32029. */
  32030. DirectionalLight.prototype.computeTransformedPosition = function () {
  32031. if (this.parent && this.parent.getWorldMatrix) {
  32032. if (!this.transformedPosition) {
  32033. this.transformedPosition = BABYLON.Vector3.Zero();
  32034. }
  32035. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  32036. return true;
  32037. }
  32038. return false;
  32039. };
  32040. /**
  32041. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  32042. * Returns the DirectionalLight.
  32043. */
  32044. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  32045. if (this.parent && this.parent.getWorldMatrix) {
  32046. if (!this._transformedDirection) {
  32047. this._transformedDirection = BABYLON.Vector3.Zero();
  32048. }
  32049. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  32050. this._uniformBuffer.updateFloat4("vLightData", this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1, lightIndex);
  32051. return this;
  32052. }
  32053. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  32054. return this;
  32055. };
  32056. DirectionalLight.prototype._getWorldMatrix = function () {
  32057. if (!this._worldMatrix) {
  32058. this._worldMatrix = BABYLON.Matrix.Identity();
  32059. }
  32060. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  32061. return this._worldMatrix;
  32062. };
  32063. /**
  32064. * Returns the integer 1.
  32065. */
  32066. DirectionalLight.prototype.getTypeID = function () {
  32067. return 1;
  32068. };
  32069. return DirectionalLight;
  32070. }(BABYLON.Light));
  32071. __decorate([
  32072. BABYLON.serializeAsVector3()
  32073. ], DirectionalLight.prototype, "position", void 0);
  32074. __decorate([
  32075. BABYLON.serializeAsVector3()
  32076. ], DirectionalLight.prototype, "direction", void 0);
  32077. __decorate([
  32078. BABYLON.serialize()
  32079. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  32080. __decorate([
  32081. BABYLON.serialize()
  32082. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  32083. __decorate([
  32084. BABYLON.serialize()
  32085. ], DirectionalLight.prototype, "shadowMinZ", void 0);
  32086. __decorate([
  32087. BABYLON.serialize()
  32088. ], DirectionalLight.prototype, "shadowMaxZ", void 0);
  32089. BABYLON.DirectionalLight = DirectionalLight;
  32090. })(BABYLON || (BABYLON = {}));
  32091. //# sourceMappingURL=babylon.directionalLight.js.map
  32092. var BABYLON;
  32093. (function (BABYLON) {
  32094. var SpotLight = (function (_super) {
  32095. __extends(SpotLight, _super);
  32096. /**
  32097. * Creates a SpotLight object in the scene with the passed parameters :
  32098. * - `position` (Vector3) is the initial SpotLight position,
  32099. * - `direction` (Vector3) is the initial SpotLight direction,
  32100. * - `angle` (float, in radians) is the spot light cone angle,
  32101. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  32102. * A spot light is a simply light oriented cone.
  32103. * It can cast shadows.
  32104. * Documentation : http://doc.babylonjs.com/tutorials/lights
  32105. */
  32106. function SpotLight(name, position, direction, angle, exponent, scene) {
  32107. var _this = _super.call(this, name, scene) || this;
  32108. _this.position = position;
  32109. _this.direction = direction;
  32110. _this.angle = angle;
  32111. _this.exponent = exponent;
  32112. return _this;
  32113. }
  32114. SpotLight.prototype._buildUniformLayout = function () {
  32115. this._uniformBuffer.addUniform("vLightData", 4);
  32116. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  32117. this._uniformBuffer.addUniform("vLightSpecular", 3);
  32118. this._uniformBuffer.addUniform("vLightDirection", 3);
  32119. this._uniformBuffer.addUniform("shadowsInfo", 3);
  32120. this._uniformBuffer.create();
  32121. };
  32122. /**
  32123. * Returns the string "SpotLight".
  32124. */
  32125. SpotLight.prototype.getClassName = function () {
  32126. return "SpotLight";
  32127. };
  32128. /**
  32129. * Returns the SpotLight absolute position in the World (Vector3).
  32130. */
  32131. SpotLight.prototype.getAbsolutePosition = function () {
  32132. return this.transformedPosition ? this.transformedPosition : this.position;
  32133. };
  32134. /**
  32135. * Return the depth scale used for the shadow map.
  32136. */
  32137. SpotLight.prototype.getDepthScale = function () {
  32138. return 30.0;
  32139. };
  32140. /**
  32141. * 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.
  32142. * Returns the SpotLight.
  32143. */
  32144. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  32145. if (this.customProjectionMatrixBuilder) {
  32146. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  32147. }
  32148. else {
  32149. var activeCamera = this.getScene().activeCamera;
  32150. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  32151. }
  32152. return this;
  32153. };
  32154. /**
  32155. * Boolean : false by default.
  32156. */
  32157. SpotLight.prototype.needCube = function () {
  32158. return false;
  32159. };
  32160. /**
  32161. * Boolean : false by default.
  32162. */
  32163. SpotLight.prototype.needRefreshPerFrame = function () {
  32164. return false;
  32165. };
  32166. /**
  32167. * Returns the SpotLight direction (Vector3) for any passed face index.
  32168. */
  32169. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  32170. return this.direction;
  32171. };
  32172. /**
  32173. * Updates the SpotLight direction towards the passed target (Vector3).
  32174. * Returns the updated direction.
  32175. */
  32176. SpotLight.prototype.setDirectionToTarget = function (target) {
  32177. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  32178. return this.direction;
  32179. };
  32180. /**
  32181. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  32182. */
  32183. SpotLight.prototype.computeTransformedPosition = function () {
  32184. if (this.parent && this.parent.getWorldMatrix) {
  32185. if (!this.transformedPosition) {
  32186. this.transformedPosition = BABYLON.Vector3.Zero();
  32187. }
  32188. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  32189. return true;
  32190. }
  32191. return false;
  32192. };
  32193. /**
  32194. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  32195. * Return the SpotLight.
  32196. */
  32197. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  32198. var normalizeDirection;
  32199. if (this.parent && this.parent.getWorldMatrix) {
  32200. if (!this._transformedDirection) {
  32201. this._transformedDirection = BABYLON.Vector3.Zero();
  32202. }
  32203. this.computeTransformedPosition();
  32204. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  32205. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  32206. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  32207. }
  32208. else {
  32209. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  32210. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  32211. }
  32212. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  32213. return this;
  32214. };
  32215. SpotLight.prototype._getWorldMatrix = function () {
  32216. if (!this._worldMatrix) {
  32217. this._worldMatrix = BABYLON.Matrix.Identity();
  32218. }
  32219. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  32220. return this._worldMatrix;
  32221. };
  32222. /**
  32223. * Returns the integer 2.
  32224. */
  32225. SpotLight.prototype.getTypeID = function () {
  32226. return 2;
  32227. };
  32228. /**
  32229. * Returns the SpotLight rotation (Vector3).
  32230. */
  32231. SpotLight.prototype.getRotation = function () {
  32232. this.direction.normalize();
  32233. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  32234. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  32235. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  32236. };
  32237. return SpotLight;
  32238. }(BABYLON.Light));
  32239. __decorate([
  32240. BABYLON.serializeAsVector3()
  32241. ], SpotLight.prototype, "position", void 0);
  32242. __decorate([
  32243. BABYLON.serializeAsVector3()
  32244. ], SpotLight.prototype, "direction", void 0);
  32245. __decorate([
  32246. BABYLON.serialize()
  32247. ], SpotLight.prototype, "angle", void 0);
  32248. __decorate([
  32249. BABYLON.serialize()
  32250. ], SpotLight.prototype, "exponent", void 0);
  32251. __decorate([
  32252. BABYLON.serialize()
  32253. ], SpotLight.prototype, "shadowMinZ", void 0);
  32254. __decorate([
  32255. BABYLON.serialize()
  32256. ], SpotLight.prototype, "shadowMaxZ", void 0);
  32257. BABYLON.SpotLight = SpotLight;
  32258. })(BABYLON || (BABYLON = {}));
  32259. //# sourceMappingURL=babylon.spotLight.js.map
  32260. var BABYLON;
  32261. (function (BABYLON) {
  32262. var AnimationRange = (function () {
  32263. function AnimationRange(name, from, to) {
  32264. this.name = name;
  32265. this.from = from;
  32266. this.to = to;
  32267. }
  32268. AnimationRange.prototype.clone = function () {
  32269. return new AnimationRange(this.name, this.from, this.to);
  32270. };
  32271. return AnimationRange;
  32272. }());
  32273. BABYLON.AnimationRange = AnimationRange;
  32274. /**
  32275. * Composed of a frame, and an action function
  32276. */
  32277. var AnimationEvent = (function () {
  32278. function AnimationEvent(frame, action, onlyOnce) {
  32279. this.frame = frame;
  32280. this.action = action;
  32281. this.onlyOnce = onlyOnce;
  32282. this.isDone = false;
  32283. }
  32284. return AnimationEvent;
  32285. }());
  32286. BABYLON.AnimationEvent = AnimationEvent;
  32287. var PathCursor = (function () {
  32288. function PathCursor(path) {
  32289. this.path = path;
  32290. this._onchange = new Array();
  32291. this.value = 0;
  32292. this.animations = new Array();
  32293. }
  32294. PathCursor.prototype.getPoint = function () {
  32295. var point = this.path.getPointAtLengthPosition(this.value);
  32296. return new BABYLON.Vector3(point.x, 0, point.y);
  32297. };
  32298. PathCursor.prototype.moveAhead = function (step) {
  32299. if (step === void 0) { step = 0.002; }
  32300. this.move(step);
  32301. return this;
  32302. };
  32303. PathCursor.prototype.moveBack = function (step) {
  32304. if (step === void 0) { step = 0.002; }
  32305. this.move(-step);
  32306. return this;
  32307. };
  32308. PathCursor.prototype.move = function (step) {
  32309. if (Math.abs(step) > 1) {
  32310. throw "step size should be less than 1.";
  32311. }
  32312. this.value += step;
  32313. this.ensureLimits();
  32314. this.raiseOnChange();
  32315. return this;
  32316. };
  32317. PathCursor.prototype.ensureLimits = function () {
  32318. while (this.value > 1) {
  32319. this.value -= 1;
  32320. }
  32321. while (this.value < 0) {
  32322. this.value += 1;
  32323. }
  32324. return this;
  32325. };
  32326. // used by animation engine
  32327. PathCursor.prototype.markAsDirty = function (propertyName) {
  32328. this.ensureLimits();
  32329. this.raiseOnChange();
  32330. return this;
  32331. };
  32332. PathCursor.prototype.raiseOnChange = function () {
  32333. var _this = this;
  32334. this._onchange.forEach(function (f) { return f(_this); });
  32335. return this;
  32336. };
  32337. PathCursor.prototype.onchange = function (f) {
  32338. this._onchange.push(f);
  32339. return this;
  32340. };
  32341. return PathCursor;
  32342. }());
  32343. BABYLON.PathCursor = PathCursor;
  32344. var Animation = (function () {
  32345. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  32346. this.name = name;
  32347. this.targetProperty = targetProperty;
  32348. this.framePerSecond = framePerSecond;
  32349. this.dataType = dataType;
  32350. this.loopMode = loopMode;
  32351. this.enableBlending = enableBlending;
  32352. this._offsetsCache = {};
  32353. this._highLimitsCache = {};
  32354. this._stopped = false;
  32355. this._blendingFactor = 0;
  32356. // The set of event that will be linked to this animation
  32357. this._events = new Array();
  32358. this.allowMatricesInterpolation = false;
  32359. this.blendingSpeed = 0.01;
  32360. this._ranges = {};
  32361. this.targetPropertyPath = targetProperty.split(".");
  32362. this.dataType = dataType;
  32363. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  32364. }
  32365. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  32366. var dataType = undefined;
  32367. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  32368. dataType = Animation.ANIMATIONTYPE_FLOAT;
  32369. }
  32370. else if (from instanceof BABYLON.Quaternion) {
  32371. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  32372. }
  32373. else if (from instanceof BABYLON.Vector3) {
  32374. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  32375. }
  32376. else if (from instanceof BABYLON.Vector2) {
  32377. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  32378. }
  32379. else if (from instanceof BABYLON.Color3) {
  32380. dataType = Animation.ANIMATIONTYPE_COLOR3;
  32381. }
  32382. else if (from instanceof BABYLON.Size) {
  32383. dataType = Animation.ANIMATIONTYPE_SIZE;
  32384. }
  32385. if (dataType == undefined) {
  32386. return null;
  32387. }
  32388. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  32389. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  32390. animation.setKeys(keys);
  32391. if (easingFunction !== undefined) {
  32392. animation.setEasingFunction(easingFunction);
  32393. }
  32394. return animation;
  32395. };
  32396. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32397. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32398. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32399. };
  32400. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32401. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32402. node.animations.push(animation);
  32403. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32404. };
  32405. // Methods
  32406. /**
  32407. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  32408. */
  32409. Animation.prototype.toString = function (fullDetails) {
  32410. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  32411. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  32412. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  32413. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  32414. if (fullDetails) {
  32415. ret += ", Ranges: {";
  32416. var first = true;
  32417. for (var name in this._ranges) {
  32418. if (first) {
  32419. ret += ", ";
  32420. first = false;
  32421. }
  32422. ret += name;
  32423. }
  32424. ret += "}";
  32425. }
  32426. return ret;
  32427. };
  32428. /**
  32429. * Add an event to this animation.
  32430. */
  32431. Animation.prototype.addEvent = function (event) {
  32432. this._events.push(event);
  32433. };
  32434. /**
  32435. * Remove all events found at the given frame
  32436. * @param frame
  32437. */
  32438. Animation.prototype.removeEvents = function (frame) {
  32439. for (var index = 0; index < this._events.length; index++) {
  32440. if (this._events[index].frame === frame) {
  32441. this._events.splice(index, 1);
  32442. index--;
  32443. }
  32444. }
  32445. };
  32446. Animation.prototype.createRange = function (name, from, to) {
  32447. // check name not already in use; could happen for bones after serialized
  32448. if (!this._ranges[name]) {
  32449. this._ranges[name] = new AnimationRange(name, from, to);
  32450. }
  32451. };
  32452. Animation.prototype.deleteRange = function (name, deleteFrames) {
  32453. if (deleteFrames === void 0) { deleteFrames = true; }
  32454. if (this._ranges[name]) {
  32455. if (deleteFrames) {
  32456. var from = this._ranges[name].from;
  32457. var to = this._ranges[name].to;
  32458. // this loop MUST go high to low for multiple splices to work
  32459. for (var key = this._keys.length - 1; key >= 0; key--) {
  32460. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  32461. this._keys.splice(key, 1);
  32462. }
  32463. }
  32464. }
  32465. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  32466. }
  32467. };
  32468. Animation.prototype.getRange = function (name) {
  32469. return this._ranges[name];
  32470. };
  32471. Animation.prototype.reset = function () {
  32472. this._offsetsCache = {};
  32473. this._highLimitsCache = {};
  32474. this.currentFrame = 0;
  32475. this._blendingFactor = 0;
  32476. this._originalBlendValue = null;
  32477. };
  32478. Animation.prototype.isStopped = function () {
  32479. return this._stopped;
  32480. };
  32481. Animation.prototype.getKeys = function () {
  32482. return this._keys;
  32483. };
  32484. Animation.prototype.getHighestFrame = function () {
  32485. var ret = 0;
  32486. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  32487. if (ret < this._keys[key].frame) {
  32488. ret = this._keys[key].frame;
  32489. }
  32490. }
  32491. return ret;
  32492. };
  32493. Animation.prototype.getEasingFunction = function () {
  32494. return this._easingFunction;
  32495. };
  32496. Animation.prototype.setEasingFunction = function (easingFunction) {
  32497. this._easingFunction = easingFunction;
  32498. };
  32499. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  32500. return startValue + (endValue - startValue) * gradient;
  32501. };
  32502. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  32503. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  32504. };
  32505. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  32506. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  32507. };
  32508. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  32509. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  32510. };
  32511. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  32512. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  32513. };
  32514. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  32515. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  32516. };
  32517. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  32518. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  32519. };
  32520. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  32521. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  32522. };
  32523. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  32524. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  32525. };
  32526. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  32527. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  32528. };
  32529. Animation.prototype.clone = function () {
  32530. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  32531. clone.enableBlending = this.enableBlending;
  32532. clone.blendingSpeed = this.blendingSpeed;
  32533. if (this._keys) {
  32534. clone.setKeys(this._keys);
  32535. }
  32536. if (this._ranges) {
  32537. clone._ranges = {};
  32538. for (var name in this._ranges) {
  32539. clone._ranges[name] = this._ranges[name].clone();
  32540. }
  32541. }
  32542. return clone;
  32543. };
  32544. Animation.prototype.setKeys = function (values) {
  32545. this._keys = values.slice(0);
  32546. this._offsetsCache = {};
  32547. this._highLimitsCache = {};
  32548. };
  32549. Animation.prototype._getKeyValue = function (value) {
  32550. if (typeof value === "function") {
  32551. return value();
  32552. }
  32553. return value;
  32554. };
  32555. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  32556. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  32557. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  32558. }
  32559. this.currentFrame = currentFrame;
  32560. // Try to get a hash to find the right key
  32561. 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));
  32562. if (this._keys[startKeyIndex].frame >= currentFrame) {
  32563. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  32564. startKeyIndex--;
  32565. }
  32566. }
  32567. for (var key = startKeyIndex; key < this._keys.length; key++) {
  32568. var endKey = this._keys[key + 1];
  32569. if (endKey.frame >= currentFrame) {
  32570. var startKey = this._keys[key];
  32571. var startValue = this._getKeyValue(startKey.value);
  32572. var endValue = this._getKeyValue(endKey.value);
  32573. var useTangent = startKey.outTangent && endKey.inTangent;
  32574. // gradient : percent of currentFrame between the frame inf and the frame sup
  32575. var gradient = (currentFrame - startKey.frame) / (endKey.frame - startKey.frame);
  32576. // check for easingFunction and correction of gradient
  32577. if (this._easingFunction != null) {
  32578. gradient = this._easingFunction.ease(gradient);
  32579. }
  32580. switch (this.dataType) {
  32581. // Float
  32582. case Animation.ANIMATIONTYPE_FLOAT:
  32583. switch (loopMode) {
  32584. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32585. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32586. return this.floatInterpolateFunction(startValue, endValue, gradient);
  32587. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32588. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  32589. }
  32590. break;
  32591. // Quaternion
  32592. case Animation.ANIMATIONTYPE_QUATERNION:
  32593. var quaternion = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent, endValue, endKey.inTangent, gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  32594. switch (loopMode) {
  32595. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32596. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32597. return quaternion;
  32598. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32599. return quaternion.add(offsetValue.scale(repeatCount));
  32600. }
  32601. return quaternion;
  32602. // Vector3
  32603. case Animation.ANIMATIONTYPE_VECTOR3:
  32604. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent, endValue, endKey.inTangent, gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  32605. switch (loopMode) {
  32606. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32607. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32608. return vec3Value;
  32609. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32610. return vec3Value.add(offsetValue.scale(repeatCount));
  32611. }
  32612. // Vector2
  32613. case Animation.ANIMATIONTYPE_VECTOR2:
  32614. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent, endValue, endKey.inTangent, gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  32615. switch (loopMode) {
  32616. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32617. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32618. return vec2Value;
  32619. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32620. return vec2Value.add(offsetValue.scale(repeatCount));
  32621. }
  32622. // Size
  32623. case Animation.ANIMATIONTYPE_SIZE:
  32624. switch (loopMode) {
  32625. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32626. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32627. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  32628. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32629. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32630. }
  32631. // Color3
  32632. case Animation.ANIMATIONTYPE_COLOR3:
  32633. switch (loopMode) {
  32634. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32635. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32636. return this.color3InterpolateFunction(startValue, endValue, gradient);
  32637. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32638. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32639. }
  32640. // Matrix
  32641. case Animation.ANIMATIONTYPE_MATRIX:
  32642. switch (loopMode) {
  32643. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32644. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32645. if (this.allowMatricesInterpolation) {
  32646. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  32647. }
  32648. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32649. return startValue;
  32650. }
  32651. default:
  32652. break;
  32653. }
  32654. break;
  32655. }
  32656. }
  32657. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  32658. };
  32659. Animation.prototype.setValue = function (currentValue, blend) {
  32660. if (blend === void 0) { blend = false; }
  32661. // Set value
  32662. var path;
  32663. var destination;
  32664. if (this.targetPropertyPath.length > 1) {
  32665. var property = this._target[this.targetPropertyPath[0]];
  32666. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  32667. property = property[this.targetPropertyPath[index]];
  32668. }
  32669. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  32670. destination = property;
  32671. }
  32672. else {
  32673. path = this.targetPropertyPath[0];
  32674. destination = this._target;
  32675. }
  32676. // Blending
  32677. if (this.enableBlending && this._blendingFactor <= 1.0) {
  32678. if (!this._originalBlendValue) {
  32679. if (destination[path].clone) {
  32680. this._originalBlendValue = destination[path].clone();
  32681. }
  32682. else {
  32683. this._originalBlendValue = destination[path];
  32684. }
  32685. }
  32686. if (this._originalBlendValue.prototype) {
  32687. if (this._originalBlendValue.prototype.Lerp) {
  32688. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  32689. }
  32690. else {
  32691. destination[path] = currentValue;
  32692. }
  32693. }
  32694. else if (this._originalBlendValue.m) {
  32695. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  32696. }
  32697. else {
  32698. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  32699. }
  32700. this._blendingFactor += this.blendingSpeed;
  32701. }
  32702. else {
  32703. destination[path] = currentValue;
  32704. }
  32705. if (this._target.markAsDirty) {
  32706. this._target.markAsDirty(this.targetProperty);
  32707. }
  32708. };
  32709. Animation.prototype.goToFrame = function (frame) {
  32710. if (frame < this._keys[0].frame) {
  32711. frame = this._keys[0].frame;
  32712. }
  32713. else if (frame > this._keys[this._keys.length - 1].frame) {
  32714. frame = this._keys[this._keys.length - 1].frame;
  32715. }
  32716. var currentValue = this._interpolate(frame, 0, this.loopMode);
  32717. this.setValue(currentValue);
  32718. };
  32719. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  32720. if (blend === void 0) { blend = false; }
  32721. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  32722. this._stopped = true;
  32723. return false;
  32724. }
  32725. var returnValue = true;
  32726. // Adding a start key at frame 0 if missing
  32727. if (this._keys[0].frame !== 0) {
  32728. var newKey = { frame: 0, value: this._keys[0].value };
  32729. this._keys.splice(0, 0, newKey);
  32730. }
  32731. // Check limits
  32732. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  32733. from = this._keys[0].frame;
  32734. }
  32735. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  32736. to = this._keys[this._keys.length - 1].frame;
  32737. }
  32738. //to and from cannot be the same key
  32739. if (from === to) {
  32740. from++;
  32741. }
  32742. // Compute ratio
  32743. var range = to - from;
  32744. var offsetValue;
  32745. // ratio represents the frame delta between from and to
  32746. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  32747. var highLimitValue = 0;
  32748. if (ratio > range && !loop) {
  32749. returnValue = false;
  32750. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  32751. }
  32752. else {
  32753. // Get max value if required
  32754. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  32755. var keyOffset = to.toString() + from.toString();
  32756. if (!this._offsetsCache[keyOffset]) {
  32757. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32758. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32759. switch (this.dataType) {
  32760. // Float
  32761. case Animation.ANIMATIONTYPE_FLOAT:
  32762. this._offsetsCache[keyOffset] = toValue - fromValue;
  32763. break;
  32764. // Quaternion
  32765. case Animation.ANIMATIONTYPE_QUATERNION:
  32766. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32767. break;
  32768. // Vector3
  32769. case Animation.ANIMATIONTYPE_VECTOR3:
  32770. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32771. // Vector2
  32772. case Animation.ANIMATIONTYPE_VECTOR2:
  32773. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32774. // Size
  32775. case Animation.ANIMATIONTYPE_SIZE:
  32776. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32777. // Color3
  32778. case Animation.ANIMATIONTYPE_COLOR3:
  32779. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32780. default:
  32781. break;
  32782. }
  32783. this._highLimitsCache[keyOffset] = toValue;
  32784. }
  32785. highLimitValue = this._highLimitsCache[keyOffset];
  32786. offsetValue = this._offsetsCache[keyOffset];
  32787. }
  32788. }
  32789. if (offsetValue === undefined) {
  32790. switch (this.dataType) {
  32791. // Float
  32792. case Animation.ANIMATIONTYPE_FLOAT:
  32793. offsetValue = 0;
  32794. break;
  32795. // Quaternion
  32796. case Animation.ANIMATIONTYPE_QUATERNION:
  32797. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  32798. break;
  32799. // Vector3
  32800. case Animation.ANIMATIONTYPE_VECTOR3:
  32801. offsetValue = BABYLON.Vector3.Zero();
  32802. break;
  32803. // Vector2
  32804. case Animation.ANIMATIONTYPE_VECTOR2:
  32805. offsetValue = BABYLON.Vector2.Zero();
  32806. break;
  32807. // Size
  32808. case Animation.ANIMATIONTYPE_SIZE:
  32809. offsetValue = BABYLON.Size.Zero();
  32810. break;
  32811. // Color3
  32812. case Animation.ANIMATIONTYPE_COLOR3:
  32813. offsetValue = BABYLON.Color3.Black();
  32814. }
  32815. }
  32816. // Compute value
  32817. var repeatCount = (ratio / range) >> 0;
  32818. var currentFrame = returnValue ? from + ratio % range : to;
  32819. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  32820. // Set value
  32821. this.setValue(currentValue);
  32822. // Check events
  32823. for (var index = 0; index < this._events.length; index++) {
  32824. if (currentFrame >= this._events[index].frame) {
  32825. var event = this._events[index];
  32826. if (!event.isDone) {
  32827. // If event should be done only once, remove it.
  32828. if (event.onlyOnce) {
  32829. this._events.splice(index, 1);
  32830. index--;
  32831. }
  32832. event.isDone = true;
  32833. event.action();
  32834. } // Don't do anything if the event has already be done.
  32835. }
  32836. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  32837. // reset event, the animation is looping
  32838. this._events[index].isDone = false;
  32839. }
  32840. }
  32841. if (!returnValue) {
  32842. this._stopped = true;
  32843. }
  32844. return returnValue;
  32845. };
  32846. Animation.prototype.serialize = function () {
  32847. var serializationObject = {};
  32848. serializationObject.name = this.name;
  32849. serializationObject.property = this.targetProperty;
  32850. serializationObject.framePerSecond = this.framePerSecond;
  32851. serializationObject.dataType = this.dataType;
  32852. serializationObject.loopBehavior = this.loopMode;
  32853. serializationObject.enableBlending = this.enableBlending;
  32854. serializationObject.blendingSpeed = this.blendingSpeed;
  32855. var dataType = this.dataType;
  32856. serializationObject.keys = [];
  32857. var keys = this.getKeys();
  32858. for (var index = 0; index < keys.length; index++) {
  32859. var animationKey = keys[index];
  32860. var key = {};
  32861. key.frame = animationKey.frame;
  32862. switch (dataType) {
  32863. case Animation.ANIMATIONTYPE_FLOAT:
  32864. key.values = [animationKey.value];
  32865. break;
  32866. case Animation.ANIMATIONTYPE_QUATERNION:
  32867. case Animation.ANIMATIONTYPE_MATRIX:
  32868. case Animation.ANIMATIONTYPE_VECTOR3:
  32869. case Animation.ANIMATIONTYPE_COLOR3:
  32870. key.values = animationKey.value.asArray();
  32871. break;
  32872. }
  32873. serializationObject.keys.push(key);
  32874. }
  32875. serializationObject.ranges = [];
  32876. for (var name in this._ranges) {
  32877. var range = {};
  32878. range.name = name;
  32879. range.from = this._ranges[name].from;
  32880. range.to = this._ranges[name].to;
  32881. serializationObject.ranges.push(range);
  32882. }
  32883. return serializationObject;
  32884. };
  32885. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  32886. get: function () {
  32887. return Animation._ANIMATIONTYPE_FLOAT;
  32888. },
  32889. enumerable: true,
  32890. configurable: true
  32891. });
  32892. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  32893. get: function () {
  32894. return Animation._ANIMATIONTYPE_VECTOR3;
  32895. },
  32896. enumerable: true,
  32897. configurable: true
  32898. });
  32899. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  32900. get: function () {
  32901. return Animation._ANIMATIONTYPE_VECTOR2;
  32902. },
  32903. enumerable: true,
  32904. configurable: true
  32905. });
  32906. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  32907. get: function () {
  32908. return Animation._ANIMATIONTYPE_SIZE;
  32909. },
  32910. enumerable: true,
  32911. configurable: true
  32912. });
  32913. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  32914. get: function () {
  32915. return Animation._ANIMATIONTYPE_QUATERNION;
  32916. },
  32917. enumerable: true,
  32918. configurable: true
  32919. });
  32920. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  32921. get: function () {
  32922. return Animation._ANIMATIONTYPE_MATRIX;
  32923. },
  32924. enumerable: true,
  32925. configurable: true
  32926. });
  32927. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  32928. get: function () {
  32929. return Animation._ANIMATIONTYPE_COLOR3;
  32930. },
  32931. enumerable: true,
  32932. configurable: true
  32933. });
  32934. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  32935. get: function () {
  32936. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  32937. },
  32938. enumerable: true,
  32939. configurable: true
  32940. });
  32941. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  32942. get: function () {
  32943. return Animation._ANIMATIONLOOPMODE_CYCLE;
  32944. },
  32945. enumerable: true,
  32946. configurable: true
  32947. });
  32948. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  32949. get: function () {
  32950. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  32951. },
  32952. enumerable: true,
  32953. configurable: true
  32954. });
  32955. Animation.Parse = function (parsedAnimation) {
  32956. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  32957. var dataType = parsedAnimation.dataType;
  32958. var keys = [];
  32959. var data;
  32960. var index;
  32961. if (parsedAnimation.enableBlending) {
  32962. animation.enableBlending = parsedAnimation.enableBlending;
  32963. }
  32964. if (parsedAnimation.blendingSpeed) {
  32965. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  32966. }
  32967. for (index = 0; index < parsedAnimation.keys.length; index++) {
  32968. var key = parsedAnimation.keys[index];
  32969. switch (dataType) {
  32970. case Animation.ANIMATIONTYPE_FLOAT:
  32971. data = key.values[0];
  32972. break;
  32973. case Animation.ANIMATIONTYPE_QUATERNION:
  32974. data = BABYLON.Quaternion.FromArray(key.values);
  32975. break;
  32976. case Animation.ANIMATIONTYPE_MATRIX:
  32977. data = BABYLON.Matrix.FromArray(key.values);
  32978. break;
  32979. case Animation.ANIMATIONTYPE_COLOR3:
  32980. data = BABYLON.Color3.FromArray(key.values);
  32981. break;
  32982. case Animation.ANIMATIONTYPE_VECTOR3:
  32983. default:
  32984. data = BABYLON.Vector3.FromArray(key.values);
  32985. break;
  32986. }
  32987. keys.push({
  32988. frame: key.frame,
  32989. value: data
  32990. });
  32991. }
  32992. animation.setKeys(keys);
  32993. if (parsedAnimation.ranges) {
  32994. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  32995. data = parsedAnimation.ranges[index];
  32996. animation.createRange(data.name, data.from, data.to);
  32997. }
  32998. }
  32999. return animation;
  33000. };
  33001. Animation.AppendSerializedAnimations = function (source, destination) {
  33002. if (source.animations) {
  33003. destination.animations = [];
  33004. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  33005. var animation = source.animations[animationIndex];
  33006. destination.animations.push(animation.serialize());
  33007. }
  33008. }
  33009. };
  33010. return Animation;
  33011. }());
  33012. // Statics
  33013. Animation._ANIMATIONTYPE_FLOAT = 0;
  33014. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  33015. Animation._ANIMATIONTYPE_QUATERNION = 2;
  33016. Animation._ANIMATIONTYPE_MATRIX = 3;
  33017. Animation._ANIMATIONTYPE_COLOR3 = 4;
  33018. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  33019. Animation._ANIMATIONTYPE_SIZE = 6;
  33020. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  33021. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  33022. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  33023. BABYLON.Animation = Animation;
  33024. })(BABYLON || (BABYLON = {}));
  33025. //# sourceMappingURL=babylon.animation.js.map
  33026. var BABYLON;
  33027. (function (BABYLON) {
  33028. var Animatable = (function () {
  33029. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  33030. if (fromFrame === void 0) { fromFrame = 0; }
  33031. if (toFrame === void 0) { toFrame = 100; }
  33032. if (loopAnimation === void 0) { loopAnimation = false; }
  33033. if (speedRatio === void 0) { speedRatio = 1.0; }
  33034. this.target = target;
  33035. this.fromFrame = fromFrame;
  33036. this.toFrame = toFrame;
  33037. this.loopAnimation = loopAnimation;
  33038. this.speedRatio = speedRatio;
  33039. this.onAnimationEnd = onAnimationEnd;
  33040. this._localDelayOffset = null;
  33041. this._pausedDelay = null;
  33042. this._animations = new Array();
  33043. this._paused = false;
  33044. this.animationStarted = false;
  33045. if (animations) {
  33046. this.appendAnimations(target, animations);
  33047. }
  33048. this._scene = scene;
  33049. scene._activeAnimatables.push(this);
  33050. }
  33051. // Methods
  33052. Animatable.prototype.getAnimations = function () {
  33053. return this._animations;
  33054. };
  33055. Animatable.prototype.appendAnimations = function (target, animations) {
  33056. for (var index = 0; index < animations.length; index++) {
  33057. var animation = animations[index];
  33058. animation._target = target;
  33059. this._animations.push(animation);
  33060. }
  33061. };
  33062. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  33063. var animations = this._animations;
  33064. for (var index = 0; index < animations.length; index++) {
  33065. if (animations[index].targetProperty === property) {
  33066. return animations[index];
  33067. }
  33068. }
  33069. return null;
  33070. };
  33071. Animatable.prototype.reset = function () {
  33072. var animations = this._animations;
  33073. for (var index = 0; index < animations.length; index++) {
  33074. animations[index].reset();
  33075. }
  33076. this._localDelayOffset = null;
  33077. this._pausedDelay = null;
  33078. };
  33079. Animatable.prototype.enableBlending = function (blendingSpeed) {
  33080. var animations = this._animations;
  33081. for (var index = 0; index < animations.length; index++) {
  33082. animations[index].enableBlending = true;
  33083. animations[index].blendingSpeed = blendingSpeed;
  33084. }
  33085. };
  33086. Animatable.prototype.disableBlending = function () {
  33087. var animations = this._animations;
  33088. for (var index = 0; index < animations.length; index++) {
  33089. animations[index].enableBlending = false;
  33090. }
  33091. };
  33092. Animatable.prototype.goToFrame = function (frame) {
  33093. var animations = this._animations;
  33094. if (animations[0]) {
  33095. var fps = animations[0].framePerSecond;
  33096. var currentFrame = animations[0].currentFrame;
  33097. var adjustTime = frame - currentFrame;
  33098. var delay = adjustTime * 1000 / fps;
  33099. this._localDelayOffset -= delay;
  33100. }
  33101. for (var index = 0; index < animations.length; index++) {
  33102. animations[index].goToFrame(frame);
  33103. }
  33104. };
  33105. Animatable.prototype.pause = function () {
  33106. if (this._paused) {
  33107. return;
  33108. }
  33109. this._paused = true;
  33110. };
  33111. Animatable.prototype.restart = function () {
  33112. this._paused = false;
  33113. };
  33114. Animatable.prototype.stop = function (animationName) {
  33115. if (animationName) {
  33116. var idx = this._scene._activeAnimatables.indexOf(this);
  33117. if (idx > -1) {
  33118. var animations = this._animations;
  33119. for (var index = animations.length - 1; index >= 0; index--) {
  33120. if (typeof animationName === "string" && animations[index].name != animationName) {
  33121. continue;
  33122. }
  33123. animations[index].reset();
  33124. animations.splice(index, 1);
  33125. }
  33126. if (animations.length == 0) {
  33127. this._scene._activeAnimatables.splice(idx, 1);
  33128. if (this.onAnimationEnd) {
  33129. this.onAnimationEnd();
  33130. }
  33131. }
  33132. }
  33133. }
  33134. else {
  33135. var index = this._scene._activeAnimatables.indexOf(this);
  33136. if (index > -1) {
  33137. this._scene._activeAnimatables.splice(index, 1);
  33138. var animations = this._animations;
  33139. for (var index = 0; index < animations.length; index++) {
  33140. animations[index].reset();
  33141. }
  33142. if (this.onAnimationEnd) {
  33143. this.onAnimationEnd();
  33144. }
  33145. }
  33146. }
  33147. };
  33148. Animatable.prototype._animate = function (delay) {
  33149. if (this._paused) {
  33150. this.animationStarted = false;
  33151. if (this._pausedDelay === null) {
  33152. this._pausedDelay = delay;
  33153. }
  33154. return true;
  33155. }
  33156. if (this._localDelayOffset === null) {
  33157. this._localDelayOffset = delay;
  33158. }
  33159. else if (this._pausedDelay !== null) {
  33160. this._localDelayOffset += delay - this._pausedDelay;
  33161. this._pausedDelay = null;
  33162. }
  33163. // Animating
  33164. var running = false;
  33165. var animations = this._animations;
  33166. var index;
  33167. for (index = 0; index < animations.length; index++) {
  33168. var animation = animations[index];
  33169. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  33170. running = running || isRunning;
  33171. }
  33172. this.animationStarted = running;
  33173. if (!running) {
  33174. // Remove from active animatables
  33175. index = this._scene._activeAnimatables.indexOf(this);
  33176. this._scene._activeAnimatables.splice(index, 1);
  33177. }
  33178. if (!running && this.onAnimationEnd) {
  33179. this.onAnimationEnd();
  33180. this.onAnimationEnd = null;
  33181. }
  33182. return running;
  33183. };
  33184. return Animatable;
  33185. }());
  33186. BABYLON.Animatable = Animatable;
  33187. })(BABYLON || (BABYLON = {}));
  33188. //# sourceMappingURL=babylon.animatable.js.map
  33189. var BABYLON;
  33190. (function (BABYLON) {
  33191. var EasingFunction = (function () {
  33192. function EasingFunction() {
  33193. // Properties
  33194. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  33195. }
  33196. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  33197. get: function () {
  33198. return EasingFunction._EASINGMODE_EASEIN;
  33199. },
  33200. enumerable: true,
  33201. configurable: true
  33202. });
  33203. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  33204. get: function () {
  33205. return EasingFunction._EASINGMODE_EASEOUT;
  33206. },
  33207. enumerable: true,
  33208. configurable: true
  33209. });
  33210. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  33211. get: function () {
  33212. return EasingFunction._EASINGMODE_EASEINOUT;
  33213. },
  33214. enumerable: true,
  33215. configurable: true
  33216. });
  33217. EasingFunction.prototype.setEasingMode = function (easingMode) {
  33218. var n = Math.min(Math.max(easingMode, 0), 2);
  33219. this._easingMode = n;
  33220. };
  33221. EasingFunction.prototype.getEasingMode = function () {
  33222. return this._easingMode;
  33223. };
  33224. EasingFunction.prototype.easeInCore = function (gradient) {
  33225. throw new Error('You must implement this method');
  33226. };
  33227. EasingFunction.prototype.ease = function (gradient) {
  33228. switch (this._easingMode) {
  33229. case EasingFunction.EASINGMODE_EASEIN:
  33230. return this.easeInCore(gradient);
  33231. case EasingFunction.EASINGMODE_EASEOUT:
  33232. return (1 - this.easeInCore(1 - gradient));
  33233. }
  33234. if (gradient >= 0.5) {
  33235. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  33236. }
  33237. return (this.easeInCore(gradient * 2) * 0.5);
  33238. };
  33239. return EasingFunction;
  33240. }());
  33241. //Statics
  33242. EasingFunction._EASINGMODE_EASEIN = 0;
  33243. EasingFunction._EASINGMODE_EASEOUT = 1;
  33244. EasingFunction._EASINGMODE_EASEINOUT = 2;
  33245. BABYLON.EasingFunction = EasingFunction;
  33246. var CircleEase = (function (_super) {
  33247. __extends(CircleEase, _super);
  33248. function CircleEase() {
  33249. return _super !== null && _super.apply(this, arguments) || this;
  33250. }
  33251. CircleEase.prototype.easeInCore = function (gradient) {
  33252. gradient = Math.max(0, Math.min(1, gradient));
  33253. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  33254. };
  33255. return CircleEase;
  33256. }(EasingFunction));
  33257. BABYLON.CircleEase = CircleEase;
  33258. var BackEase = (function (_super) {
  33259. __extends(BackEase, _super);
  33260. function BackEase(amplitude) {
  33261. if (amplitude === void 0) { amplitude = 1; }
  33262. var _this = _super.call(this) || this;
  33263. _this.amplitude = amplitude;
  33264. return _this;
  33265. }
  33266. BackEase.prototype.easeInCore = function (gradient) {
  33267. var num = Math.max(0, this.amplitude);
  33268. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  33269. };
  33270. return BackEase;
  33271. }(EasingFunction));
  33272. BABYLON.BackEase = BackEase;
  33273. var BounceEase = (function (_super) {
  33274. __extends(BounceEase, _super);
  33275. function BounceEase(bounces, bounciness) {
  33276. if (bounces === void 0) { bounces = 3; }
  33277. if (bounciness === void 0) { bounciness = 2; }
  33278. var _this = _super.call(this) || this;
  33279. _this.bounces = bounces;
  33280. _this.bounciness = bounciness;
  33281. return _this;
  33282. }
  33283. BounceEase.prototype.easeInCore = function (gradient) {
  33284. var y = Math.max(0.0, this.bounces);
  33285. var bounciness = this.bounciness;
  33286. if (bounciness <= 1.0) {
  33287. bounciness = 1.001;
  33288. }
  33289. var num9 = Math.pow(bounciness, y);
  33290. var num5 = 1.0 - bounciness;
  33291. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  33292. var num15 = gradient * num4;
  33293. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  33294. var num3 = Math.floor(num65);
  33295. var num13 = num3 + 1.0;
  33296. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  33297. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  33298. var num7 = (num8 + num12) * 0.5;
  33299. var num6 = gradient - num7;
  33300. var num2 = num7 - num8;
  33301. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  33302. };
  33303. return BounceEase;
  33304. }(EasingFunction));
  33305. BABYLON.BounceEase = BounceEase;
  33306. var CubicEase = (function (_super) {
  33307. __extends(CubicEase, _super);
  33308. function CubicEase() {
  33309. return _super !== null && _super.apply(this, arguments) || this;
  33310. }
  33311. CubicEase.prototype.easeInCore = function (gradient) {
  33312. return (gradient * gradient * gradient);
  33313. };
  33314. return CubicEase;
  33315. }(EasingFunction));
  33316. BABYLON.CubicEase = CubicEase;
  33317. var ElasticEase = (function (_super) {
  33318. __extends(ElasticEase, _super);
  33319. function ElasticEase(oscillations, springiness) {
  33320. if (oscillations === void 0) { oscillations = 3; }
  33321. if (springiness === void 0) { springiness = 3; }
  33322. var _this = _super.call(this) || this;
  33323. _this.oscillations = oscillations;
  33324. _this.springiness = springiness;
  33325. return _this;
  33326. }
  33327. ElasticEase.prototype.easeInCore = function (gradient) {
  33328. var num2;
  33329. var num3 = Math.max(0.0, this.oscillations);
  33330. var num = Math.max(0.0, this.springiness);
  33331. if (num == 0) {
  33332. num2 = gradient;
  33333. }
  33334. else {
  33335. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  33336. }
  33337. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  33338. };
  33339. return ElasticEase;
  33340. }(EasingFunction));
  33341. BABYLON.ElasticEase = ElasticEase;
  33342. var ExponentialEase = (function (_super) {
  33343. __extends(ExponentialEase, _super);
  33344. function ExponentialEase(exponent) {
  33345. if (exponent === void 0) { exponent = 2; }
  33346. var _this = _super.call(this) || this;
  33347. _this.exponent = exponent;
  33348. return _this;
  33349. }
  33350. ExponentialEase.prototype.easeInCore = function (gradient) {
  33351. if (this.exponent <= 0) {
  33352. return gradient;
  33353. }
  33354. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  33355. };
  33356. return ExponentialEase;
  33357. }(EasingFunction));
  33358. BABYLON.ExponentialEase = ExponentialEase;
  33359. var PowerEase = (function (_super) {
  33360. __extends(PowerEase, _super);
  33361. function PowerEase(power) {
  33362. if (power === void 0) { power = 2; }
  33363. var _this = _super.call(this) || this;
  33364. _this.power = power;
  33365. return _this;
  33366. }
  33367. PowerEase.prototype.easeInCore = function (gradient) {
  33368. var y = Math.max(0.0, this.power);
  33369. return Math.pow(gradient, y);
  33370. };
  33371. return PowerEase;
  33372. }(EasingFunction));
  33373. BABYLON.PowerEase = PowerEase;
  33374. var QuadraticEase = (function (_super) {
  33375. __extends(QuadraticEase, _super);
  33376. function QuadraticEase() {
  33377. return _super !== null && _super.apply(this, arguments) || this;
  33378. }
  33379. QuadraticEase.prototype.easeInCore = function (gradient) {
  33380. return (gradient * gradient);
  33381. };
  33382. return QuadraticEase;
  33383. }(EasingFunction));
  33384. BABYLON.QuadraticEase = QuadraticEase;
  33385. var QuarticEase = (function (_super) {
  33386. __extends(QuarticEase, _super);
  33387. function QuarticEase() {
  33388. return _super !== null && _super.apply(this, arguments) || this;
  33389. }
  33390. QuarticEase.prototype.easeInCore = function (gradient) {
  33391. return (gradient * gradient * gradient * gradient);
  33392. };
  33393. return QuarticEase;
  33394. }(EasingFunction));
  33395. BABYLON.QuarticEase = QuarticEase;
  33396. var QuinticEase = (function (_super) {
  33397. __extends(QuinticEase, _super);
  33398. function QuinticEase() {
  33399. return _super !== null && _super.apply(this, arguments) || this;
  33400. }
  33401. QuinticEase.prototype.easeInCore = function (gradient) {
  33402. return (gradient * gradient * gradient * gradient * gradient);
  33403. };
  33404. return QuinticEase;
  33405. }(EasingFunction));
  33406. BABYLON.QuinticEase = QuinticEase;
  33407. var SineEase = (function (_super) {
  33408. __extends(SineEase, _super);
  33409. function SineEase() {
  33410. return _super !== null && _super.apply(this, arguments) || this;
  33411. }
  33412. SineEase.prototype.easeInCore = function (gradient) {
  33413. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  33414. };
  33415. return SineEase;
  33416. }(EasingFunction));
  33417. BABYLON.SineEase = SineEase;
  33418. var BezierCurveEase = (function (_super) {
  33419. __extends(BezierCurveEase, _super);
  33420. function BezierCurveEase(x1, y1, x2, y2) {
  33421. if (x1 === void 0) { x1 = 0; }
  33422. if (y1 === void 0) { y1 = 0; }
  33423. if (x2 === void 0) { x2 = 1; }
  33424. if (y2 === void 0) { y2 = 1; }
  33425. var _this = _super.call(this) || this;
  33426. _this.x1 = x1;
  33427. _this.y1 = y1;
  33428. _this.x2 = x2;
  33429. _this.y2 = y2;
  33430. return _this;
  33431. }
  33432. BezierCurveEase.prototype.easeInCore = function (gradient) {
  33433. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  33434. };
  33435. return BezierCurveEase;
  33436. }(EasingFunction));
  33437. BABYLON.BezierCurveEase = BezierCurveEase;
  33438. })(BABYLON || (BABYLON = {}));
  33439. //# sourceMappingURL=babylon.easing.js.map
  33440. var BABYLON;
  33441. (function (BABYLON) {
  33442. var Condition = (function () {
  33443. function Condition(actionManager) {
  33444. this._actionManager = actionManager;
  33445. }
  33446. Condition.prototype.isValid = function () {
  33447. return true;
  33448. };
  33449. Condition.prototype._getProperty = function (propertyPath) {
  33450. return this._actionManager._getProperty(propertyPath);
  33451. };
  33452. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  33453. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33454. };
  33455. Condition.prototype.serialize = function () {
  33456. };
  33457. Condition.prototype._serialize = function (serializedCondition) {
  33458. return {
  33459. type: 2,
  33460. children: [],
  33461. name: serializedCondition.name,
  33462. properties: serializedCondition.properties
  33463. };
  33464. };
  33465. return Condition;
  33466. }());
  33467. BABYLON.Condition = Condition;
  33468. var ValueCondition = (function (_super) {
  33469. __extends(ValueCondition, _super);
  33470. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  33471. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  33472. var _this = _super.call(this, actionManager) || this;
  33473. _this.propertyPath = propertyPath;
  33474. _this.value = value;
  33475. _this.operator = operator;
  33476. _this._target = target;
  33477. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  33478. _this._property = _this._getProperty(_this.propertyPath);
  33479. return _this;
  33480. }
  33481. Object.defineProperty(ValueCondition, "IsEqual", {
  33482. get: function () {
  33483. return ValueCondition._IsEqual;
  33484. },
  33485. enumerable: true,
  33486. configurable: true
  33487. });
  33488. Object.defineProperty(ValueCondition, "IsDifferent", {
  33489. get: function () {
  33490. return ValueCondition._IsDifferent;
  33491. },
  33492. enumerable: true,
  33493. configurable: true
  33494. });
  33495. Object.defineProperty(ValueCondition, "IsGreater", {
  33496. get: function () {
  33497. return ValueCondition._IsGreater;
  33498. },
  33499. enumerable: true,
  33500. configurable: true
  33501. });
  33502. Object.defineProperty(ValueCondition, "IsLesser", {
  33503. get: function () {
  33504. return ValueCondition._IsLesser;
  33505. },
  33506. enumerable: true,
  33507. configurable: true
  33508. });
  33509. // Methods
  33510. ValueCondition.prototype.isValid = function () {
  33511. switch (this.operator) {
  33512. case ValueCondition.IsGreater:
  33513. return this._effectiveTarget[this._property] > this.value;
  33514. case ValueCondition.IsLesser:
  33515. return this._effectiveTarget[this._property] < this.value;
  33516. case ValueCondition.IsEqual:
  33517. case ValueCondition.IsDifferent:
  33518. var check;
  33519. if (this.value.equals) {
  33520. check = this.value.equals(this._effectiveTarget[this._property]);
  33521. }
  33522. else {
  33523. check = this.value === this._effectiveTarget[this._property];
  33524. }
  33525. return this.operator === ValueCondition.IsEqual ? check : !check;
  33526. }
  33527. return false;
  33528. };
  33529. ValueCondition.prototype.serialize = function () {
  33530. return this._serialize({
  33531. name: "ValueCondition",
  33532. properties: [
  33533. BABYLON.Action._GetTargetProperty(this._target),
  33534. { name: "propertyPath", value: this.propertyPath },
  33535. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33536. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  33537. ]
  33538. });
  33539. };
  33540. ValueCondition.GetOperatorName = function (operator) {
  33541. switch (operator) {
  33542. case ValueCondition._IsEqual: return "IsEqual";
  33543. case ValueCondition._IsDifferent: return "IsDifferent";
  33544. case ValueCondition._IsGreater: return "IsGreater";
  33545. case ValueCondition._IsLesser: return "IsLesser";
  33546. default: return "";
  33547. }
  33548. };
  33549. return ValueCondition;
  33550. }(Condition));
  33551. // Statics
  33552. ValueCondition._IsEqual = 0;
  33553. ValueCondition._IsDifferent = 1;
  33554. ValueCondition._IsGreater = 2;
  33555. ValueCondition._IsLesser = 3;
  33556. BABYLON.ValueCondition = ValueCondition;
  33557. var PredicateCondition = (function (_super) {
  33558. __extends(PredicateCondition, _super);
  33559. function PredicateCondition(actionManager, predicate) {
  33560. var _this = _super.call(this, actionManager) || this;
  33561. _this.predicate = predicate;
  33562. return _this;
  33563. }
  33564. PredicateCondition.prototype.isValid = function () {
  33565. return this.predicate();
  33566. };
  33567. return PredicateCondition;
  33568. }(Condition));
  33569. BABYLON.PredicateCondition = PredicateCondition;
  33570. var StateCondition = (function (_super) {
  33571. __extends(StateCondition, _super);
  33572. function StateCondition(actionManager, target, value) {
  33573. var _this = _super.call(this, actionManager) || this;
  33574. _this.value = value;
  33575. _this._target = target;
  33576. return _this;
  33577. }
  33578. // Methods
  33579. StateCondition.prototype.isValid = function () {
  33580. return this._target.state === this.value;
  33581. };
  33582. StateCondition.prototype.serialize = function () {
  33583. return this._serialize({
  33584. name: "StateCondition",
  33585. properties: [
  33586. BABYLON.Action._GetTargetProperty(this._target),
  33587. { name: "value", value: this.value }
  33588. ]
  33589. });
  33590. };
  33591. return StateCondition;
  33592. }(Condition));
  33593. BABYLON.StateCondition = StateCondition;
  33594. })(BABYLON || (BABYLON = {}));
  33595. //# sourceMappingURL=babylon.condition.js.map
  33596. var BABYLON;
  33597. (function (BABYLON) {
  33598. var Action = (function () {
  33599. function Action(triggerOptions, condition) {
  33600. this.triggerOptions = triggerOptions;
  33601. if (triggerOptions.parameter) {
  33602. this.trigger = triggerOptions.trigger;
  33603. this._triggerParameter = triggerOptions.parameter;
  33604. }
  33605. else {
  33606. this.trigger = triggerOptions;
  33607. }
  33608. this._nextActiveAction = this;
  33609. this._condition = condition;
  33610. }
  33611. // Methods
  33612. Action.prototype._prepare = function () {
  33613. };
  33614. Action.prototype.getTriggerParameter = function () {
  33615. return this._triggerParameter;
  33616. };
  33617. Action.prototype._executeCurrent = function (evt) {
  33618. if (this._nextActiveAction._condition) {
  33619. var condition = this._nextActiveAction._condition;
  33620. var currentRenderId = this._actionManager.getScene().getRenderId();
  33621. // We cache the current evaluation for the current frame
  33622. if (condition._evaluationId === currentRenderId) {
  33623. if (!condition._currentResult) {
  33624. return;
  33625. }
  33626. }
  33627. else {
  33628. condition._evaluationId = currentRenderId;
  33629. if (!condition.isValid()) {
  33630. condition._currentResult = false;
  33631. return;
  33632. }
  33633. condition._currentResult = true;
  33634. }
  33635. }
  33636. this._nextActiveAction.execute(evt);
  33637. this.skipToNextActiveAction();
  33638. };
  33639. Action.prototype.execute = function (evt) {
  33640. };
  33641. Action.prototype.skipToNextActiveAction = function () {
  33642. if (this._nextActiveAction._child) {
  33643. if (!this._nextActiveAction._child._actionManager) {
  33644. this._nextActiveAction._child._actionManager = this._actionManager;
  33645. }
  33646. this._nextActiveAction = this._nextActiveAction._child;
  33647. }
  33648. else {
  33649. this._nextActiveAction = this;
  33650. }
  33651. };
  33652. Action.prototype.then = function (action) {
  33653. this._child = action;
  33654. action._actionManager = this._actionManager;
  33655. action._prepare();
  33656. return action;
  33657. };
  33658. Action.prototype._getProperty = function (propertyPath) {
  33659. return this._actionManager._getProperty(propertyPath);
  33660. };
  33661. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  33662. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33663. };
  33664. Action.prototype.serialize = function (parent) {
  33665. };
  33666. // Called by BABYLON.Action objects in serialize(...). Internal use
  33667. Action.prototype._serialize = function (serializedAction, parent) {
  33668. var serializationObject = {
  33669. type: 1,
  33670. children: [],
  33671. name: serializedAction.name,
  33672. properties: serializedAction.properties || []
  33673. };
  33674. // Serialize child
  33675. if (this._child) {
  33676. this._child.serialize(serializationObject);
  33677. }
  33678. // Check if "this" has a condition
  33679. if (this._condition) {
  33680. var serializedCondition = this._condition.serialize();
  33681. serializedCondition.children.push(serializationObject);
  33682. if (parent) {
  33683. parent.children.push(serializedCondition);
  33684. }
  33685. return serializedCondition;
  33686. }
  33687. if (parent) {
  33688. parent.children.push(serializationObject);
  33689. }
  33690. return serializationObject;
  33691. };
  33692. return Action;
  33693. }());
  33694. Action._SerializeValueAsString = function (value) {
  33695. if (typeof value === "number") {
  33696. return value.toString();
  33697. }
  33698. if (typeof value === "boolean") {
  33699. return value ? "true" : "false";
  33700. }
  33701. if (value instanceof BABYLON.Vector2) {
  33702. return value.x + ", " + value.y;
  33703. }
  33704. if (value instanceof BABYLON.Vector3) {
  33705. return value.x + ", " + value.y + ", " + value.z;
  33706. }
  33707. if (value instanceof BABYLON.Color3) {
  33708. return value.r + ", " + value.g + ", " + value.b;
  33709. }
  33710. if (value instanceof BABYLON.Color4) {
  33711. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  33712. }
  33713. return value; // string
  33714. };
  33715. Action._GetTargetProperty = function (target) {
  33716. return {
  33717. name: "target",
  33718. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  33719. : target instanceof BABYLON.Light ? "LightProperties"
  33720. : target instanceof BABYLON.Camera ? "CameraProperties"
  33721. : "SceneProperties",
  33722. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  33723. };
  33724. };
  33725. BABYLON.Action = Action;
  33726. })(BABYLON || (BABYLON = {}));
  33727. //# sourceMappingURL=babylon.action.js.map
  33728. var BABYLON;
  33729. (function (BABYLON) {
  33730. /**
  33731. * ActionEvent is the event beint sent when an action is triggered.
  33732. */
  33733. var ActionEvent = (function () {
  33734. /**
  33735. * @constructor
  33736. * @param source The mesh or sprite that triggered the action.
  33737. * @param pointerX The X mouse cursor position at the time of the event
  33738. * @param pointerY The Y mouse cursor position at the time of the event
  33739. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  33740. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  33741. */
  33742. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  33743. this.source = source;
  33744. this.pointerX = pointerX;
  33745. this.pointerY = pointerY;
  33746. this.meshUnderPointer = meshUnderPointer;
  33747. this.sourceEvent = sourceEvent;
  33748. this.additionalData = additionalData;
  33749. }
  33750. /**
  33751. * Helper function to auto-create an ActionEvent from a source mesh.
  33752. * @param source The source mesh that triggered the event
  33753. * @param evt {Event} The original (browser) event
  33754. */
  33755. ActionEvent.CreateNew = function (source, evt, additionalData) {
  33756. var scene = source.getScene();
  33757. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33758. };
  33759. /**
  33760. * Helper function to auto-create an ActionEvent from a source mesh.
  33761. * @param source The source sprite that triggered the event
  33762. * @param scene Scene associated with the sprite
  33763. * @param evt {Event} The original (browser) event
  33764. */
  33765. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  33766. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33767. };
  33768. /**
  33769. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  33770. * @param scene the scene where the event occurred
  33771. * @param evt {Event} The original (browser) event
  33772. */
  33773. ActionEvent.CreateNewFromScene = function (scene, evt) {
  33774. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  33775. };
  33776. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  33777. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  33778. };
  33779. return ActionEvent;
  33780. }());
  33781. BABYLON.ActionEvent = ActionEvent;
  33782. /**
  33783. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  33784. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  33785. */
  33786. var ActionManager = (function () {
  33787. function ActionManager(scene) {
  33788. // Members
  33789. this.actions = new Array();
  33790. this.hoverCursor = '';
  33791. this._scene = scene;
  33792. scene._actionManagers.push(this);
  33793. }
  33794. Object.defineProperty(ActionManager, "NothingTrigger", {
  33795. get: function () {
  33796. return ActionManager._NothingTrigger;
  33797. },
  33798. enumerable: true,
  33799. configurable: true
  33800. });
  33801. Object.defineProperty(ActionManager, "OnPickTrigger", {
  33802. get: function () {
  33803. return ActionManager._OnPickTrigger;
  33804. },
  33805. enumerable: true,
  33806. configurable: true
  33807. });
  33808. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  33809. get: function () {
  33810. return ActionManager._OnLeftPickTrigger;
  33811. },
  33812. enumerable: true,
  33813. configurable: true
  33814. });
  33815. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  33816. get: function () {
  33817. return ActionManager._OnRightPickTrigger;
  33818. },
  33819. enumerable: true,
  33820. configurable: true
  33821. });
  33822. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  33823. get: function () {
  33824. return ActionManager._OnCenterPickTrigger;
  33825. },
  33826. enumerable: true,
  33827. configurable: true
  33828. });
  33829. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  33830. get: function () {
  33831. return ActionManager._OnPickDownTrigger;
  33832. },
  33833. enumerable: true,
  33834. configurable: true
  33835. });
  33836. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  33837. get: function () {
  33838. return ActionManager._OnDoublePickTrigger;
  33839. },
  33840. enumerable: true,
  33841. configurable: true
  33842. });
  33843. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  33844. get: function () {
  33845. return ActionManager._OnPickUpTrigger;
  33846. },
  33847. enumerable: true,
  33848. configurable: true
  33849. });
  33850. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  33851. /// This trigger will only be raised if you also declared a OnPickDown
  33852. get: function () {
  33853. return ActionManager._OnPickOutTrigger;
  33854. },
  33855. enumerable: true,
  33856. configurable: true
  33857. });
  33858. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  33859. get: function () {
  33860. return ActionManager._OnLongPressTrigger;
  33861. },
  33862. enumerable: true,
  33863. configurable: true
  33864. });
  33865. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  33866. get: function () {
  33867. return ActionManager._OnPointerOverTrigger;
  33868. },
  33869. enumerable: true,
  33870. configurable: true
  33871. });
  33872. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  33873. get: function () {
  33874. return ActionManager._OnPointerOutTrigger;
  33875. },
  33876. enumerable: true,
  33877. configurable: true
  33878. });
  33879. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  33880. get: function () {
  33881. return ActionManager._OnEveryFrameTrigger;
  33882. },
  33883. enumerable: true,
  33884. configurable: true
  33885. });
  33886. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  33887. get: function () {
  33888. return ActionManager._OnIntersectionEnterTrigger;
  33889. },
  33890. enumerable: true,
  33891. configurable: true
  33892. });
  33893. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  33894. get: function () {
  33895. return ActionManager._OnIntersectionExitTrigger;
  33896. },
  33897. enumerable: true,
  33898. configurable: true
  33899. });
  33900. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  33901. get: function () {
  33902. return ActionManager._OnKeyDownTrigger;
  33903. },
  33904. enumerable: true,
  33905. configurable: true
  33906. });
  33907. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  33908. get: function () {
  33909. return ActionManager._OnKeyUpTrigger;
  33910. },
  33911. enumerable: true,
  33912. configurable: true
  33913. });
  33914. // Methods
  33915. ActionManager.prototype.dispose = function () {
  33916. var index = this._scene._actionManagers.indexOf(this);
  33917. for (var i = 0; i < this.actions.length; i++) {
  33918. var action = this.actions[i];
  33919. ActionManager.Triggers[action.trigger]--;
  33920. if (ActionManager.Triggers[action.trigger] === 0) {
  33921. delete ActionManager.Triggers[action.trigger];
  33922. }
  33923. }
  33924. if (index > -1) {
  33925. this._scene._actionManagers.splice(index, 1);
  33926. }
  33927. };
  33928. ActionManager.prototype.getScene = function () {
  33929. return this._scene;
  33930. };
  33931. /**
  33932. * Does this action manager handles actions of any of the given triggers
  33933. * @param {number[]} triggers - the triggers to be tested
  33934. * @return {boolean} whether one (or more) of the triggers is handeled
  33935. */
  33936. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  33937. for (var index = 0; index < this.actions.length; index++) {
  33938. var action = this.actions[index];
  33939. if (triggers.indexOf(action.trigger) > -1) {
  33940. return true;
  33941. }
  33942. }
  33943. return false;
  33944. };
  33945. /**
  33946. * Does this action manager handles actions of a given trigger
  33947. * @param {number} trigger - the trigger to be tested
  33948. * @return {boolean} whether the trigger is handeled
  33949. */
  33950. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  33951. for (var index = 0; index < this.actions.length; index++) {
  33952. var action = this.actions[index];
  33953. if (action.trigger === trigger) {
  33954. return true;
  33955. }
  33956. }
  33957. return false;
  33958. };
  33959. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  33960. /**
  33961. * Does this action manager has pointer triggers
  33962. * @return {boolean} whether or not it has pointer triggers
  33963. */
  33964. get: function () {
  33965. for (var index = 0; index < this.actions.length; index++) {
  33966. var action = this.actions[index];
  33967. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  33968. return true;
  33969. }
  33970. }
  33971. return false;
  33972. },
  33973. enumerable: true,
  33974. configurable: true
  33975. });
  33976. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  33977. /**
  33978. * Does this action manager has pick triggers
  33979. * @return {boolean} whether or not it has pick triggers
  33980. */
  33981. get: function () {
  33982. for (var index = 0; index < this.actions.length; index++) {
  33983. var action = this.actions[index];
  33984. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  33985. return true;
  33986. }
  33987. }
  33988. return false;
  33989. },
  33990. enumerable: true,
  33991. configurable: true
  33992. });
  33993. Object.defineProperty(ActionManager, "HasTriggers", {
  33994. /**
  33995. * Does exist one action manager with at least one trigger
  33996. * @return {boolean} whether or not it exists one action manager with one trigger
  33997. **/
  33998. get: function () {
  33999. for (var t in ActionManager.Triggers) {
  34000. if (ActionManager.Triggers.hasOwnProperty(t)) {
  34001. return true;
  34002. }
  34003. }
  34004. return false;
  34005. },
  34006. enumerable: true,
  34007. configurable: true
  34008. });
  34009. Object.defineProperty(ActionManager, "HasPickTriggers", {
  34010. /**
  34011. * Does exist one action manager with at least one pick trigger
  34012. * @return {boolean} whether or not it exists one action manager with one pick trigger
  34013. **/
  34014. get: function () {
  34015. for (var t in ActionManager.Triggers) {
  34016. if (ActionManager.Triggers.hasOwnProperty(t)) {
  34017. var t_int = parseInt(t);
  34018. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  34019. return true;
  34020. }
  34021. }
  34022. }
  34023. return false;
  34024. },
  34025. enumerable: true,
  34026. configurable: true
  34027. });
  34028. /**
  34029. * Does exist one action manager that handles actions of a given trigger
  34030. * @param {number} trigger - the trigger to be tested
  34031. * @return {boolean} whether the trigger is handeled by at least one action manager
  34032. **/
  34033. ActionManager.HasSpecificTrigger = function (trigger) {
  34034. for (var t in ActionManager.Triggers) {
  34035. if (ActionManager.Triggers.hasOwnProperty(t)) {
  34036. var t_int = parseInt(t);
  34037. if (t_int === trigger) {
  34038. return true;
  34039. }
  34040. }
  34041. }
  34042. return false;
  34043. };
  34044. /**
  34045. * Registers an action to this action manager
  34046. * @param {BABYLON.Action} action - the action to be registered
  34047. * @return {BABYLON.Action} the action amended (prepared) after registration
  34048. */
  34049. ActionManager.prototype.registerAction = function (action) {
  34050. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  34051. if (this.getScene().actionManager !== this) {
  34052. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  34053. return null;
  34054. }
  34055. }
  34056. this.actions.push(action);
  34057. if (ActionManager.Triggers[action.trigger]) {
  34058. ActionManager.Triggers[action.trigger]++;
  34059. }
  34060. else {
  34061. ActionManager.Triggers[action.trigger] = 1;
  34062. }
  34063. action._actionManager = this;
  34064. action._prepare();
  34065. return action;
  34066. };
  34067. /**
  34068. * Process a specific trigger
  34069. * @param {number} trigger - the trigger to process
  34070. * @param evt {BABYLON.ActionEvent} the event details to be processed
  34071. */
  34072. ActionManager.prototype.processTrigger = function (trigger, evt) {
  34073. for (var index = 0; index < this.actions.length; index++) {
  34074. var action = this.actions[index];
  34075. if (action.trigger === trigger) {
  34076. if (trigger === ActionManager.OnKeyUpTrigger
  34077. || trigger === ActionManager.OnKeyDownTrigger) {
  34078. var parameter = action.getTriggerParameter();
  34079. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  34080. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  34081. var actualkey = String.fromCharCode(unicode).toLowerCase();
  34082. if (actualkey !== parameter.toLowerCase()) {
  34083. continue;
  34084. }
  34085. }
  34086. }
  34087. action._executeCurrent(evt);
  34088. }
  34089. }
  34090. };
  34091. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  34092. var properties = propertyPath.split(".");
  34093. for (var index = 0; index < properties.length - 1; index++) {
  34094. target = target[properties[index]];
  34095. }
  34096. return target;
  34097. };
  34098. ActionManager.prototype._getProperty = function (propertyPath) {
  34099. var properties = propertyPath.split(".");
  34100. return properties[properties.length - 1];
  34101. };
  34102. ActionManager.prototype.serialize = function (name) {
  34103. var root = {
  34104. children: [],
  34105. name: name,
  34106. type: 3,
  34107. properties: [] // Empty for root but required
  34108. };
  34109. for (var i = 0; i < this.actions.length; i++) {
  34110. var triggerObject = {
  34111. type: 0,
  34112. children: [],
  34113. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  34114. properties: []
  34115. };
  34116. var triggerOptions = this.actions[i].triggerOptions;
  34117. if (triggerOptions && typeof triggerOptions !== "number") {
  34118. if (triggerOptions.parameter instanceof BABYLON.Node) {
  34119. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  34120. }
  34121. else {
  34122. var parameter = {};
  34123. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  34124. if (triggerOptions.parameter.mesh) {
  34125. parameter._meshId = triggerOptions.parameter.mesh.id;
  34126. }
  34127. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  34128. }
  34129. }
  34130. // Serialize child action, recursively
  34131. this.actions[i].serialize(triggerObject);
  34132. // Add serialized trigger
  34133. root.children.push(triggerObject);
  34134. }
  34135. return root;
  34136. };
  34137. ActionManager.Parse = function (parsedActions, object, scene) {
  34138. var actionManager = new BABYLON.ActionManager(scene);
  34139. if (object === null)
  34140. scene.actionManager = actionManager;
  34141. else
  34142. object.actionManager = actionManager;
  34143. // instanciate a new object
  34144. var instanciate = function (name, params) {
  34145. var newInstance = Object.create(BABYLON[name].prototype);
  34146. newInstance.constructor.apply(newInstance, params);
  34147. return newInstance;
  34148. };
  34149. var parseParameter = function (name, value, target, propertyPath) {
  34150. if (propertyPath === null) {
  34151. // String, boolean or float
  34152. var floatValue = parseFloat(value);
  34153. if (value === "true" || value === "false")
  34154. return value === "true";
  34155. else
  34156. return isNaN(floatValue) ? value : floatValue;
  34157. }
  34158. var effectiveTarget = propertyPath.split(".");
  34159. var values = value.split(",");
  34160. // Get effective Target
  34161. for (var i = 0; i < effectiveTarget.length; i++) {
  34162. target = target[effectiveTarget[i]];
  34163. }
  34164. // Return appropriate value with its type
  34165. if (typeof (target) === "boolean")
  34166. return values[0] === "true";
  34167. if (typeof (target) === "string")
  34168. return values[0];
  34169. // Parameters with multiple values such as Vector3 etc.
  34170. var split = new Array();
  34171. for (var i = 0; i < values.length; i++)
  34172. split.push(parseFloat(values[i]));
  34173. if (target instanceof BABYLON.Vector3)
  34174. return BABYLON.Vector3.FromArray(split);
  34175. if (target instanceof BABYLON.Vector4)
  34176. return BABYLON.Vector4.FromArray(split);
  34177. if (target instanceof BABYLON.Color3)
  34178. return BABYLON.Color3.FromArray(split);
  34179. if (target instanceof BABYLON.Color4)
  34180. return BABYLON.Color4.FromArray(split);
  34181. return parseFloat(values[0]);
  34182. };
  34183. // traverse graph per trigger
  34184. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  34185. if (combineArray === void 0) { combineArray = null; }
  34186. if (parsedAction.detached)
  34187. return;
  34188. var parameters = new Array();
  34189. var target = null;
  34190. var propertyPath = null;
  34191. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  34192. // Parameters
  34193. if (parsedAction.type === 2)
  34194. parameters.push(actionManager);
  34195. else
  34196. parameters.push(trigger);
  34197. if (combine) {
  34198. var actions = new Array();
  34199. for (var j = 0; j < parsedAction.combine.length; j++) {
  34200. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  34201. }
  34202. parameters.push(actions);
  34203. }
  34204. else {
  34205. for (var i = 0; i < parsedAction.properties.length; i++) {
  34206. var value = parsedAction.properties[i].value;
  34207. var name = parsedAction.properties[i].name;
  34208. var targetType = parsedAction.properties[i].targetType;
  34209. if (name === "target")
  34210. if (targetType !== null && targetType === "SceneProperties")
  34211. value = target = scene;
  34212. else
  34213. value = target = scene.getNodeByName(value);
  34214. else if (name === "parent")
  34215. value = scene.getNodeByName(value);
  34216. else if (name === "sound")
  34217. value = scene.getSoundByName(value);
  34218. else if (name !== "propertyPath") {
  34219. if (parsedAction.type === 2 && name === "operator")
  34220. value = BABYLON.ValueCondition[value];
  34221. else
  34222. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  34223. }
  34224. else {
  34225. propertyPath = value;
  34226. }
  34227. parameters.push(value);
  34228. }
  34229. }
  34230. if (combineArray === null) {
  34231. parameters.push(condition);
  34232. }
  34233. else {
  34234. parameters.push(null);
  34235. }
  34236. // If interpolate value action
  34237. if (parsedAction.name === "InterpolateValueAction") {
  34238. var param = parameters[parameters.length - 2];
  34239. parameters[parameters.length - 1] = param;
  34240. parameters[parameters.length - 2] = condition;
  34241. }
  34242. // Action or condition(s) and not CombineAction
  34243. var newAction = instanciate(parsedAction.name, parameters);
  34244. if (newAction instanceof BABYLON.Condition && condition !== null) {
  34245. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  34246. if (action)
  34247. action.then(nothing);
  34248. else
  34249. actionManager.registerAction(nothing);
  34250. action = nothing;
  34251. }
  34252. if (combineArray === null) {
  34253. if (newAction instanceof BABYLON.Condition) {
  34254. condition = newAction;
  34255. newAction = action;
  34256. }
  34257. else {
  34258. condition = null;
  34259. if (action)
  34260. action.then(newAction);
  34261. else
  34262. actionManager.registerAction(newAction);
  34263. }
  34264. }
  34265. else {
  34266. combineArray.push(newAction);
  34267. }
  34268. for (var i = 0; i < parsedAction.children.length; i++)
  34269. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  34270. };
  34271. // triggers
  34272. for (var i = 0; i < parsedActions.children.length; i++) {
  34273. var triggerParams;
  34274. var trigger = parsedActions.children[i];
  34275. if (trigger.properties.length > 0) {
  34276. var param = trigger.properties[0].value;
  34277. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  34278. if (value._meshId) {
  34279. value.mesh = scene.getMeshByID(value._meshId);
  34280. }
  34281. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  34282. }
  34283. else
  34284. triggerParams = BABYLON.ActionManager[trigger.name];
  34285. for (var j = 0; j < trigger.children.length; j++) {
  34286. if (!trigger.detached)
  34287. traverse(trigger.children[j], triggerParams, null, null);
  34288. }
  34289. }
  34290. };
  34291. ActionManager.GetTriggerName = function (trigger) {
  34292. switch (trigger) {
  34293. case 0: return "NothingTrigger";
  34294. case 1: return "OnPickTrigger";
  34295. case 2: return "OnLeftPickTrigger";
  34296. case 3: return "OnRightPickTrigger";
  34297. case 4: return "OnCenterPickTrigger";
  34298. case 5: return "OnPickDownTrigger";
  34299. case 6: return "OnPickUpTrigger";
  34300. case 7: return "OnLongPressTrigger";
  34301. case 8: return "OnPointerOverTrigger";
  34302. case 9: return "OnPointerOutTrigger";
  34303. case 10: return "OnEveryFrameTrigger";
  34304. case 11: return "OnIntersectionEnterTrigger";
  34305. case 12: return "OnIntersectionExitTrigger";
  34306. case 13: return "OnKeyDownTrigger";
  34307. case 14: return "OnKeyUpTrigger";
  34308. case 15: return "OnPickOutTrigger";
  34309. default: return "";
  34310. }
  34311. };
  34312. return ActionManager;
  34313. }());
  34314. // Statics
  34315. ActionManager._NothingTrigger = 0;
  34316. ActionManager._OnPickTrigger = 1;
  34317. ActionManager._OnLeftPickTrigger = 2;
  34318. ActionManager._OnRightPickTrigger = 3;
  34319. ActionManager._OnCenterPickTrigger = 4;
  34320. ActionManager._OnPickDownTrigger = 5;
  34321. ActionManager._OnDoublePickTrigger = 6;
  34322. ActionManager._OnPickUpTrigger = 7;
  34323. ActionManager._OnLongPressTrigger = 8;
  34324. ActionManager._OnPointerOverTrigger = 9;
  34325. ActionManager._OnPointerOutTrigger = 10;
  34326. ActionManager._OnEveryFrameTrigger = 11;
  34327. ActionManager._OnIntersectionEnterTrigger = 12;
  34328. ActionManager._OnIntersectionExitTrigger = 13;
  34329. ActionManager._OnKeyDownTrigger = 14;
  34330. ActionManager._OnKeyUpTrigger = 15;
  34331. ActionManager._OnPickOutTrigger = 16;
  34332. ActionManager.Triggers = {};
  34333. BABYLON.ActionManager = ActionManager;
  34334. })(BABYLON || (BABYLON = {}));
  34335. //# sourceMappingURL=babylon.actionManager.js.map
  34336. var BABYLON;
  34337. (function (BABYLON) {
  34338. var InterpolateValueAction = (function (_super) {
  34339. __extends(InterpolateValueAction, _super);
  34340. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  34341. if (duration === void 0) { duration = 1000; }
  34342. var _this = _super.call(this, triggerOptions, condition) || this;
  34343. _this.propertyPath = propertyPath;
  34344. _this.value = value;
  34345. _this.duration = duration;
  34346. _this.stopOtherAnimations = stopOtherAnimations;
  34347. _this.onInterpolationDone = onInterpolationDone;
  34348. _this._target = _this._effectiveTarget = target;
  34349. return _this;
  34350. }
  34351. InterpolateValueAction.prototype._prepare = function () {
  34352. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34353. this._property = this._getProperty(this.propertyPath);
  34354. };
  34355. InterpolateValueAction.prototype.execute = function () {
  34356. var scene = this._actionManager.getScene();
  34357. var keys = [
  34358. {
  34359. frame: 0,
  34360. value: this._effectiveTarget[this._property]
  34361. }, {
  34362. frame: 100,
  34363. value: this.value
  34364. }
  34365. ];
  34366. var dataType;
  34367. if (typeof this.value === "number") {
  34368. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  34369. }
  34370. else if (this.value instanceof BABYLON.Color3) {
  34371. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  34372. }
  34373. else if (this.value instanceof BABYLON.Vector3) {
  34374. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  34375. }
  34376. else if (this.value instanceof BABYLON.Matrix) {
  34377. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  34378. }
  34379. else if (this.value instanceof BABYLON.Quaternion) {
  34380. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  34381. }
  34382. else {
  34383. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  34384. return;
  34385. }
  34386. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  34387. animation.setKeys(keys);
  34388. if (this.stopOtherAnimations) {
  34389. scene.stopAnimation(this._effectiveTarget);
  34390. }
  34391. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  34392. };
  34393. InterpolateValueAction.prototype.serialize = function (parent) {
  34394. return _super.prototype._serialize.call(this, {
  34395. name: "InterpolateValueAction",
  34396. properties: [
  34397. BABYLON.Action._GetTargetProperty(this._target),
  34398. { name: "propertyPath", value: this.propertyPath },
  34399. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34400. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  34401. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  34402. ]
  34403. }, parent);
  34404. };
  34405. return InterpolateValueAction;
  34406. }(BABYLON.Action));
  34407. BABYLON.InterpolateValueAction = InterpolateValueAction;
  34408. })(BABYLON || (BABYLON = {}));
  34409. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  34410. var BABYLON;
  34411. (function (BABYLON) {
  34412. var SwitchBooleanAction = (function (_super) {
  34413. __extends(SwitchBooleanAction, _super);
  34414. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  34415. var _this = _super.call(this, triggerOptions, condition) || this;
  34416. _this.propertyPath = propertyPath;
  34417. _this._target = _this._effectiveTarget = target;
  34418. return _this;
  34419. }
  34420. SwitchBooleanAction.prototype._prepare = function () {
  34421. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34422. this._property = this._getProperty(this.propertyPath);
  34423. };
  34424. SwitchBooleanAction.prototype.execute = function () {
  34425. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  34426. };
  34427. SwitchBooleanAction.prototype.serialize = function (parent) {
  34428. return _super.prototype._serialize.call(this, {
  34429. name: "SwitchBooleanAction",
  34430. properties: [
  34431. BABYLON.Action._GetTargetProperty(this._target),
  34432. { name: "propertyPath", value: this.propertyPath }
  34433. ]
  34434. }, parent);
  34435. };
  34436. return SwitchBooleanAction;
  34437. }(BABYLON.Action));
  34438. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  34439. var SetStateAction = (function (_super) {
  34440. __extends(SetStateAction, _super);
  34441. function SetStateAction(triggerOptions, target, value, condition) {
  34442. var _this = _super.call(this, triggerOptions, condition) || this;
  34443. _this.value = value;
  34444. _this._target = target;
  34445. return _this;
  34446. }
  34447. SetStateAction.prototype.execute = function () {
  34448. this._target.state = this.value;
  34449. };
  34450. SetStateAction.prototype.serialize = function (parent) {
  34451. return _super.prototype._serialize.call(this, {
  34452. name: "SetStateAction",
  34453. properties: [
  34454. BABYLON.Action._GetTargetProperty(this._target),
  34455. { name: "value", value: this.value }
  34456. ]
  34457. }, parent);
  34458. };
  34459. return SetStateAction;
  34460. }(BABYLON.Action));
  34461. BABYLON.SetStateAction = SetStateAction;
  34462. var SetValueAction = (function (_super) {
  34463. __extends(SetValueAction, _super);
  34464. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  34465. var _this = _super.call(this, triggerOptions, condition) || this;
  34466. _this.propertyPath = propertyPath;
  34467. _this.value = value;
  34468. _this._target = _this._effectiveTarget = target;
  34469. return _this;
  34470. }
  34471. SetValueAction.prototype._prepare = function () {
  34472. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34473. this._property = this._getProperty(this.propertyPath);
  34474. };
  34475. SetValueAction.prototype.execute = function () {
  34476. this._effectiveTarget[this._property] = this.value;
  34477. if (this._target.markAsDirty) {
  34478. this._target.markAsDirty(this._property);
  34479. }
  34480. };
  34481. SetValueAction.prototype.serialize = function (parent) {
  34482. return _super.prototype._serialize.call(this, {
  34483. name: "SetValueAction",
  34484. properties: [
  34485. BABYLON.Action._GetTargetProperty(this._target),
  34486. { name: "propertyPath", value: this.propertyPath },
  34487. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34488. ]
  34489. }, parent);
  34490. };
  34491. return SetValueAction;
  34492. }(BABYLON.Action));
  34493. BABYLON.SetValueAction = SetValueAction;
  34494. var IncrementValueAction = (function (_super) {
  34495. __extends(IncrementValueAction, _super);
  34496. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  34497. var _this = _super.call(this, triggerOptions, condition) || this;
  34498. _this.propertyPath = propertyPath;
  34499. _this.value = value;
  34500. _this._target = _this._effectiveTarget = target;
  34501. return _this;
  34502. }
  34503. IncrementValueAction.prototype._prepare = function () {
  34504. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34505. this._property = this._getProperty(this.propertyPath);
  34506. if (typeof this._effectiveTarget[this._property] !== "number") {
  34507. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  34508. }
  34509. };
  34510. IncrementValueAction.prototype.execute = function () {
  34511. this._effectiveTarget[this._property] += this.value;
  34512. if (this._target.markAsDirty) {
  34513. this._target.markAsDirty(this._property);
  34514. }
  34515. };
  34516. IncrementValueAction.prototype.serialize = function (parent) {
  34517. return _super.prototype._serialize.call(this, {
  34518. name: "IncrementValueAction",
  34519. properties: [
  34520. BABYLON.Action._GetTargetProperty(this._target),
  34521. { name: "propertyPath", value: this.propertyPath },
  34522. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34523. ]
  34524. }, parent);
  34525. };
  34526. return IncrementValueAction;
  34527. }(BABYLON.Action));
  34528. BABYLON.IncrementValueAction = IncrementValueAction;
  34529. var PlayAnimationAction = (function (_super) {
  34530. __extends(PlayAnimationAction, _super);
  34531. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  34532. var _this = _super.call(this, triggerOptions, condition) || this;
  34533. _this.from = from;
  34534. _this.to = to;
  34535. _this.loop = loop;
  34536. _this._target = target;
  34537. return _this;
  34538. }
  34539. PlayAnimationAction.prototype._prepare = function () {
  34540. };
  34541. PlayAnimationAction.prototype.execute = function () {
  34542. var scene = this._actionManager.getScene();
  34543. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  34544. };
  34545. PlayAnimationAction.prototype.serialize = function (parent) {
  34546. return _super.prototype._serialize.call(this, {
  34547. name: "PlayAnimationAction",
  34548. properties: [
  34549. BABYLON.Action._GetTargetProperty(this._target),
  34550. { name: "from", value: String(this.from) },
  34551. { name: "to", value: String(this.to) },
  34552. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  34553. ]
  34554. }, parent);
  34555. };
  34556. return PlayAnimationAction;
  34557. }(BABYLON.Action));
  34558. BABYLON.PlayAnimationAction = PlayAnimationAction;
  34559. var StopAnimationAction = (function (_super) {
  34560. __extends(StopAnimationAction, _super);
  34561. function StopAnimationAction(triggerOptions, target, condition) {
  34562. var _this = _super.call(this, triggerOptions, condition) || this;
  34563. _this._target = target;
  34564. return _this;
  34565. }
  34566. StopAnimationAction.prototype._prepare = function () {
  34567. };
  34568. StopAnimationAction.prototype.execute = function () {
  34569. var scene = this._actionManager.getScene();
  34570. scene.stopAnimation(this._target);
  34571. };
  34572. StopAnimationAction.prototype.serialize = function (parent) {
  34573. return _super.prototype._serialize.call(this, {
  34574. name: "StopAnimationAction",
  34575. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  34576. }, parent);
  34577. };
  34578. return StopAnimationAction;
  34579. }(BABYLON.Action));
  34580. BABYLON.StopAnimationAction = StopAnimationAction;
  34581. var DoNothingAction = (function (_super) {
  34582. __extends(DoNothingAction, _super);
  34583. function DoNothingAction(triggerOptions, condition) {
  34584. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  34585. return _super.call(this, triggerOptions, condition) || this;
  34586. }
  34587. DoNothingAction.prototype.execute = function () {
  34588. };
  34589. DoNothingAction.prototype.serialize = function (parent) {
  34590. return _super.prototype._serialize.call(this, {
  34591. name: "DoNothingAction",
  34592. properties: []
  34593. }, parent);
  34594. };
  34595. return DoNothingAction;
  34596. }(BABYLON.Action));
  34597. BABYLON.DoNothingAction = DoNothingAction;
  34598. var CombineAction = (function (_super) {
  34599. __extends(CombineAction, _super);
  34600. function CombineAction(triggerOptions, children, condition) {
  34601. var _this = _super.call(this, triggerOptions, condition) || this;
  34602. _this.children = children;
  34603. return _this;
  34604. }
  34605. CombineAction.prototype._prepare = function () {
  34606. for (var index = 0; index < this.children.length; index++) {
  34607. this.children[index]._actionManager = this._actionManager;
  34608. this.children[index]._prepare();
  34609. }
  34610. };
  34611. CombineAction.prototype.execute = function (evt) {
  34612. for (var index = 0; index < this.children.length; index++) {
  34613. this.children[index].execute(evt);
  34614. }
  34615. };
  34616. CombineAction.prototype.serialize = function (parent) {
  34617. var serializationObject = _super.prototype._serialize.call(this, {
  34618. name: "CombineAction",
  34619. properties: [],
  34620. combine: []
  34621. }, parent);
  34622. for (var i = 0; i < this.children.length; i++) {
  34623. serializationObject.combine.push(this.children[i].serialize(null));
  34624. }
  34625. return serializationObject;
  34626. };
  34627. return CombineAction;
  34628. }(BABYLON.Action));
  34629. BABYLON.CombineAction = CombineAction;
  34630. var ExecuteCodeAction = (function (_super) {
  34631. __extends(ExecuteCodeAction, _super);
  34632. function ExecuteCodeAction(triggerOptions, func, condition) {
  34633. var _this = _super.call(this, triggerOptions, condition) || this;
  34634. _this.func = func;
  34635. return _this;
  34636. }
  34637. ExecuteCodeAction.prototype.execute = function (evt) {
  34638. this.func(evt);
  34639. };
  34640. return ExecuteCodeAction;
  34641. }(BABYLON.Action));
  34642. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  34643. var SetParentAction = (function (_super) {
  34644. __extends(SetParentAction, _super);
  34645. function SetParentAction(triggerOptions, target, parent, condition) {
  34646. var _this = _super.call(this, triggerOptions, condition) || this;
  34647. _this._target = target;
  34648. _this._parent = parent;
  34649. return _this;
  34650. }
  34651. SetParentAction.prototype._prepare = function () {
  34652. };
  34653. SetParentAction.prototype.execute = function () {
  34654. if (this._target.parent === this._parent) {
  34655. return;
  34656. }
  34657. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  34658. invertParentWorldMatrix.invert();
  34659. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  34660. this._target.parent = this._parent;
  34661. };
  34662. SetParentAction.prototype.serialize = function (parent) {
  34663. return _super.prototype._serialize.call(this, {
  34664. name: "SetParentAction",
  34665. properties: [
  34666. BABYLON.Action._GetTargetProperty(this._target),
  34667. BABYLON.Action._GetTargetProperty(this._parent),
  34668. ]
  34669. }, parent);
  34670. };
  34671. return SetParentAction;
  34672. }(BABYLON.Action));
  34673. BABYLON.SetParentAction = SetParentAction;
  34674. var PlaySoundAction = (function (_super) {
  34675. __extends(PlaySoundAction, _super);
  34676. function PlaySoundAction(triggerOptions, sound, condition) {
  34677. var _this = _super.call(this, triggerOptions, condition) || this;
  34678. _this._sound = sound;
  34679. return _this;
  34680. }
  34681. PlaySoundAction.prototype._prepare = function () {
  34682. };
  34683. PlaySoundAction.prototype.execute = function () {
  34684. if (this._sound !== undefined)
  34685. this._sound.play();
  34686. };
  34687. PlaySoundAction.prototype.serialize = function (parent) {
  34688. return _super.prototype._serialize.call(this, {
  34689. name: "PlaySoundAction",
  34690. properties: [{ name: "sound", value: this._sound.name }]
  34691. }, parent);
  34692. };
  34693. return PlaySoundAction;
  34694. }(BABYLON.Action));
  34695. BABYLON.PlaySoundAction = PlaySoundAction;
  34696. var StopSoundAction = (function (_super) {
  34697. __extends(StopSoundAction, _super);
  34698. function StopSoundAction(triggerOptions, sound, condition) {
  34699. var _this = _super.call(this, triggerOptions, condition) || this;
  34700. _this._sound = sound;
  34701. return _this;
  34702. }
  34703. StopSoundAction.prototype._prepare = function () {
  34704. };
  34705. StopSoundAction.prototype.execute = function () {
  34706. if (this._sound !== undefined)
  34707. this._sound.stop();
  34708. };
  34709. StopSoundAction.prototype.serialize = function (parent) {
  34710. return _super.prototype._serialize.call(this, {
  34711. name: "StopSoundAction",
  34712. properties: [{ name: "sound", value: this._sound.name }]
  34713. }, parent);
  34714. };
  34715. return StopSoundAction;
  34716. }(BABYLON.Action));
  34717. BABYLON.StopSoundAction = StopSoundAction;
  34718. })(BABYLON || (BABYLON = {}));
  34719. //# sourceMappingURL=babylon.directActions.js.map
  34720. var BABYLON;
  34721. (function (BABYLON) {
  34722. var SpriteManager = (function () {
  34723. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  34724. if (epsilon === void 0) { epsilon = 0.01; }
  34725. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34726. this.name = name;
  34727. this.sprites = new Array();
  34728. this.renderingGroupId = 0;
  34729. this.layerMask = 0x0FFFFFFF;
  34730. this.fogEnabled = true;
  34731. this.isPickable = false;
  34732. /**
  34733. * An event triggered when the manager is disposed.
  34734. * @type {BABYLON.Observable}
  34735. */
  34736. this.onDisposeObservable = new BABYLON.Observable();
  34737. this._vertexBuffers = {};
  34738. this._capacity = capacity;
  34739. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  34740. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34741. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34742. if (cellSize.width && cellSize.height) {
  34743. this.cellWidth = cellSize.width;
  34744. this.cellHeight = cellSize.height;
  34745. }
  34746. else if (cellSize !== undefined) {
  34747. this.cellWidth = cellSize;
  34748. this.cellHeight = cellSize;
  34749. }
  34750. else {
  34751. return;
  34752. }
  34753. this._epsilon = epsilon;
  34754. this._scene = scene;
  34755. this._scene.spriteManagers.push(this);
  34756. var indices = [];
  34757. var index = 0;
  34758. for (var count = 0; count < capacity; count++) {
  34759. indices.push(index);
  34760. indices.push(index + 1);
  34761. indices.push(index + 2);
  34762. indices.push(index);
  34763. indices.push(index + 2);
  34764. indices.push(index + 3);
  34765. index += 4;
  34766. }
  34767. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  34768. // VBO
  34769. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  34770. this._vertexData = new Float32Array(capacity * 16 * 4);
  34771. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  34772. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  34773. var options = this._buffer.createVertexBuffer("options", 4, 4);
  34774. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  34775. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  34776. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  34777. this._vertexBuffers["options"] = options;
  34778. this._vertexBuffers["cellInfo"] = cellInfo;
  34779. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  34780. // Effects
  34781. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  34782. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  34783. }
  34784. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  34785. set: function (callback) {
  34786. if (this._onDisposeObserver) {
  34787. this.onDisposeObservable.remove(this._onDisposeObserver);
  34788. }
  34789. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34790. },
  34791. enumerable: true,
  34792. configurable: true
  34793. });
  34794. Object.defineProperty(SpriteManager.prototype, "texture", {
  34795. get: function () {
  34796. return this._spriteTexture;
  34797. },
  34798. set: function (value) {
  34799. this._spriteTexture = value;
  34800. },
  34801. enumerable: true,
  34802. configurable: true
  34803. });
  34804. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  34805. var arrayOffset = index * 16;
  34806. if (offsetX === 0)
  34807. offsetX = this._epsilon;
  34808. else if (offsetX === 1)
  34809. offsetX = 1 - this._epsilon;
  34810. if (offsetY === 0)
  34811. offsetY = this._epsilon;
  34812. else if (offsetY === 1)
  34813. offsetY = 1 - this._epsilon;
  34814. this._vertexData[arrayOffset] = sprite.position.x;
  34815. this._vertexData[arrayOffset + 1] = sprite.position.y;
  34816. this._vertexData[arrayOffset + 2] = sprite.position.z;
  34817. this._vertexData[arrayOffset + 3] = sprite.angle;
  34818. this._vertexData[arrayOffset + 4] = sprite.width;
  34819. this._vertexData[arrayOffset + 5] = sprite.height;
  34820. this._vertexData[arrayOffset + 6] = offsetX;
  34821. this._vertexData[arrayOffset + 7] = offsetY;
  34822. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  34823. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  34824. var offset = (sprite.cellIndex / rowSize) >> 0;
  34825. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  34826. this._vertexData[arrayOffset + 11] = offset;
  34827. // Color
  34828. this._vertexData[arrayOffset + 12] = sprite.color.r;
  34829. this._vertexData[arrayOffset + 13] = sprite.color.g;
  34830. this._vertexData[arrayOffset + 14] = sprite.color.b;
  34831. this._vertexData[arrayOffset + 15] = sprite.color.a;
  34832. };
  34833. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  34834. var count = Math.min(this._capacity, this.sprites.length);
  34835. var min = BABYLON.Vector3.Zero();
  34836. var max = BABYLON.Vector3.Zero();
  34837. var distance = Number.MAX_VALUE;
  34838. var currentSprite;
  34839. var cameraSpacePosition = BABYLON.Vector3.Zero();
  34840. var cameraView = camera.getViewMatrix();
  34841. for (var index = 0; index < count; index++) {
  34842. var sprite = this.sprites[index];
  34843. if (!sprite) {
  34844. continue;
  34845. }
  34846. if (predicate) {
  34847. if (!predicate(sprite)) {
  34848. continue;
  34849. }
  34850. }
  34851. else if (!sprite.isPickable) {
  34852. continue;
  34853. }
  34854. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  34855. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  34856. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  34857. if (ray.intersectsBoxMinMax(min, max)) {
  34858. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  34859. if (distance > currentDistance) {
  34860. distance = currentDistance;
  34861. currentSprite = sprite;
  34862. if (fastCheck) {
  34863. break;
  34864. }
  34865. }
  34866. }
  34867. }
  34868. if (currentSprite) {
  34869. var result = new BABYLON.PickingInfo();
  34870. result.hit = true;
  34871. result.pickedSprite = currentSprite;
  34872. result.distance = distance;
  34873. return result;
  34874. }
  34875. return null;
  34876. };
  34877. SpriteManager.prototype.render = function () {
  34878. // Check
  34879. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  34880. return;
  34881. var engine = this._scene.getEngine();
  34882. var baseSize = this._spriteTexture.getBaseSize();
  34883. // Sprites
  34884. var deltaTime = engine.getDeltaTime();
  34885. var max = Math.min(this._capacity, this.sprites.length);
  34886. var rowSize = baseSize.width / this.cellWidth;
  34887. var offset = 0;
  34888. for (var index = 0; index < max; index++) {
  34889. var sprite = this.sprites[index];
  34890. if (!sprite) {
  34891. continue;
  34892. }
  34893. sprite._animate(deltaTime);
  34894. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  34895. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  34896. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  34897. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  34898. }
  34899. this._buffer.update(this._vertexData);
  34900. // Render
  34901. var effect = this._effectBase;
  34902. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  34903. effect = this._effectFog;
  34904. }
  34905. engine.enableEffect(effect);
  34906. var viewMatrix = this._scene.getViewMatrix();
  34907. effect.setTexture("diffuseSampler", this._spriteTexture);
  34908. effect.setMatrix("view", viewMatrix);
  34909. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  34910. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  34911. // Fog
  34912. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  34913. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  34914. effect.setColor3("vFogColor", this._scene.fogColor);
  34915. }
  34916. // VBOs
  34917. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34918. // Draw order
  34919. engine.setDepthFunctionToLessOrEqual();
  34920. effect.setBool("alphaTest", true);
  34921. engine.setColorWrite(false);
  34922. engine.draw(true, 0, max * 6);
  34923. engine.setColorWrite(true);
  34924. effect.setBool("alphaTest", false);
  34925. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  34926. engine.draw(true, 0, max * 6);
  34927. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34928. };
  34929. SpriteManager.prototype.dispose = function () {
  34930. if (this._buffer) {
  34931. this._buffer.dispose();
  34932. this._buffer = null;
  34933. }
  34934. if (this._indexBuffer) {
  34935. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34936. this._indexBuffer = null;
  34937. }
  34938. if (this._spriteTexture) {
  34939. this._spriteTexture.dispose();
  34940. this._spriteTexture = null;
  34941. }
  34942. // Remove from scene
  34943. var index = this._scene.spriteManagers.indexOf(this);
  34944. this._scene.spriteManagers.splice(index, 1);
  34945. // Callback
  34946. this.onDisposeObservable.notifyObservers(this);
  34947. this.onDisposeObservable.clear();
  34948. };
  34949. return SpriteManager;
  34950. }());
  34951. BABYLON.SpriteManager = SpriteManager;
  34952. })(BABYLON || (BABYLON = {}));
  34953. //# sourceMappingURL=babylon.spriteManager.js.map
  34954. var BABYLON;
  34955. (function (BABYLON) {
  34956. var Sprite = (function () {
  34957. function Sprite(name, manager) {
  34958. this.name = name;
  34959. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  34960. this.width = 1.0;
  34961. this.height = 1.0;
  34962. this.angle = 0;
  34963. this.cellIndex = 0;
  34964. this.invertU = 0;
  34965. this.invertV = 0;
  34966. this.animations = new Array();
  34967. this.isPickable = false;
  34968. this._animationStarted = false;
  34969. this._loopAnimation = false;
  34970. this._fromIndex = 0;
  34971. this._toIndex = 0;
  34972. this._delay = 0;
  34973. this._direction = 1;
  34974. this._frameCount = 0;
  34975. this._time = 0;
  34976. this._manager = manager;
  34977. this._manager.sprites.push(this);
  34978. this.position = BABYLON.Vector3.Zero();
  34979. }
  34980. Object.defineProperty(Sprite.prototype, "size", {
  34981. get: function () {
  34982. return this.width;
  34983. },
  34984. set: function (value) {
  34985. this.width = value;
  34986. this.height = value;
  34987. },
  34988. enumerable: true,
  34989. configurable: true
  34990. });
  34991. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  34992. this._fromIndex = from;
  34993. this._toIndex = to;
  34994. this._loopAnimation = loop;
  34995. this._delay = delay;
  34996. this._animationStarted = true;
  34997. this._direction = from < to ? 1 : -1;
  34998. this.cellIndex = from;
  34999. this._time = 0;
  35000. this._onAnimationEnd = onAnimationEnd;
  35001. };
  35002. Sprite.prototype.stopAnimation = function () {
  35003. this._animationStarted = false;
  35004. };
  35005. Sprite.prototype._animate = function (deltaTime) {
  35006. if (!this._animationStarted)
  35007. return;
  35008. this._time += deltaTime;
  35009. if (this._time > this._delay) {
  35010. this._time = this._time % this._delay;
  35011. this.cellIndex += this._direction;
  35012. if (this.cellIndex === this._toIndex) {
  35013. if (this._loopAnimation) {
  35014. this.cellIndex = this._fromIndex;
  35015. }
  35016. else {
  35017. this._animationStarted = false;
  35018. if (this._onAnimationEnd) {
  35019. this._onAnimationEnd();
  35020. }
  35021. if (this.disposeWhenFinishedAnimating) {
  35022. this.dispose();
  35023. }
  35024. }
  35025. }
  35026. }
  35027. };
  35028. Sprite.prototype.dispose = function () {
  35029. for (var i = 0; i < this._manager.sprites.length; i++) {
  35030. if (this._manager.sprites[i] == this) {
  35031. this._manager.sprites.splice(i, 1);
  35032. }
  35033. }
  35034. };
  35035. return Sprite;
  35036. }());
  35037. BABYLON.Sprite = Sprite;
  35038. })(BABYLON || (BABYLON = {}));
  35039. //# sourceMappingURL=babylon.sprite.js.map
  35040. var BABYLON;
  35041. (function (BABYLON) {
  35042. var IntersectionInfo = (function () {
  35043. function IntersectionInfo(bu, bv, distance) {
  35044. this.bu = bu;
  35045. this.bv = bv;
  35046. this.distance = distance;
  35047. this.faceId = 0;
  35048. this.subMeshId = 0;
  35049. }
  35050. return IntersectionInfo;
  35051. }());
  35052. BABYLON.IntersectionInfo = IntersectionInfo;
  35053. var PickingInfo = (function () {
  35054. function PickingInfo() {
  35055. this.hit = false;
  35056. this.distance = 0;
  35057. this.pickedPoint = null;
  35058. this.pickedMesh = null;
  35059. this.bu = 0;
  35060. this.bv = 0;
  35061. this.faceId = -1;
  35062. this.subMeshId = 0;
  35063. this.pickedSprite = null;
  35064. }
  35065. // Methods
  35066. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  35067. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  35068. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  35069. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35070. return null;
  35071. }
  35072. var indices = this.pickedMesh.getIndices();
  35073. var result;
  35074. if (useVerticesNormals) {
  35075. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35076. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  35077. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  35078. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  35079. normal0 = normal0.scale(this.bu);
  35080. normal1 = normal1.scale(this.bv);
  35081. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  35082. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  35083. }
  35084. else {
  35085. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35086. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  35087. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  35088. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  35089. var p1p2 = vertex1.subtract(vertex2);
  35090. var p3p2 = vertex3.subtract(vertex2);
  35091. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  35092. }
  35093. if (useWorldCoordinates) {
  35094. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  35095. }
  35096. return BABYLON.Vector3.Normalize(result);
  35097. };
  35098. PickingInfo.prototype.getTextureCoordinates = function () {
  35099. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35100. return null;
  35101. }
  35102. var indices = this.pickedMesh.getIndices();
  35103. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35104. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  35105. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  35106. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  35107. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  35108. uv1 = uv1.scale(this.bu);
  35109. uv2 = uv2.scale(this.bv);
  35110. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  35111. };
  35112. return PickingInfo;
  35113. }());
  35114. BABYLON.PickingInfo = PickingInfo;
  35115. })(BABYLON || (BABYLON = {}));
  35116. //# sourceMappingURL=babylon.pickingInfo.js.map
  35117. var BABYLON;
  35118. (function (BABYLON) {
  35119. var Ray = (function () {
  35120. function Ray(origin, direction, length) {
  35121. if (length === void 0) { length = Number.MAX_VALUE; }
  35122. this.origin = origin;
  35123. this.direction = direction;
  35124. this.length = length;
  35125. }
  35126. // Methods
  35127. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  35128. var d = 0.0;
  35129. var maxValue = Number.MAX_VALUE;
  35130. var inv;
  35131. var min;
  35132. var max;
  35133. var temp;
  35134. if (Math.abs(this.direction.x) < 0.0000001) {
  35135. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  35136. return false;
  35137. }
  35138. }
  35139. else {
  35140. inv = 1.0 / this.direction.x;
  35141. min = (minimum.x - this.origin.x) * inv;
  35142. max = (maximum.x - this.origin.x) * inv;
  35143. if (max === -Infinity) {
  35144. max = Infinity;
  35145. }
  35146. if (min > max) {
  35147. temp = min;
  35148. min = max;
  35149. max = temp;
  35150. }
  35151. d = Math.max(min, d);
  35152. maxValue = Math.min(max, maxValue);
  35153. if (d > maxValue) {
  35154. return false;
  35155. }
  35156. }
  35157. if (Math.abs(this.direction.y) < 0.0000001) {
  35158. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  35159. return false;
  35160. }
  35161. }
  35162. else {
  35163. inv = 1.0 / this.direction.y;
  35164. min = (minimum.y - this.origin.y) * inv;
  35165. max = (maximum.y - this.origin.y) * inv;
  35166. if (max === -Infinity) {
  35167. max = Infinity;
  35168. }
  35169. if (min > max) {
  35170. temp = min;
  35171. min = max;
  35172. max = temp;
  35173. }
  35174. d = Math.max(min, d);
  35175. maxValue = Math.min(max, maxValue);
  35176. if (d > maxValue) {
  35177. return false;
  35178. }
  35179. }
  35180. if (Math.abs(this.direction.z) < 0.0000001) {
  35181. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  35182. return false;
  35183. }
  35184. }
  35185. else {
  35186. inv = 1.0 / this.direction.z;
  35187. min = (minimum.z - this.origin.z) * inv;
  35188. max = (maximum.z - this.origin.z) * inv;
  35189. if (max === -Infinity) {
  35190. max = Infinity;
  35191. }
  35192. if (min > max) {
  35193. temp = min;
  35194. min = max;
  35195. max = temp;
  35196. }
  35197. d = Math.max(min, d);
  35198. maxValue = Math.min(max, maxValue);
  35199. if (d > maxValue) {
  35200. return false;
  35201. }
  35202. }
  35203. return true;
  35204. };
  35205. Ray.prototype.intersectsBox = function (box) {
  35206. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  35207. };
  35208. Ray.prototype.intersectsSphere = function (sphere) {
  35209. var x = sphere.center.x - this.origin.x;
  35210. var y = sphere.center.y - this.origin.y;
  35211. var z = sphere.center.z - this.origin.z;
  35212. var pyth = (x * x) + (y * y) + (z * z);
  35213. var rr = sphere.radius * sphere.radius;
  35214. if (pyth <= rr) {
  35215. return true;
  35216. }
  35217. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  35218. if (dot < 0.0) {
  35219. return false;
  35220. }
  35221. var temp = pyth - (dot * dot);
  35222. return temp <= rr;
  35223. };
  35224. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  35225. if (!this._edge1) {
  35226. this._edge1 = BABYLON.Vector3.Zero();
  35227. this._edge2 = BABYLON.Vector3.Zero();
  35228. this._pvec = BABYLON.Vector3.Zero();
  35229. this._tvec = BABYLON.Vector3.Zero();
  35230. this._qvec = BABYLON.Vector3.Zero();
  35231. }
  35232. vertex1.subtractToRef(vertex0, this._edge1);
  35233. vertex2.subtractToRef(vertex0, this._edge2);
  35234. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  35235. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  35236. if (det === 0) {
  35237. return null;
  35238. }
  35239. var invdet = 1 / det;
  35240. this.origin.subtractToRef(vertex0, this._tvec);
  35241. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  35242. if (bu < 0 || bu > 1.0) {
  35243. return null;
  35244. }
  35245. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  35246. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  35247. if (bv < 0 || bu + bv > 1.0) {
  35248. return null;
  35249. }
  35250. //check if the distance is longer than the predefined length.
  35251. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  35252. if (distance > this.length) {
  35253. return null;
  35254. }
  35255. return new BABYLON.IntersectionInfo(bu, bv, distance);
  35256. };
  35257. Ray.prototype.intersectsPlane = function (plane) {
  35258. var distance;
  35259. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  35260. if (Math.abs(result1) < 9.99999997475243E-07) {
  35261. return null;
  35262. }
  35263. else {
  35264. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  35265. distance = (-plane.d - result2) / result1;
  35266. if (distance < 0.0) {
  35267. if (distance < -9.99999997475243E-07) {
  35268. return null;
  35269. }
  35270. else {
  35271. return 0;
  35272. }
  35273. }
  35274. return distance;
  35275. }
  35276. };
  35277. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  35278. var tm = BABYLON.Tmp.Matrix[0];
  35279. mesh.getWorldMatrix().invertToRef(tm);
  35280. if (this._tmpRay) {
  35281. Ray.TransformToRef(this, tm, this._tmpRay);
  35282. }
  35283. else {
  35284. this._tmpRay = Ray.Transform(this, tm);
  35285. }
  35286. return mesh.intersects(this._tmpRay, fastCheck);
  35287. };
  35288. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  35289. if (results) {
  35290. results.length = 0;
  35291. }
  35292. else {
  35293. results = [];
  35294. }
  35295. for (var i = 0; i < meshes.length; i++) {
  35296. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  35297. if (pickInfo.hit) {
  35298. results.push(pickInfo);
  35299. }
  35300. }
  35301. results.sort(this._comparePickingInfo);
  35302. return results;
  35303. };
  35304. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  35305. if (pickingInfoA.distance < pickingInfoB.distance) {
  35306. return -1;
  35307. }
  35308. else if (pickingInfoA.distance > pickingInfoB.distance) {
  35309. return 1;
  35310. }
  35311. else {
  35312. return 0;
  35313. }
  35314. };
  35315. /**
  35316. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  35317. * @param sega the first point of the segment to test the intersection against
  35318. * @param segb the second point of the segment to test the intersection against
  35319. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  35320. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  35321. */
  35322. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  35323. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  35324. var u = segb.subtract(sega);
  35325. var v = rsegb.subtract(this.origin);
  35326. var w = sega.subtract(this.origin);
  35327. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  35328. var b = BABYLON.Vector3.Dot(u, v);
  35329. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  35330. var d = BABYLON.Vector3.Dot(u, w);
  35331. var e = BABYLON.Vector3.Dot(v, w);
  35332. var D = a * c - b * b; // always >= 0
  35333. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  35334. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  35335. // compute the line parameters of the two closest points
  35336. if (D < Ray.smallnum) {
  35337. sN = 0.0; // force using point P0 on segment S1
  35338. sD = 1.0; // to prevent possible division by 0.0 later
  35339. tN = e;
  35340. tD = c;
  35341. }
  35342. else {
  35343. sN = (b * e - c * d);
  35344. tN = (a * e - b * d);
  35345. if (sN < 0.0) {
  35346. sN = 0.0;
  35347. tN = e;
  35348. tD = c;
  35349. }
  35350. else if (sN > sD) {
  35351. sN = sD;
  35352. tN = e + b;
  35353. tD = c;
  35354. }
  35355. }
  35356. if (tN < 0.0) {
  35357. tN = 0.0;
  35358. // recompute sc for this edge
  35359. if (-d < 0.0) {
  35360. sN = 0.0;
  35361. }
  35362. else if (-d > a)
  35363. sN = sD;
  35364. else {
  35365. sN = -d;
  35366. sD = a;
  35367. }
  35368. }
  35369. else if (tN > tD) {
  35370. tN = tD;
  35371. // recompute sc for this edge
  35372. if ((-d + b) < 0.0) {
  35373. sN = 0;
  35374. }
  35375. else if ((-d + b) > a) {
  35376. sN = sD;
  35377. }
  35378. else {
  35379. sN = (-d + b);
  35380. sD = a;
  35381. }
  35382. }
  35383. // finally do the division to get sc and tc
  35384. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  35385. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  35386. // get the difference of the two closest points
  35387. var qtc = v.multiplyByFloats(tc, tc, tc);
  35388. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  35389. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  35390. if (isIntersected) {
  35391. return qtc.length();
  35392. }
  35393. return -1;
  35394. };
  35395. // Statics
  35396. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  35397. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  35398. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  35399. var direction = end.subtract(start);
  35400. direction.normalize();
  35401. return new Ray(start, direction);
  35402. };
  35403. /**
  35404. * 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
  35405. * transformed to the given world matrix.
  35406. * @param origin The origin point
  35407. * @param end The end point
  35408. * @param world a matrix to transform the ray to. Default is the identity matrix.
  35409. */
  35410. Ray.CreateNewFromTo = function (origin, end, world) {
  35411. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  35412. var direction = end.subtract(origin);
  35413. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  35414. direction.normalize();
  35415. return Ray.Transform(new Ray(origin, direction, length), world);
  35416. };
  35417. Ray.Transform = function (ray, matrix) {
  35418. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  35419. Ray.TransformToRef(ray, matrix, result);
  35420. return result;
  35421. };
  35422. Ray.TransformToRef = function (ray, matrix, result) {
  35423. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  35424. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  35425. result.length = ray.length;
  35426. var dir = result.direction;
  35427. var len = dir.length();
  35428. if (!(len === 0 || len === 1)) {
  35429. var num = 1.0 / len;
  35430. dir.x *= num;
  35431. dir.y *= num;
  35432. dir.z *= num;
  35433. result.length *= len;
  35434. }
  35435. };
  35436. return Ray;
  35437. }());
  35438. Ray.smallnum = 0.00000001;
  35439. Ray.rayl = 10e8;
  35440. BABYLON.Ray = Ray;
  35441. })(BABYLON || (BABYLON = {}));
  35442. //# sourceMappingURL=babylon.ray.js.map
  35443. var BABYLON;
  35444. (function (BABYLON) {
  35445. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  35446. if (boxMin.x > sphereCenter.x + sphereRadius)
  35447. return false;
  35448. if (sphereCenter.x - sphereRadius > boxMax.x)
  35449. return false;
  35450. if (boxMin.y > sphereCenter.y + sphereRadius)
  35451. return false;
  35452. if (sphereCenter.y - sphereRadius > boxMax.y)
  35453. return false;
  35454. if (boxMin.z > sphereCenter.z + sphereRadius)
  35455. return false;
  35456. if (sphereCenter.z - sphereRadius > boxMax.z)
  35457. return false;
  35458. return true;
  35459. };
  35460. var getLowestRoot = (function () {
  35461. var result = { root: 0, found: false };
  35462. return function (a, b, c, maxR) {
  35463. result.root = 0;
  35464. result.found = false;
  35465. var determinant = b * b - 4.0 * a * c;
  35466. if (determinant < 0)
  35467. return result;
  35468. var sqrtD = Math.sqrt(determinant);
  35469. var r1 = (-b - sqrtD) / (2.0 * a);
  35470. var r2 = (-b + sqrtD) / (2.0 * a);
  35471. if (r1 > r2) {
  35472. var temp = r2;
  35473. r2 = r1;
  35474. r1 = temp;
  35475. }
  35476. if (r1 > 0 && r1 < maxR) {
  35477. result.root = r1;
  35478. result.found = true;
  35479. return result;
  35480. }
  35481. if (r2 > 0 && r2 < maxR) {
  35482. result.root = r2;
  35483. result.found = true;
  35484. return result;
  35485. }
  35486. return result;
  35487. };
  35488. })();
  35489. var Collider = (function () {
  35490. function Collider() {
  35491. this.radius = new BABYLON.Vector3(1, 1, 1);
  35492. this.retry = 0;
  35493. this.basePointWorld = BABYLON.Vector3.Zero();
  35494. this.velocityWorld = BABYLON.Vector3.Zero();
  35495. this.normalizedVelocity = BABYLON.Vector3.Zero();
  35496. this._collisionPoint = BABYLON.Vector3.Zero();
  35497. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  35498. this._tempVector = BABYLON.Vector3.Zero();
  35499. this._tempVector2 = BABYLON.Vector3.Zero();
  35500. this._tempVector3 = BABYLON.Vector3.Zero();
  35501. this._tempVector4 = BABYLON.Vector3.Zero();
  35502. this._edge = BABYLON.Vector3.Zero();
  35503. this._baseToVertex = BABYLON.Vector3.Zero();
  35504. this._destinationPoint = BABYLON.Vector3.Zero();
  35505. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  35506. this._displacementVector = BABYLON.Vector3.Zero();
  35507. this._collisionMask = -1;
  35508. }
  35509. Object.defineProperty(Collider.prototype, "collisionMask", {
  35510. get: function () {
  35511. return this._collisionMask;
  35512. },
  35513. set: function (mask) {
  35514. this._collisionMask = !isNaN(mask) ? mask : -1;
  35515. },
  35516. enumerable: true,
  35517. configurable: true
  35518. });
  35519. // Methods
  35520. Collider.prototype._initialize = function (source, dir, e) {
  35521. this.velocity = dir;
  35522. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  35523. this.basePoint = source;
  35524. source.multiplyToRef(this.radius, this.basePointWorld);
  35525. dir.multiplyToRef(this.radius, this.velocityWorld);
  35526. this.velocityWorldLength = this.velocityWorld.length();
  35527. this.epsilon = e;
  35528. this.collisionFound = false;
  35529. };
  35530. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  35531. pa.subtractToRef(point, this._tempVector);
  35532. pb.subtractToRef(point, this._tempVector2);
  35533. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  35534. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  35535. if (d < 0)
  35536. return false;
  35537. pc.subtractToRef(point, this._tempVector3);
  35538. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  35539. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  35540. if (d < 0)
  35541. return false;
  35542. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  35543. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  35544. return d >= 0;
  35545. };
  35546. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  35547. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  35548. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  35549. if (distance > this.velocityWorldLength + max + sphereRadius) {
  35550. return false;
  35551. }
  35552. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  35553. return false;
  35554. return true;
  35555. };
  35556. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  35557. var t0;
  35558. var embeddedInPlane = false;
  35559. //defensive programming, actually not needed.
  35560. if (!trianglePlaneArray) {
  35561. trianglePlaneArray = [];
  35562. }
  35563. if (!trianglePlaneArray[faceIndex]) {
  35564. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  35565. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  35566. }
  35567. var trianglePlane = trianglePlaneArray[faceIndex];
  35568. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  35569. return;
  35570. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  35571. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  35572. if (normalDotVelocity == 0) {
  35573. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  35574. return;
  35575. embeddedInPlane = true;
  35576. t0 = 0;
  35577. }
  35578. else {
  35579. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  35580. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  35581. if (t0 > t1) {
  35582. var temp = t1;
  35583. t1 = t0;
  35584. t0 = temp;
  35585. }
  35586. if (t0 > 1.0 || t1 < 0.0)
  35587. return;
  35588. if (t0 < 0)
  35589. t0 = 0;
  35590. if (t0 > 1.0)
  35591. t0 = 1.0;
  35592. }
  35593. this._collisionPoint.copyFromFloats(0, 0, 0);
  35594. var found = false;
  35595. var t = 1.0;
  35596. if (!embeddedInPlane) {
  35597. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  35598. this.velocity.scaleToRef(t0, this._tempVector);
  35599. this._planeIntersectionPoint.addInPlace(this._tempVector);
  35600. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  35601. found = true;
  35602. t = t0;
  35603. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  35604. }
  35605. }
  35606. if (!found) {
  35607. var velocitySquaredLength = this.velocity.lengthSquared();
  35608. var a = velocitySquaredLength;
  35609. this.basePoint.subtractToRef(p1, this._tempVector);
  35610. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  35611. var c = this._tempVector.lengthSquared() - 1.0;
  35612. var lowestRoot = getLowestRoot(a, b, c, t);
  35613. if (lowestRoot.found) {
  35614. t = lowestRoot.root;
  35615. found = true;
  35616. this._collisionPoint.copyFrom(p1);
  35617. }
  35618. this.basePoint.subtractToRef(p2, this._tempVector);
  35619. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  35620. c = this._tempVector.lengthSquared() - 1.0;
  35621. lowestRoot = getLowestRoot(a, b, c, t);
  35622. if (lowestRoot.found) {
  35623. t = lowestRoot.root;
  35624. found = true;
  35625. this._collisionPoint.copyFrom(p2);
  35626. }
  35627. this.basePoint.subtractToRef(p3, this._tempVector);
  35628. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  35629. c = this._tempVector.lengthSquared() - 1.0;
  35630. lowestRoot = getLowestRoot(a, b, c, t);
  35631. if (lowestRoot.found) {
  35632. t = lowestRoot.root;
  35633. found = true;
  35634. this._collisionPoint.copyFrom(p3);
  35635. }
  35636. p2.subtractToRef(p1, this._edge);
  35637. p1.subtractToRef(this.basePoint, this._baseToVertex);
  35638. var edgeSquaredLength = this._edge.lengthSquared();
  35639. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  35640. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  35641. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  35642. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  35643. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  35644. lowestRoot = getLowestRoot(a, b, c, t);
  35645. if (lowestRoot.found) {
  35646. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  35647. if (f >= 0.0 && f <= 1.0) {
  35648. t = lowestRoot.root;
  35649. found = true;
  35650. this._edge.scaleInPlace(f);
  35651. p1.addToRef(this._edge, this._collisionPoint);
  35652. }
  35653. }
  35654. p3.subtractToRef(p2, this._edge);
  35655. p2.subtractToRef(this.basePoint, this._baseToVertex);
  35656. edgeSquaredLength = this._edge.lengthSquared();
  35657. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  35658. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  35659. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  35660. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  35661. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  35662. lowestRoot = getLowestRoot(a, b, c, t);
  35663. if (lowestRoot.found) {
  35664. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  35665. if (f >= 0.0 && f <= 1.0) {
  35666. t = lowestRoot.root;
  35667. found = true;
  35668. this._edge.scaleInPlace(f);
  35669. p2.addToRef(this._edge, this._collisionPoint);
  35670. }
  35671. }
  35672. p1.subtractToRef(p3, this._edge);
  35673. p3.subtractToRef(this.basePoint, this._baseToVertex);
  35674. edgeSquaredLength = this._edge.lengthSquared();
  35675. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  35676. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  35677. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  35678. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  35679. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  35680. lowestRoot = getLowestRoot(a, b, c, t);
  35681. if (lowestRoot.found) {
  35682. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  35683. if (f >= 0.0 && f <= 1.0) {
  35684. t = lowestRoot.root;
  35685. found = true;
  35686. this._edge.scaleInPlace(f);
  35687. p3.addToRef(this._edge, this._collisionPoint);
  35688. }
  35689. }
  35690. }
  35691. if (found) {
  35692. var distToCollision = t * this.velocity.length();
  35693. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  35694. if (!this.intersectionPoint) {
  35695. this.intersectionPoint = this._collisionPoint.clone();
  35696. }
  35697. else {
  35698. this.intersectionPoint.copyFrom(this._collisionPoint);
  35699. }
  35700. this.nearestDistance = distToCollision;
  35701. this.collisionFound = true;
  35702. }
  35703. }
  35704. };
  35705. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  35706. for (var i = indexStart; i < indexEnd; i += 3) {
  35707. var p1 = pts[indices[i] - decal];
  35708. var p2 = pts[indices[i + 1] - decal];
  35709. var p3 = pts[indices[i + 2] - decal];
  35710. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  35711. }
  35712. };
  35713. Collider.prototype._getResponse = function (pos, vel) {
  35714. pos.addToRef(vel, this._destinationPoint);
  35715. vel.scaleInPlace((this.nearestDistance / vel.length()));
  35716. this.basePoint.addToRef(vel, pos);
  35717. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  35718. this._slidePlaneNormal.normalize();
  35719. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  35720. pos.addInPlace(this._displacementVector);
  35721. this.intersectionPoint.addInPlace(this._displacementVector);
  35722. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  35723. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  35724. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  35725. };
  35726. return Collider;
  35727. }());
  35728. BABYLON.Collider = Collider;
  35729. })(BABYLON || (BABYLON = {}));
  35730. //# sourceMappingURL=babylon.collider.js.map
  35731. var BABYLON;
  35732. (function (BABYLON) {
  35733. //WebWorker code will be inserted to this variable.
  35734. BABYLON.CollisionWorker = "";
  35735. var WorkerTaskType;
  35736. (function (WorkerTaskType) {
  35737. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  35738. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  35739. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  35740. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  35741. var WorkerReplyType;
  35742. (function (WorkerReplyType) {
  35743. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  35744. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  35745. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  35746. var CollisionCoordinatorWorker = (function () {
  35747. function CollisionCoordinatorWorker() {
  35748. var _this = this;
  35749. this._scaledPosition = BABYLON.Vector3.Zero();
  35750. this._scaledVelocity = BABYLON.Vector3.Zero();
  35751. this.onMeshUpdated = function (mesh) {
  35752. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  35753. };
  35754. this.onGeometryUpdated = function (geometry) {
  35755. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  35756. };
  35757. this._afterRender = function () {
  35758. if (!_this._init)
  35759. return;
  35760. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  35761. return;
  35762. }
  35763. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  35764. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  35765. if (_this._runningUpdated > 4) {
  35766. return;
  35767. }
  35768. ++_this._runningUpdated;
  35769. var payload = {
  35770. updatedMeshes: _this._addUpdateMeshesList,
  35771. updatedGeometries: _this._addUpdateGeometriesList,
  35772. removedGeometries: _this._toRemoveGeometryArray,
  35773. removedMeshes: _this._toRemoveMeshesArray
  35774. };
  35775. var message = {
  35776. payload: payload,
  35777. taskType: WorkerTaskType.UPDATE
  35778. };
  35779. var serializable = [];
  35780. for (var id in payload.updatedGeometries) {
  35781. if (payload.updatedGeometries.hasOwnProperty(id)) {
  35782. //prepare transferables
  35783. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  35784. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  35785. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  35786. }
  35787. }
  35788. _this._worker.postMessage(message, serializable);
  35789. _this._addUpdateMeshesList = {};
  35790. _this._addUpdateGeometriesList = {};
  35791. _this._toRemoveGeometryArray = [];
  35792. _this._toRemoveMeshesArray = [];
  35793. };
  35794. this._onMessageFromWorker = function (e) {
  35795. var returnData = e.data;
  35796. if (returnData.error != WorkerReplyType.SUCCESS) {
  35797. //TODO what errors can be returned from the worker?
  35798. BABYLON.Tools.Warn("error returned from worker!");
  35799. return;
  35800. }
  35801. switch (returnData.taskType) {
  35802. case WorkerTaskType.INIT:
  35803. _this._init = true;
  35804. //Update the worked with ALL of the scene's current state
  35805. _this._scene.meshes.forEach(function (mesh) {
  35806. _this.onMeshAdded(mesh);
  35807. });
  35808. _this._scene.getGeometries().forEach(function (geometry) {
  35809. _this.onGeometryAdded(geometry);
  35810. });
  35811. break;
  35812. case WorkerTaskType.UPDATE:
  35813. _this._runningUpdated--;
  35814. break;
  35815. case WorkerTaskType.COLLIDE:
  35816. _this._runningCollisionTask = false;
  35817. var returnPayload = returnData.payload;
  35818. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  35819. return;
  35820. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  35821. //cleanup
  35822. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  35823. break;
  35824. }
  35825. };
  35826. this._collisionsCallbackArray = [];
  35827. this._init = false;
  35828. this._runningUpdated = 0;
  35829. this._runningCollisionTask = false;
  35830. this._addUpdateMeshesList = {};
  35831. this._addUpdateGeometriesList = {};
  35832. this._toRemoveGeometryArray = [];
  35833. this._toRemoveMeshesArray = [];
  35834. }
  35835. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  35836. if (!this._init)
  35837. return;
  35838. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  35839. return;
  35840. position.divideToRef(collider.radius, this._scaledPosition);
  35841. velocity.divideToRef(collider.radius, this._scaledVelocity);
  35842. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  35843. var payload = {
  35844. collider: {
  35845. position: this._scaledPosition.asArray(),
  35846. velocity: this._scaledVelocity.asArray(),
  35847. radius: collider.radius.asArray()
  35848. },
  35849. collisionId: collisionIndex,
  35850. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  35851. maximumRetry: maximumRetry
  35852. };
  35853. var message = {
  35854. payload: payload,
  35855. taskType: WorkerTaskType.COLLIDE
  35856. };
  35857. this._worker.postMessage(message);
  35858. };
  35859. CollisionCoordinatorWorker.prototype.init = function (scene) {
  35860. this._scene = scene;
  35861. this._scene.registerAfterRender(this._afterRender);
  35862. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  35863. this._worker = new Worker(workerUrl);
  35864. this._worker.onmessage = this._onMessageFromWorker;
  35865. var message = {
  35866. payload: {},
  35867. taskType: WorkerTaskType.INIT
  35868. };
  35869. this._worker.postMessage(message);
  35870. };
  35871. CollisionCoordinatorWorker.prototype.destroy = function () {
  35872. this._scene.unregisterAfterRender(this._afterRender);
  35873. this._worker.terminate();
  35874. };
  35875. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  35876. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  35877. this.onMeshUpdated(mesh);
  35878. };
  35879. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  35880. this._toRemoveMeshesArray.push(mesh.uniqueId);
  35881. };
  35882. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  35883. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  35884. geometry.onGeometryUpdated = this.onGeometryUpdated;
  35885. this.onGeometryUpdated(geometry);
  35886. };
  35887. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  35888. this._toRemoveGeometryArray.push(geometry.id);
  35889. };
  35890. return CollisionCoordinatorWorker;
  35891. }());
  35892. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  35893. var submeshes = [];
  35894. if (mesh.subMeshes) {
  35895. submeshes = mesh.subMeshes.map(function (sm, idx) {
  35896. return {
  35897. position: idx,
  35898. verticesStart: sm.verticesStart,
  35899. verticesCount: sm.verticesCount,
  35900. indexStart: sm.indexStart,
  35901. indexCount: sm.indexCount,
  35902. hasMaterial: !!sm.getMaterial(),
  35903. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  35904. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  35905. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  35906. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  35907. };
  35908. });
  35909. }
  35910. var geometryId = null;
  35911. if (mesh instanceof BABYLON.Mesh) {
  35912. geometryId = mesh.geometry ? mesh.geometry.id : null;
  35913. }
  35914. else if (mesh instanceof BABYLON.InstancedMesh) {
  35915. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  35916. }
  35917. return {
  35918. uniqueId: mesh.uniqueId,
  35919. id: mesh.id,
  35920. name: mesh.name,
  35921. geometryId: geometryId,
  35922. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  35923. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  35924. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  35925. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  35926. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  35927. subMeshes: submeshes,
  35928. checkCollisions: mesh.checkCollisions
  35929. };
  35930. };
  35931. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  35932. return {
  35933. id: geometry.id,
  35934. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  35935. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  35936. indices: new Uint32Array(geometry.getIndices() || []),
  35937. };
  35938. };
  35939. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  35940. var CollisionCoordinatorLegacy = (function () {
  35941. function CollisionCoordinatorLegacy() {
  35942. this._scaledPosition = BABYLON.Vector3.Zero();
  35943. this._scaledVelocity = BABYLON.Vector3.Zero();
  35944. this._finalPosition = BABYLON.Vector3.Zero();
  35945. }
  35946. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  35947. position.divideToRef(collider.radius, this._scaledPosition);
  35948. velocity.divideToRef(collider.radius, this._scaledVelocity);
  35949. collider.collidedMesh = null;
  35950. collider.retry = 0;
  35951. collider.initialVelocity = this._scaledVelocity;
  35952. collider.initialPosition = this._scaledPosition;
  35953. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  35954. this._finalPosition.multiplyInPlace(collider.radius);
  35955. //run the callback
  35956. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  35957. };
  35958. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  35959. this._scene = scene;
  35960. };
  35961. CollisionCoordinatorLegacy.prototype.destroy = function () {
  35962. //Legacy need no destruction method.
  35963. };
  35964. //No update in legacy mode
  35965. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  35966. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  35967. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  35968. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  35969. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  35970. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  35971. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  35972. if (excludedMesh === void 0) { excludedMesh = null; }
  35973. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  35974. if (collider.retry >= maximumRetry) {
  35975. finalPosition.copyFrom(position);
  35976. return;
  35977. }
  35978. // Check if this is a mesh else camera or -1
  35979. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  35980. collider._initialize(position, velocity, closeDistance);
  35981. // Check all meshes
  35982. for (var index = 0; index < this._scene.meshes.length; index++) {
  35983. var mesh = this._scene.meshes[index];
  35984. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  35985. mesh._checkCollision(collider);
  35986. }
  35987. }
  35988. if (!collider.collisionFound) {
  35989. position.addToRef(velocity, finalPosition);
  35990. return;
  35991. }
  35992. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  35993. collider._getResponse(position, velocity);
  35994. }
  35995. if (velocity.length() <= closeDistance) {
  35996. finalPosition.copyFrom(position);
  35997. return;
  35998. }
  35999. collider.retry++;
  36000. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  36001. };
  36002. return CollisionCoordinatorLegacy;
  36003. }());
  36004. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  36005. })(BABYLON || (BABYLON = {}));
  36006. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  36007. var BABYLON;
  36008. (function (BABYLON) {
  36009. var Particle = (function () {
  36010. function Particle() {
  36011. this.position = BABYLON.Vector3.Zero();
  36012. this.direction = BABYLON.Vector3.Zero();
  36013. this.color = new BABYLON.Color4(0, 0, 0, 0);
  36014. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  36015. this.lifeTime = 1.0;
  36016. this.age = 0;
  36017. this.size = 0;
  36018. this.angle = 0;
  36019. this.angularSpeed = 0;
  36020. }
  36021. Particle.prototype.copyTo = function (other) {
  36022. other.position.copyFrom(this.position);
  36023. other.direction.copyFrom(this.direction);
  36024. other.color.copyFrom(this.color);
  36025. other.colorStep.copyFrom(this.colorStep);
  36026. other.lifeTime = this.lifeTime;
  36027. other.age = this.age;
  36028. other.size = this.size;
  36029. other.angle = this.angle;
  36030. other.angularSpeed = this.angularSpeed;
  36031. };
  36032. return Particle;
  36033. }());
  36034. BABYLON.Particle = Particle;
  36035. })(BABYLON || (BABYLON = {}));
  36036. //# sourceMappingURL=babylon.particle.js.map
  36037. var BABYLON;
  36038. (function (BABYLON) {
  36039. var randomNumber = function (min, max) {
  36040. if (min === max) {
  36041. return (min);
  36042. }
  36043. var random = Math.random();
  36044. return ((random * (max - min)) + min);
  36045. };
  36046. var ParticleSystem = (function () {
  36047. function ParticleSystem(name, capacity, scene, customEffect) {
  36048. var _this = this;
  36049. this.name = name;
  36050. // Members
  36051. this.animations = [];
  36052. this.renderingGroupId = 0;
  36053. this.emitter = null;
  36054. this.emitRate = 10;
  36055. this.manualEmitCount = -1;
  36056. this.updateSpeed = 0.01;
  36057. this.targetStopDuration = 0;
  36058. this.disposeOnStop = false;
  36059. this.minEmitPower = 1;
  36060. this.maxEmitPower = 1;
  36061. this.minLifeTime = 1;
  36062. this.maxLifeTime = 1;
  36063. this.minSize = 1;
  36064. this.maxSize = 1;
  36065. this.minAngularSpeed = 0;
  36066. this.maxAngularSpeed = 0;
  36067. this.layerMask = 0x0FFFFFFF;
  36068. this.customShader = null;
  36069. this.preventAutoStart = false;
  36070. /**
  36071. * An event triggered when the system is disposed.
  36072. * @type {BABYLON.Observable}
  36073. */
  36074. this.onDisposeObservable = new BABYLON.Observable();
  36075. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  36076. this.forceDepthWrite = false;
  36077. this.gravity = BABYLON.Vector3.Zero();
  36078. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  36079. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  36080. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  36081. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  36082. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  36083. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  36084. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  36085. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  36086. this.particles = new Array();
  36087. this._stockParticles = new Array();
  36088. this._newPartsExcess = 0;
  36089. this._vertexBuffers = {};
  36090. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  36091. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  36092. this._scaledDirection = BABYLON.Vector3.Zero();
  36093. this._scaledGravity = BABYLON.Vector3.Zero();
  36094. this._currentRenderId = -1;
  36095. this._started = false;
  36096. this._stopped = false;
  36097. this._actualFrame = 0;
  36098. this.id = name;
  36099. this._capacity = capacity;
  36100. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36101. this._customEffect = customEffect;
  36102. scene.particleSystems.push(this);
  36103. var indices = [];
  36104. var index = 0;
  36105. for (var count = 0; count < capacity; count++) {
  36106. indices.push(index);
  36107. indices.push(index + 1);
  36108. indices.push(index + 2);
  36109. indices.push(index);
  36110. indices.push(index + 2);
  36111. indices.push(index + 3);
  36112. index += 4;
  36113. }
  36114. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  36115. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  36116. this._vertexData = new Float32Array(capacity * 11 * 4);
  36117. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  36118. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  36119. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  36120. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  36121. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  36122. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  36123. this._vertexBuffers["options"] = options;
  36124. // Default behaviors
  36125. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  36126. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  36127. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  36128. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  36129. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  36130. };
  36131. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  36132. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  36133. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  36134. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  36135. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  36136. };
  36137. this.updateFunction = function (particles) {
  36138. for (var index = 0; index < particles.length; index++) {
  36139. var particle = particles[index];
  36140. particle.age += _this._scaledUpdateSpeed;
  36141. if (particle.age >= particle.lifeTime) {
  36142. _this.recycleParticle(particle);
  36143. index--;
  36144. continue;
  36145. }
  36146. else {
  36147. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  36148. particle.color.addInPlace(_this._scaledColorStep);
  36149. if (particle.color.a < 0)
  36150. particle.color.a = 0;
  36151. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  36152. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  36153. particle.position.addInPlace(_this._scaledDirection);
  36154. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  36155. particle.direction.addInPlace(_this._scaledGravity);
  36156. }
  36157. }
  36158. };
  36159. }
  36160. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  36161. set: function (callback) {
  36162. if (this._onDisposeObserver) {
  36163. this.onDisposeObservable.remove(this._onDisposeObserver);
  36164. }
  36165. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36166. },
  36167. enumerable: true,
  36168. configurable: true
  36169. });
  36170. ParticleSystem.prototype.recycleParticle = function (particle) {
  36171. var lastParticle = this.particles.pop();
  36172. if (lastParticle !== particle) {
  36173. lastParticle.copyTo(particle);
  36174. this._stockParticles.push(lastParticle);
  36175. }
  36176. };
  36177. ParticleSystem.prototype.getCapacity = function () {
  36178. return this._capacity;
  36179. };
  36180. ParticleSystem.prototype.isAlive = function () {
  36181. return this._alive;
  36182. };
  36183. ParticleSystem.prototype.isStarted = function () {
  36184. return this._started;
  36185. };
  36186. ParticleSystem.prototype.start = function () {
  36187. this._started = true;
  36188. this._stopped = false;
  36189. this._actualFrame = 0;
  36190. };
  36191. ParticleSystem.prototype.stop = function () {
  36192. this._stopped = true;
  36193. };
  36194. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  36195. var offset = index * 11;
  36196. this._vertexData[offset] = particle.position.x;
  36197. this._vertexData[offset + 1] = particle.position.y;
  36198. this._vertexData[offset + 2] = particle.position.z;
  36199. this._vertexData[offset + 3] = particle.color.r;
  36200. this._vertexData[offset + 4] = particle.color.g;
  36201. this._vertexData[offset + 5] = particle.color.b;
  36202. this._vertexData[offset + 6] = particle.color.a;
  36203. this._vertexData[offset + 7] = particle.angle;
  36204. this._vertexData[offset + 8] = particle.size;
  36205. this._vertexData[offset + 9] = offsetX;
  36206. this._vertexData[offset + 10] = offsetY;
  36207. };
  36208. ParticleSystem.prototype._update = function (newParticles) {
  36209. // Update current
  36210. this._alive = this.particles.length > 0;
  36211. this.updateFunction(this.particles);
  36212. // Add new ones
  36213. var worldMatrix;
  36214. if (this.emitter.position) {
  36215. worldMatrix = this.emitter.getWorldMatrix();
  36216. }
  36217. else {
  36218. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  36219. }
  36220. var particle;
  36221. for (var index = 0; index < newParticles; index++) {
  36222. if (this.particles.length === this._capacity) {
  36223. break;
  36224. }
  36225. if (this._stockParticles.length !== 0) {
  36226. particle = this._stockParticles.pop();
  36227. particle.age = 0;
  36228. }
  36229. else {
  36230. particle = new BABYLON.Particle();
  36231. }
  36232. this.particles.push(particle);
  36233. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  36234. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  36235. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  36236. particle.size = randomNumber(this.minSize, this.maxSize);
  36237. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  36238. this.startPositionFunction(worldMatrix, particle.position, particle);
  36239. var step = randomNumber(0, 1.0);
  36240. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  36241. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  36242. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  36243. }
  36244. };
  36245. ParticleSystem.prototype._getEffect = function () {
  36246. if (this._customEffect) {
  36247. return this._customEffect;
  36248. }
  36249. ;
  36250. var defines = [];
  36251. if (this._scene.clipPlane) {
  36252. defines.push("#define CLIPPLANE");
  36253. }
  36254. // Effect
  36255. var join = defines.join("\n");
  36256. if (this._cachedDefines !== join) {
  36257. this._cachedDefines = join;
  36258. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  36259. }
  36260. return this._effect;
  36261. };
  36262. ParticleSystem.prototype.animate = function () {
  36263. if (!this._started)
  36264. return;
  36265. var effect = this._getEffect();
  36266. // Check
  36267. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  36268. return;
  36269. if (this._currentRenderId === this._scene.getRenderId()) {
  36270. return;
  36271. }
  36272. this._currentRenderId = this._scene.getRenderId();
  36273. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  36274. // determine the number of particles we need to create
  36275. var newParticles;
  36276. if (this.manualEmitCount > -1) {
  36277. newParticles = this.manualEmitCount;
  36278. this._newPartsExcess = 0;
  36279. this.manualEmitCount = 0;
  36280. }
  36281. else {
  36282. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  36283. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  36284. }
  36285. if (this._newPartsExcess > 1.0) {
  36286. newParticles += this._newPartsExcess >> 0;
  36287. this._newPartsExcess -= this._newPartsExcess >> 0;
  36288. }
  36289. this._alive = false;
  36290. if (!this._stopped) {
  36291. this._actualFrame += this._scaledUpdateSpeed;
  36292. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  36293. this.stop();
  36294. }
  36295. else {
  36296. newParticles = 0;
  36297. }
  36298. this._update(newParticles);
  36299. // Stopped?
  36300. if (this._stopped) {
  36301. if (!this._alive) {
  36302. this._started = false;
  36303. if (this.disposeOnStop) {
  36304. this._scene._toBeDisposed.push(this);
  36305. }
  36306. }
  36307. }
  36308. // Update VBO
  36309. var offset = 0;
  36310. for (var index = 0; index < this.particles.length; index++) {
  36311. var particle = this.particles[index];
  36312. this._appendParticleVertex(offset++, particle, 0, 0);
  36313. this._appendParticleVertex(offset++, particle, 1, 0);
  36314. this._appendParticleVertex(offset++, particle, 1, 1);
  36315. this._appendParticleVertex(offset++, particle, 0, 1);
  36316. }
  36317. this._vertexBuffer.update(this._vertexData);
  36318. };
  36319. ParticleSystem.prototype.render = function () {
  36320. var effect = this._getEffect();
  36321. // Check
  36322. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  36323. return 0;
  36324. var engine = this._scene.getEngine();
  36325. // Render
  36326. engine.enableEffect(effect);
  36327. engine.setState(false);
  36328. var viewMatrix = this._scene.getViewMatrix();
  36329. effect.setTexture("diffuseSampler", this.particleTexture);
  36330. effect.setMatrix("view", viewMatrix);
  36331. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  36332. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  36333. if (this._scene.clipPlane) {
  36334. var clipPlane = this._scene.clipPlane;
  36335. var invView = viewMatrix.clone();
  36336. invView.invert();
  36337. effect.setMatrix("invView", invView);
  36338. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  36339. }
  36340. // VBOs
  36341. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36342. // Draw order
  36343. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  36344. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  36345. }
  36346. else {
  36347. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36348. }
  36349. if (this.forceDepthWrite) {
  36350. engine.setDepthWrite(true);
  36351. }
  36352. engine.draw(true, 0, this.particles.length * 6);
  36353. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36354. return this.particles.length;
  36355. };
  36356. ParticleSystem.prototype.dispose = function () {
  36357. if (this._vertexBuffer) {
  36358. this._vertexBuffer.dispose();
  36359. this._vertexBuffer = null;
  36360. }
  36361. if (this._indexBuffer) {
  36362. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36363. this._indexBuffer = null;
  36364. }
  36365. if (this.particleTexture) {
  36366. this.particleTexture.dispose();
  36367. this.particleTexture = null;
  36368. }
  36369. // Remove from scene
  36370. var index = this._scene.particleSystems.indexOf(this);
  36371. this._scene.particleSystems.splice(index, 1);
  36372. // Callback
  36373. this.onDisposeObservable.notifyObservers(this);
  36374. this.onDisposeObservable.clear();
  36375. };
  36376. // Clone
  36377. ParticleSystem.prototype.clone = function (name, newEmitter) {
  36378. var custom = null;
  36379. var program = null;
  36380. if (this.customShader != null) {
  36381. program = this.customShader;
  36382. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  36383. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  36384. }
  36385. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  36386. result.customShader = program;
  36387. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  36388. if (newEmitter === undefined) {
  36389. newEmitter = this.emitter;
  36390. }
  36391. result.emitter = newEmitter;
  36392. if (this.particleTexture) {
  36393. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  36394. }
  36395. if (!this.preventAutoStart) {
  36396. result.start();
  36397. }
  36398. return result;
  36399. };
  36400. ParticleSystem.prototype.serialize = function () {
  36401. var serializationObject = {};
  36402. serializationObject.name = this.name;
  36403. serializationObject.id = this.id;
  36404. // Emitter
  36405. if (this.emitter.position) {
  36406. serializationObject.emitterId = this.emitter.id;
  36407. }
  36408. else {
  36409. serializationObject.emitter = this.emitter.asArray();
  36410. }
  36411. serializationObject.capacity = this.getCapacity();
  36412. if (this.particleTexture) {
  36413. serializationObject.textureName = this.particleTexture.name;
  36414. }
  36415. // Animations
  36416. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  36417. // Particle system
  36418. serializationObject.minAngularSpeed = this.minAngularSpeed;
  36419. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  36420. serializationObject.minSize = this.minSize;
  36421. serializationObject.maxSize = this.maxSize;
  36422. serializationObject.minEmitPower = this.minEmitPower;
  36423. serializationObject.maxEmitPower = this.maxEmitPower;
  36424. serializationObject.minLifeTime = this.minLifeTime;
  36425. serializationObject.maxLifeTime = this.maxLifeTime;
  36426. serializationObject.emitRate = this.emitRate;
  36427. serializationObject.minEmitBox = this.minEmitBox.asArray();
  36428. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  36429. serializationObject.gravity = this.gravity.asArray();
  36430. serializationObject.direction1 = this.direction1.asArray();
  36431. serializationObject.direction2 = this.direction2.asArray();
  36432. serializationObject.color1 = this.color1.asArray();
  36433. serializationObject.color2 = this.color2.asArray();
  36434. serializationObject.colorDead = this.colorDead.asArray();
  36435. serializationObject.updateSpeed = this.updateSpeed;
  36436. serializationObject.targetStopDuration = this.targetStopDuration;
  36437. serializationObject.textureMask = this.textureMask.asArray();
  36438. serializationObject.blendMode = this.blendMode;
  36439. serializationObject.customShader = this.customShader;
  36440. serializationObject.preventAutoStart = this.preventAutoStart;
  36441. return serializationObject;
  36442. };
  36443. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  36444. var name = parsedParticleSystem.name;
  36445. var custom = null;
  36446. var program = null;
  36447. if (parsedParticleSystem.customShader) {
  36448. program = parsedParticleSystem.customShader;
  36449. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  36450. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  36451. }
  36452. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  36453. particleSystem.customShader = program;
  36454. if (parsedParticleSystem.id) {
  36455. particleSystem.id = parsedParticleSystem.id;
  36456. }
  36457. // Auto start
  36458. if (parsedParticleSystem.preventAutoStart) {
  36459. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  36460. }
  36461. // Texture
  36462. if (parsedParticleSystem.textureName) {
  36463. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  36464. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  36465. }
  36466. // Emitter
  36467. if (parsedParticleSystem.emitterId) {
  36468. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  36469. }
  36470. else {
  36471. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  36472. }
  36473. // Animations
  36474. if (parsedParticleSystem.animations) {
  36475. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  36476. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  36477. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  36478. }
  36479. }
  36480. if (parsedParticleSystem.autoAnimate) {
  36481. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  36482. }
  36483. // Particle system
  36484. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  36485. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  36486. particleSystem.minSize = parsedParticleSystem.minSize;
  36487. particleSystem.maxSize = parsedParticleSystem.maxSize;
  36488. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  36489. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  36490. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  36491. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  36492. particleSystem.emitRate = parsedParticleSystem.emitRate;
  36493. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  36494. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  36495. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  36496. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  36497. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  36498. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  36499. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  36500. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  36501. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  36502. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  36503. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  36504. particleSystem.blendMode = parsedParticleSystem.blendMode;
  36505. if (!particleSystem.preventAutoStart) {
  36506. particleSystem.start();
  36507. }
  36508. return particleSystem;
  36509. };
  36510. return ParticleSystem;
  36511. }());
  36512. // Statics
  36513. ParticleSystem.BLENDMODE_ONEONE = 0;
  36514. ParticleSystem.BLENDMODE_STANDARD = 1;
  36515. BABYLON.ParticleSystem = ParticleSystem;
  36516. })(BABYLON || (BABYLON = {}));
  36517. //# sourceMappingURL=babylon.particleSystem.js.map
  36518. var BABYLON;
  36519. (function (BABYLON) {
  36520. var SolidParticle = (function () {
  36521. /**
  36522. * Creates a Solid Particle object.
  36523. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  36524. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  36525. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  36526. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  36527. * `shapeId` (integer) is the model shape identifier in the SPS.
  36528. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  36529. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  36530. */
  36531. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  36532. this.idx = 0; // particle global index
  36533. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  36534. this.position = BABYLON.Vector3.Zero(); // position
  36535. this.rotation = BABYLON.Vector3.Zero(); // rotation
  36536. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  36537. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  36538. this.velocity = BABYLON.Vector3.Zero(); // velocity
  36539. this.alive = true; // alive
  36540. this.isVisible = true; // visibility
  36541. this._pos = 0; // index of this particle in the global "positions" array
  36542. this.shapeId = 0; // model shape id
  36543. this.idxInShape = 0; // index of the particle in its shape id
  36544. this.idx = particleIndex;
  36545. this._pos = positionIndex;
  36546. this._model = model;
  36547. this.shapeId = shapeId;
  36548. this.idxInShape = idxInShape;
  36549. this._sps = sps;
  36550. if (modelBoundingInfo) {
  36551. this._modelBoundingInfo = modelBoundingInfo;
  36552. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  36553. }
  36554. }
  36555. Object.defineProperty(SolidParticle.prototype, "scale", {
  36556. /**
  36557. * legacy support, changed scale to scaling
  36558. */
  36559. get: function () {
  36560. return this.scaling;
  36561. },
  36562. set: function (scale) {
  36563. this.scaling = scale;
  36564. },
  36565. enumerable: true,
  36566. configurable: true
  36567. });
  36568. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  36569. /**
  36570. * legacy support, changed quaternion to rotationQuaternion
  36571. */
  36572. get: function () {
  36573. return this.rotationQuaternion;
  36574. },
  36575. set: function (q) {
  36576. this.rotationQuaternion = q;
  36577. },
  36578. enumerable: true,
  36579. configurable: true
  36580. });
  36581. /**
  36582. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  36583. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  36584. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  36585. */
  36586. SolidParticle.prototype.intersectsMesh = function (target) {
  36587. if (!this._boundingInfo || !target._boundingInfo) {
  36588. return false;
  36589. }
  36590. if (this._sps._bSphereOnly) {
  36591. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  36592. }
  36593. return this._boundingInfo.intersects(target._boundingInfo, false);
  36594. };
  36595. return SolidParticle;
  36596. }());
  36597. BABYLON.SolidParticle = SolidParticle;
  36598. var ModelShape = (function () {
  36599. /**
  36600. * 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.
  36601. * SPS internal tool, don't use it manually.
  36602. */
  36603. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  36604. this.shapeID = id;
  36605. this._shape = shape;
  36606. this._shapeUV = shapeUV;
  36607. this._positionFunction = posFunction;
  36608. this._vertexFunction = vtxFunction;
  36609. }
  36610. return ModelShape;
  36611. }());
  36612. BABYLON.ModelShape = ModelShape;
  36613. })(BABYLON || (BABYLON = {}));
  36614. //# sourceMappingURL=babylon.solidParticle.js.map
  36615. var BABYLON;
  36616. (function (BABYLON) {
  36617. /**
  36618. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  36619. */
  36620. var SolidParticleSystem = (function () {
  36621. /**
  36622. * Creates a SPS (Solid Particle System) object.
  36623. * `name` (String) is the SPS name, this will be the underlying mesh name.
  36624. * `scene` (Scene) is the scene in which the SPS is added.
  36625. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  36626. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  36627. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  36628. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  36629. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  36630. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  36631. */
  36632. function SolidParticleSystem(name, scene, options) {
  36633. // public members
  36634. /**
  36635. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  36636. * Example : var p = SPS.particles[i];
  36637. */
  36638. this.particles = new Array();
  36639. /**
  36640. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  36641. */
  36642. this.nbParticles = 0;
  36643. /**
  36644. * If the particles must ever face the camera (default false). Useful for planar particles.
  36645. */
  36646. this.billboard = false;
  36647. /**
  36648. * Recompute normals when adding a shape
  36649. */
  36650. this.recomputeNormals = true;
  36651. /**
  36652. * This a counter ofr your own usage. It's not set by any SPS functions.
  36653. */
  36654. this.counter = 0;
  36655. /**
  36656. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  36657. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  36658. */
  36659. this.vars = {};
  36660. this._positions = new Array();
  36661. this._indices = new Array();
  36662. this._normals = new Array();
  36663. this._colors = new Array();
  36664. this._uvs = new Array();
  36665. this._index = 0; // indices index
  36666. this._updatable = true;
  36667. this._pickable = false;
  36668. this._isVisibilityBoxLocked = false;
  36669. this._alwaysVisible = false;
  36670. this._shapeCounter = 0;
  36671. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  36672. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36673. this._computeParticleColor = true;
  36674. this._computeParticleTexture = true;
  36675. this._computeParticleRotation = true;
  36676. this._computeParticleVertex = false;
  36677. this._computeBoundingBox = false;
  36678. this._cam_axisZ = BABYLON.Vector3.Zero();
  36679. this._cam_axisY = BABYLON.Vector3.Zero();
  36680. this._cam_axisX = BABYLON.Vector3.Zero();
  36681. this._axisX = BABYLON.Axis.X;
  36682. this._axisY = BABYLON.Axis.Y;
  36683. this._axisZ = BABYLON.Axis.Z;
  36684. this._camDir = BABYLON.Vector3.Zero();
  36685. this._rotMatrix = new BABYLON.Matrix();
  36686. this._invertMatrix = new BABYLON.Matrix();
  36687. this._rotated = BABYLON.Vector3.Zero();
  36688. this._quaternion = new BABYLON.Quaternion();
  36689. this._vertex = BABYLON.Vector3.Zero();
  36690. this._normal = BABYLON.Vector3.Zero();
  36691. this._yaw = 0.0;
  36692. this._pitch = 0.0;
  36693. this._roll = 0.0;
  36694. this._halfroll = 0.0;
  36695. this._halfpitch = 0.0;
  36696. this._halfyaw = 0.0;
  36697. this._sinRoll = 0.0;
  36698. this._cosRoll = 0.0;
  36699. this._sinPitch = 0.0;
  36700. this._cosPitch = 0.0;
  36701. this._sinYaw = 0.0;
  36702. this._cosYaw = 0.0;
  36703. this._w = 0.0;
  36704. this._mustUnrotateFixedNormals = false;
  36705. this._minimum = BABYLON.Tmp.Vector3[0];
  36706. this._maximum = BABYLON.Tmp.Vector3[1];
  36707. this._scale = BABYLON.Tmp.Vector3[2];
  36708. this._translation = BABYLON.Tmp.Vector3[3];
  36709. this._minBbox = BABYLON.Tmp.Vector3[4];
  36710. this._maxBbox = BABYLON.Tmp.Vector3[5];
  36711. this._particlesIntersect = false;
  36712. this._bSphereOnly = false;
  36713. this._bSphereRadiusFactor = 1.0;
  36714. this.name = name;
  36715. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36716. this._camera = scene.activeCamera;
  36717. this._pickable = options ? options.isPickable : false;
  36718. this._particlesIntersect = options ? options.particleIntersection : false;
  36719. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  36720. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  36721. if (options && options.updatable) {
  36722. this._updatable = options.updatable;
  36723. }
  36724. else {
  36725. this._updatable = true;
  36726. }
  36727. if (this._pickable) {
  36728. this.pickedParticles = [];
  36729. }
  36730. }
  36731. /**
  36732. * Builds the SPS underlying mesh. Returns a standard Mesh.
  36733. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  36734. */
  36735. SolidParticleSystem.prototype.buildMesh = function () {
  36736. if (this.nbParticles === 0) {
  36737. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36738. this.addShape(triangle, 1);
  36739. triangle.dispose();
  36740. }
  36741. this._positions32 = new Float32Array(this._positions);
  36742. this._uvs32 = new Float32Array(this._uvs);
  36743. this._colors32 = new Float32Array(this._colors);
  36744. if (this.recomputeNormals) {
  36745. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36746. }
  36747. this._normals32 = new Float32Array(this._normals);
  36748. this._fixedNormal32 = new Float32Array(this._normals);
  36749. if (this._mustUnrotateFixedNormals) {
  36750. this._unrotateFixedNormals();
  36751. }
  36752. var vertexData = new BABYLON.VertexData();
  36753. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36754. vertexData.indices = this._indices;
  36755. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36756. if (this._uvs32) {
  36757. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36758. ;
  36759. }
  36760. if (this._colors32) {
  36761. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36762. }
  36763. var mesh = new BABYLON.Mesh(this.name, this._scene);
  36764. vertexData.applyToMesh(mesh, this._updatable);
  36765. this.mesh = mesh;
  36766. this.mesh.isPickable = this._pickable;
  36767. // free memory
  36768. this._positions = null;
  36769. this._normals = null;
  36770. this._uvs = null;
  36771. this._colors = null;
  36772. if (!this._updatable) {
  36773. this.particles.length = 0;
  36774. }
  36775. return mesh;
  36776. };
  36777. /**
  36778. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  36779. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  36780. * Thus the particles generated from `digest()` have their property `position` set yet.
  36781. * `mesh` ( Mesh ) is the mesh to be digested
  36782. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  36783. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  36784. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  36785. */
  36786. SolidParticleSystem.prototype.digest = function (mesh, options) {
  36787. var size = (options && options.facetNb) || 1;
  36788. var number = (options && options.number);
  36789. var delta = (options && options.delta) || 0;
  36790. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36791. var meshInd = mesh.getIndices();
  36792. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36793. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36794. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36795. var f = 0; // facet counter
  36796. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  36797. // compute size from number
  36798. if (number) {
  36799. number = (number > totalFacets) ? totalFacets : number;
  36800. size = Math.round(totalFacets / number);
  36801. delta = 0;
  36802. }
  36803. else {
  36804. size = (size > totalFacets) ? totalFacets : size;
  36805. }
  36806. var facetPos = []; // submesh positions
  36807. var facetInd = []; // submesh indices
  36808. var facetUV = []; // submesh UV
  36809. var facetCol = []; // submesh colors
  36810. var barycenter = BABYLON.Tmp.Vector3[0];
  36811. var rand;
  36812. var sizeO = size;
  36813. while (f < totalFacets) {
  36814. size = sizeO + Math.floor((1 + delta) * Math.random());
  36815. if (f > totalFacets - size) {
  36816. size = totalFacets - f;
  36817. }
  36818. // reset temp arrays
  36819. facetPos.length = 0;
  36820. facetInd.length = 0;
  36821. facetUV.length = 0;
  36822. facetCol.length = 0;
  36823. // iterate over "size" facets
  36824. var fi = 0;
  36825. for (var j = f * 3; j < (f + size) * 3; j++) {
  36826. facetInd.push(fi);
  36827. var i = meshInd[j];
  36828. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  36829. if (meshUV) {
  36830. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  36831. }
  36832. if (meshCol) {
  36833. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  36834. }
  36835. fi++;
  36836. }
  36837. // create a model shape for each single particle
  36838. var idx = this.nbParticles;
  36839. var shape = this._posToShape(facetPos);
  36840. var shapeUV = this._uvsToShapeUV(facetUV);
  36841. // compute the barycenter of the shape
  36842. var v;
  36843. for (v = 0; v < shape.length; v++) {
  36844. barycenter.addInPlace(shape[v]);
  36845. }
  36846. barycenter.scaleInPlace(1 / shape.length);
  36847. // shift the shape from its barycenter to the origin
  36848. for (v = 0; v < shape.length; v++) {
  36849. shape[v].subtractInPlace(barycenter);
  36850. }
  36851. var bInfo;
  36852. if (this._particlesIntersect) {
  36853. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  36854. }
  36855. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  36856. // add the particle in the SPS
  36857. var currentPos = this._positions.length;
  36858. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  36859. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  36860. // initialize the particle position
  36861. this.particles[this.nbParticles].position.addInPlace(barycenter);
  36862. this._index += shape.length;
  36863. idx++;
  36864. this.nbParticles++;
  36865. this._shapeCounter++;
  36866. f += size;
  36867. }
  36868. return this;
  36869. };
  36870. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  36871. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  36872. var index = 0;
  36873. var idx = 0;
  36874. for (var p = 0; p < this.particles.length; p++) {
  36875. this._particle = this.particles[p];
  36876. this._shape = this._particle._model._shape;
  36877. if (this._particle.rotationQuaternion) {
  36878. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  36879. }
  36880. else {
  36881. this._yaw = this._particle.rotation.y;
  36882. this._pitch = this._particle.rotation.x;
  36883. this._roll = this._particle.rotation.z;
  36884. this._quaternionRotationYPR();
  36885. }
  36886. this._quaternionToRotationMatrix();
  36887. this._rotMatrix.invertToRef(this._invertMatrix);
  36888. for (var pt = 0; pt < this._shape.length; pt++) {
  36889. idx = index + pt * 3;
  36890. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  36891. this._fixedNormal32[idx] = this._normal.x;
  36892. this._fixedNormal32[idx + 1] = this._normal.y;
  36893. this._fixedNormal32[idx + 2] = this._normal.z;
  36894. }
  36895. index = idx + 3;
  36896. }
  36897. };
  36898. //reset copy
  36899. SolidParticleSystem.prototype._resetCopy = function () {
  36900. this._copy.position.x = 0;
  36901. this._copy.position.y = 0;
  36902. this._copy.position.z = 0;
  36903. this._copy.rotation.x = 0;
  36904. this._copy.rotation.y = 0;
  36905. this._copy.rotation.z = 0;
  36906. this._copy.rotationQuaternion = null;
  36907. this._copy.scaling.x = 1;
  36908. this._copy.scaling.y = 1;
  36909. this._copy.scaling.z = 1;
  36910. this._copy.uvs.x = 0;
  36911. this._copy.uvs.y = 0;
  36912. this._copy.uvs.z = 1;
  36913. this._copy.uvs.w = 1;
  36914. this._copy.color = null;
  36915. };
  36916. // _meshBuilder : inserts the shape model in the global SPS mesh
  36917. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  36918. var i;
  36919. var u = 0;
  36920. var c = 0;
  36921. var n = 0;
  36922. this._resetCopy();
  36923. if (options && options.positionFunction) {
  36924. options.positionFunction(this._copy, idx, idxInShape);
  36925. this._mustUnrotateFixedNormals = true;
  36926. }
  36927. if (this._copy.rotationQuaternion) {
  36928. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  36929. }
  36930. else {
  36931. this._yaw = this._copy.rotation.y;
  36932. this._pitch = this._copy.rotation.x;
  36933. this._roll = this._copy.rotation.z;
  36934. this._quaternionRotationYPR();
  36935. }
  36936. this._quaternionToRotationMatrix();
  36937. for (i = 0; i < shape.length; i++) {
  36938. this._vertex.x = shape[i].x;
  36939. this._vertex.y = shape[i].y;
  36940. this._vertex.z = shape[i].z;
  36941. if (options && options.vertexFunction) {
  36942. options.vertexFunction(this._copy, this._vertex, i);
  36943. }
  36944. this._vertex.x *= this._copy.scaling.x;
  36945. this._vertex.y *= this._copy.scaling.y;
  36946. this._vertex.z *= this._copy.scaling.z;
  36947. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36948. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36949. if (meshUV) {
  36950. 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);
  36951. u += 2;
  36952. }
  36953. if (this._copy.color) {
  36954. this._color = this._copy.color;
  36955. }
  36956. else if (meshCol && meshCol[c] !== undefined) {
  36957. this._color.r = meshCol[c];
  36958. this._color.g = meshCol[c + 1];
  36959. this._color.b = meshCol[c + 2];
  36960. this._color.a = meshCol[c + 3];
  36961. }
  36962. else {
  36963. this._color.r = 1;
  36964. this._color.g = 1;
  36965. this._color.b = 1;
  36966. this._color.a = 1;
  36967. }
  36968. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36969. c += 4;
  36970. if (!this.recomputeNormals && meshNor) {
  36971. this._normal.x = meshNor[n];
  36972. this._normal.y = meshNor[n + 1];
  36973. this._normal.z = meshNor[n + 2];
  36974. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  36975. normals.push(this._normal.x, this._normal.y, this._normal.z);
  36976. n += 3;
  36977. }
  36978. }
  36979. for (i = 0; i < meshInd.length; i++) {
  36980. indices.push(p + meshInd[i]);
  36981. }
  36982. if (this._pickable) {
  36983. var nbfaces = meshInd.length / 3;
  36984. for (i = 0; i < nbfaces; i++) {
  36985. this.pickedParticles.push({ idx: idx, faceId: i });
  36986. }
  36987. }
  36988. return this._copy;
  36989. };
  36990. // returns a shape array from positions array
  36991. SolidParticleSystem.prototype._posToShape = function (positions) {
  36992. var shape = [];
  36993. for (var i = 0; i < positions.length; i += 3) {
  36994. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36995. }
  36996. return shape;
  36997. };
  36998. // returns a shapeUV array from a Vector4 uvs
  36999. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  37000. var shapeUV = [];
  37001. if (uvs) {
  37002. for (var i = 0; i < uvs.length; i++)
  37003. shapeUV.push(uvs[i]);
  37004. }
  37005. return shapeUV;
  37006. };
  37007. // adds a new particle object in the particles array
  37008. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  37009. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  37010. this.particles.push(sp);
  37011. return sp;
  37012. };
  37013. /**
  37014. * Adds some particles to the SPS from the model shape. Returns the shape id.
  37015. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  37016. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  37017. * `nb` (positive integer) the number of particles to be created from this model
  37018. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  37019. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  37020. */
  37021. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  37022. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37023. var meshInd = mesh.getIndices();
  37024. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37025. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37026. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37027. var bbInfo;
  37028. if (this._particlesIntersect) {
  37029. bbInfo = mesh.getBoundingInfo();
  37030. }
  37031. var shape = this._posToShape(meshPos);
  37032. var shapeUV = this._uvsToShapeUV(meshUV);
  37033. var posfunc = options ? options.positionFunction : null;
  37034. var vtxfunc = options ? options.vertexFunction : null;
  37035. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  37036. // particles
  37037. var sp;
  37038. var currentCopy;
  37039. var idx = this.nbParticles;
  37040. for (var i = 0; i < nb; i++) {
  37041. var currentPos = this._positions.length;
  37042. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  37043. if (this._updatable) {
  37044. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  37045. sp.position.copyFrom(currentCopy.position);
  37046. sp.rotation.copyFrom(currentCopy.rotation);
  37047. if (currentCopy.rotationQuaternion) {
  37048. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  37049. }
  37050. if (currentCopy.color) {
  37051. sp.color.copyFrom(currentCopy.color);
  37052. }
  37053. sp.scaling.copyFrom(currentCopy.scaling);
  37054. sp.uvs.copyFrom(currentCopy.uvs);
  37055. }
  37056. this._index += shape.length;
  37057. idx++;
  37058. }
  37059. this.nbParticles += nb;
  37060. this._shapeCounter++;
  37061. return this._shapeCounter - 1;
  37062. };
  37063. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  37064. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  37065. this._resetCopy();
  37066. if (particle._model._positionFunction) {
  37067. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  37068. }
  37069. if (this._copy.rotationQuaternion) {
  37070. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  37071. }
  37072. else {
  37073. this._yaw = this._copy.rotation.y;
  37074. this._pitch = this._copy.rotation.x;
  37075. this._roll = this._copy.rotation.z;
  37076. this._quaternionRotationYPR();
  37077. }
  37078. this._quaternionToRotationMatrix();
  37079. this._shape = particle._model._shape;
  37080. for (var pt = 0; pt < this._shape.length; pt++) {
  37081. this._vertex.x = this._shape[pt].x;
  37082. this._vertex.y = this._shape[pt].y;
  37083. this._vertex.z = this._shape[pt].z;
  37084. if (particle._model._vertexFunction) {
  37085. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  37086. }
  37087. this._vertex.x *= this._copy.scaling.x;
  37088. this._vertex.y *= this._copy.scaling.y;
  37089. this._vertex.z *= this._copy.scaling.z;
  37090. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  37091. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  37092. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  37093. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  37094. }
  37095. particle.position.x = 0.0;
  37096. particle.position.y = 0.0;
  37097. particle.position.z = 0.0;
  37098. particle.rotation.x = 0.0;
  37099. particle.rotation.y = 0.0;
  37100. particle.rotation.z = 0.0;
  37101. particle.rotationQuaternion = null;
  37102. particle.scaling.x = 1.0;
  37103. particle.scaling.y = 1.0;
  37104. particle.scaling.z = 1.0;
  37105. };
  37106. /**
  37107. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  37108. * Returns the SPS.
  37109. */
  37110. SolidParticleSystem.prototype.rebuildMesh = function () {
  37111. for (var p = 0; p < this.particles.length; p++) {
  37112. this._rebuildParticle(this.particles[p]);
  37113. }
  37114. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37115. return this;
  37116. };
  37117. /**
  37118. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  37119. * This method calls `updateParticle()` for each particle of the SPS.
  37120. * For an animated SPS, it is usually called within the render loop.
  37121. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  37122. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  37123. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  37124. * Returns the SPS.
  37125. */
  37126. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  37127. if (start === void 0) { start = 0; }
  37128. if (end === void 0) { end = this.nbParticles - 1; }
  37129. if (update === void 0) { update = true; }
  37130. if (!this._updatable) {
  37131. return;
  37132. }
  37133. // custom beforeUpdate
  37134. this.beforeUpdateParticles(start, end, update);
  37135. this._cam_axisX.x = 1.0;
  37136. this._cam_axisX.y = 0.0;
  37137. this._cam_axisX.z = 0.0;
  37138. this._cam_axisY.x = 0.0;
  37139. this._cam_axisY.y = 1.0;
  37140. this._cam_axisY.z = 0.0;
  37141. this._cam_axisZ.x = 0.0;
  37142. this._cam_axisZ.y = 0.0;
  37143. this._cam_axisZ.z = 1.0;
  37144. // if the particles will always face the camera
  37145. if (this.billboard) {
  37146. this.mesh.computeWorldMatrix(true);
  37147. // compute the camera position and un-rotate it by the current mesh rotation
  37148. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  37149. this._quaternionToRotationMatrix();
  37150. this._rotMatrix.invertToRef(this._invertMatrix);
  37151. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  37152. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  37153. this._cam_axisZ.normalize();
  37154. // same for camera up vector extracted from the cam view matrix
  37155. var view = this._camera.getViewMatrix(true);
  37156. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  37157. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  37158. this._cam_axisY.normalize();
  37159. this._cam_axisX.normalize();
  37160. }
  37161. }
  37162. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  37163. var idx = 0; // current position index in the global array positions32
  37164. var index = 0; // position start index in the global array positions32 of the current particle
  37165. var colidx = 0; // current color index in the global array colors32
  37166. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  37167. var uvidx = 0; // current uv index in the global array uvs32
  37168. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  37169. var pt = 0; // current index in the particle model shape
  37170. if (this.mesh.isFacetDataEnabled) {
  37171. this._computeBoundingBox = true;
  37172. }
  37173. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  37174. if (this._computeBoundingBox) {
  37175. if (start == 0 && end == this.nbParticles - 1) {
  37176. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  37177. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  37178. }
  37179. else {
  37180. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  37181. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  37182. }
  37183. }
  37184. // particle loop
  37185. index = this.particles[start]._pos;
  37186. var vpos = (index / 3) | 0;
  37187. colorIndex = vpos * 4;
  37188. uvIndex = vpos * 2;
  37189. for (var p = start; p <= end; p++) {
  37190. this._particle = this.particles[p];
  37191. this._shape = this._particle._model._shape;
  37192. this._shapeUV = this._particle._model._shapeUV;
  37193. // call to custom user function to update the particle properties
  37194. this.updateParticle(this._particle);
  37195. if (this._particle.isVisible) {
  37196. // particle rotation matrix
  37197. if (this.billboard) {
  37198. this._particle.rotation.x = 0.0;
  37199. this._particle.rotation.y = 0.0;
  37200. }
  37201. if (this._computeParticleRotation || this.billboard) {
  37202. if (this._particle.rotationQuaternion) {
  37203. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  37204. }
  37205. else {
  37206. this._yaw = this._particle.rotation.y;
  37207. this._pitch = this._particle.rotation.x;
  37208. this._roll = this._particle.rotation.z;
  37209. this._quaternionRotationYPR();
  37210. }
  37211. this._quaternionToRotationMatrix();
  37212. }
  37213. // particle vertex loop
  37214. for (pt = 0; pt < this._shape.length; pt++) {
  37215. idx = index + pt * 3;
  37216. colidx = colorIndex + pt * 4;
  37217. uvidx = uvIndex + pt * 2;
  37218. this._vertex.x = this._shape[pt].x;
  37219. this._vertex.y = this._shape[pt].y;
  37220. this._vertex.z = this._shape[pt].z;
  37221. if (this._computeParticleVertex) {
  37222. this.updateParticleVertex(this._particle, this._vertex, pt);
  37223. }
  37224. // positions
  37225. this._vertex.x *= this._particle.scaling.x;
  37226. this._vertex.y *= this._particle.scaling.y;
  37227. this._vertex.z *= this._particle.scaling.z;
  37228. 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];
  37229. 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;
  37230. 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;
  37231. 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;
  37232. 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;
  37233. 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;
  37234. 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;
  37235. if (this._computeBoundingBox) {
  37236. if (this._positions32[idx] < this._minimum.x) {
  37237. this._minimum.x = this._positions32[idx];
  37238. }
  37239. if (this._positions32[idx] > this._maximum.x) {
  37240. this._maximum.x = this._positions32[idx];
  37241. }
  37242. if (this._positions32[idx + 1] < this._minimum.y) {
  37243. this._minimum.y = this._positions32[idx + 1];
  37244. }
  37245. if (this._positions32[idx + 1] > this._maximum.y) {
  37246. this._maximum.y = this._positions32[idx + 1];
  37247. }
  37248. if (this._positions32[idx + 2] < this._minimum.z) {
  37249. this._minimum.z = this._positions32[idx + 2];
  37250. }
  37251. if (this._positions32[idx + 2] > this._maximum.z) {
  37252. this._maximum.z = this._positions32[idx + 2];
  37253. }
  37254. }
  37255. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  37256. if (!this._computeParticleVertex) {
  37257. this._normal.x = this._fixedNormal32[idx];
  37258. this._normal.y = this._fixedNormal32[idx + 1];
  37259. this._normal.z = this._fixedNormal32[idx + 2];
  37260. 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]);
  37261. 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]);
  37262. 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]);
  37263. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  37264. 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;
  37265. 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;
  37266. }
  37267. if (this._computeParticleColor) {
  37268. this._colors32[colidx] = this._particle.color.r;
  37269. this._colors32[colidx + 1] = this._particle.color.g;
  37270. this._colors32[colidx + 2] = this._particle.color.b;
  37271. this._colors32[colidx + 3] = this._particle.color.a;
  37272. }
  37273. if (this._computeParticleTexture) {
  37274. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37275. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37276. }
  37277. }
  37278. }
  37279. else {
  37280. for (pt = 0; pt < this._shape.length; pt++) {
  37281. idx = index + pt * 3;
  37282. colidx = colorIndex + pt * 4;
  37283. uvidx = uvIndex + pt * 2;
  37284. this._positions32[idx] = this._camera.position.x;
  37285. this._positions32[idx + 1] = this._camera.position.y;
  37286. this._positions32[idx + 2] = this._camera.position.z;
  37287. this._normals32[idx] = 0.0;
  37288. this._normals32[idx + 1] = 0.0;
  37289. this._normals32[idx + 2] = 0.0;
  37290. if (this._computeParticleColor) {
  37291. this._colors32[colidx] = this._particle.color.r;
  37292. this._colors32[colidx + 1] = this._particle.color.g;
  37293. this._colors32[colidx + 2] = this._particle.color.b;
  37294. this._colors32[colidx + 3] = this._particle.color.a;
  37295. }
  37296. if (this._computeParticleTexture) {
  37297. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37298. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37299. }
  37300. }
  37301. }
  37302. // if the particle intersections must be computed : update the bbInfo
  37303. if (this._particlesIntersect) {
  37304. var bInfo = this._particle._boundingInfo;
  37305. var bBox = bInfo.boundingBox;
  37306. var bSphere = bInfo.boundingSphere;
  37307. if (!this._bSphereOnly) {
  37308. // place, scale and rotate the particle bbox within the SPS local system, then update it
  37309. for (var b = 0; b < bBox.vectors.length; b++) {
  37310. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  37311. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  37312. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  37313. 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];
  37314. 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;
  37315. 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;
  37316. 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;
  37317. 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;
  37318. 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;
  37319. 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;
  37320. }
  37321. bBox._update(this.mesh._worldMatrix);
  37322. }
  37323. // place and scale the particle bouding sphere in the SPS local system, then update it
  37324. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  37325. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  37326. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  37327. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  37328. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  37329. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  37330. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  37331. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  37332. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  37333. 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));
  37334. bSphere._update(this.mesh._worldMatrix);
  37335. }
  37336. // increment indexes for the next particle
  37337. index = idx + 3;
  37338. colorIndex = colidx + 4;
  37339. uvIndex = uvidx + 2;
  37340. }
  37341. // if the VBO must be updated
  37342. if (update) {
  37343. if (this._computeParticleColor) {
  37344. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  37345. }
  37346. if (this._computeParticleTexture) {
  37347. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  37348. }
  37349. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37350. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  37351. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  37352. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  37353. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  37354. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  37355. for (var i = 0; i < this._normals32.length; i++) {
  37356. this._fixedNormal32[i] = this._normals32[i];
  37357. }
  37358. }
  37359. if (!this.mesh.areNormalsFrozen) {
  37360. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  37361. }
  37362. }
  37363. }
  37364. if (this._computeBoundingBox) {
  37365. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  37366. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  37367. }
  37368. this.afterUpdateParticles(start, end, update);
  37369. return this;
  37370. };
  37371. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  37372. this._halfroll = this._roll * 0.5;
  37373. this._halfpitch = this._pitch * 0.5;
  37374. this._halfyaw = this._yaw * 0.5;
  37375. this._sinRoll = Math.sin(this._halfroll);
  37376. this._cosRoll = Math.cos(this._halfroll);
  37377. this._sinPitch = Math.sin(this._halfpitch);
  37378. this._cosPitch = Math.cos(this._halfpitch);
  37379. this._sinYaw = Math.sin(this._halfyaw);
  37380. this._cosYaw = Math.cos(this._halfyaw);
  37381. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  37382. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  37383. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  37384. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  37385. };
  37386. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  37387. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  37388. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  37389. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  37390. this._rotMatrix.m[3] = 0;
  37391. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  37392. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  37393. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  37394. this._rotMatrix.m[7] = 0;
  37395. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  37396. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  37397. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  37398. this._rotMatrix.m[11] = 0;
  37399. this._rotMatrix.m[12] = 0;
  37400. this._rotMatrix.m[13] = 0;
  37401. this._rotMatrix.m[14] = 0;
  37402. this._rotMatrix.m[15] = 1.0;
  37403. };
  37404. /**
  37405. * Disposes the SPS.
  37406. * Returns nothing.
  37407. */
  37408. SolidParticleSystem.prototype.dispose = function () {
  37409. this.mesh.dispose();
  37410. this.vars = null;
  37411. // drop references to internal big arrays for the GC
  37412. this._positions = null;
  37413. this._indices = null;
  37414. this._normals = null;
  37415. this._uvs = null;
  37416. this._colors = null;
  37417. this._positions32 = null;
  37418. this._normals32 = null;
  37419. this._fixedNormal32 = null;
  37420. this._uvs32 = null;
  37421. this._colors32 = null;
  37422. this.pickedParticles = null;
  37423. };
  37424. /**
  37425. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  37426. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37427. * Returns the SPS.
  37428. */
  37429. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  37430. if (!this._isVisibilityBoxLocked) {
  37431. this.mesh.refreshBoundingInfo();
  37432. }
  37433. return this;
  37434. };
  37435. /**
  37436. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  37437. * @param size the size (float) of the visibility box
  37438. * note : this doesn't lock the SPS mesh bounding box.
  37439. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37440. */
  37441. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  37442. var vis = size / 2;
  37443. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  37444. };
  37445. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  37446. // getter and setter
  37447. get: function () {
  37448. return this._alwaysVisible;
  37449. },
  37450. /**
  37451. * Sets the SPS as always visible or not
  37452. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37453. */
  37454. set: function (val) {
  37455. this._alwaysVisible = val;
  37456. this.mesh.alwaysSelectAsActiveMesh = val;
  37457. },
  37458. enumerable: true,
  37459. configurable: true
  37460. });
  37461. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  37462. get: function () {
  37463. return this._isVisibilityBoxLocked;
  37464. },
  37465. /**
  37466. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  37467. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37468. */
  37469. set: function (val) {
  37470. this._isVisibilityBoxLocked = val;
  37471. this.mesh.getBoundingInfo().isLocked = val;
  37472. },
  37473. enumerable: true,
  37474. configurable: true
  37475. });
  37476. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  37477. // getters
  37478. get: function () {
  37479. return this._computeParticleRotation;
  37480. },
  37481. // Optimizer setters
  37482. /**
  37483. * Tells to `setParticles()` to compute the particle rotations or not.
  37484. * Default value : true. The SPS is faster when it's set to false.
  37485. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  37486. */
  37487. set: function (val) {
  37488. this._computeParticleRotation = val;
  37489. },
  37490. enumerable: true,
  37491. configurable: true
  37492. });
  37493. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  37494. get: function () {
  37495. return this._computeParticleColor;
  37496. },
  37497. /**
  37498. * Tells to `setParticles()` to compute the particle colors or not.
  37499. * Default value : true. The SPS is faster when it's set to false.
  37500. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  37501. */
  37502. set: function (val) {
  37503. this._computeParticleColor = val;
  37504. },
  37505. enumerable: true,
  37506. configurable: true
  37507. });
  37508. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  37509. get: function () {
  37510. return this._computeParticleTexture;
  37511. },
  37512. /**
  37513. * Tells to `setParticles()` to compute the particle textures or not.
  37514. * Default value : true. The SPS is faster when it's set to false.
  37515. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  37516. */
  37517. set: function (val) {
  37518. this._computeParticleTexture = val;
  37519. },
  37520. enumerable: true,
  37521. configurable: true
  37522. });
  37523. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  37524. get: function () {
  37525. return this._computeParticleVertex;
  37526. },
  37527. /**
  37528. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  37529. * Default value : false. The SPS is faster when it's set to false.
  37530. * Note : the particle custom vertex positions aren't stored values.
  37531. */
  37532. set: function (val) {
  37533. this._computeParticleVertex = val;
  37534. },
  37535. enumerable: true,
  37536. configurable: true
  37537. });
  37538. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  37539. get: function () {
  37540. return this._computeBoundingBox;
  37541. },
  37542. /**
  37543. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  37544. */
  37545. set: function (val) {
  37546. this._computeBoundingBox = val;
  37547. },
  37548. enumerable: true,
  37549. configurable: true
  37550. });
  37551. // =======================================================================
  37552. // Particle behavior logic
  37553. // these following methods may be overwritten by the user to fit his needs
  37554. /**
  37555. * This function does nothing. It may be overwritten to set all the particle first values.
  37556. * The SPS doesn't call this function, you may have to call it by your own.
  37557. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  37558. */
  37559. SolidParticleSystem.prototype.initParticles = function () {
  37560. };
  37561. /**
  37562. * This function does nothing. It may be overwritten to recycle a particle.
  37563. * The SPS doesn't call this function, you may have to call it by your own.
  37564. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  37565. */
  37566. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  37567. return particle;
  37568. };
  37569. /**
  37570. * Updates a particle : this function should be overwritten by the user.
  37571. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  37572. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  37573. * ex : just set a particle position or velocity and recycle conditions
  37574. */
  37575. SolidParticleSystem.prototype.updateParticle = function (particle) {
  37576. return particle;
  37577. };
  37578. /**
  37579. * Updates a vertex of a particle : it can be overwritten by the user.
  37580. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  37581. * @param particle the current particle
  37582. * @param vertex the current index of the current particle
  37583. * @param pt the index of the current vertex in the particle shape
  37584. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  37585. * ex : just set a vertex particle position
  37586. */
  37587. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  37588. return vertex;
  37589. };
  37590. /**
  37591. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  37592. * This does nothing and may be overwritten by the user.
  37593. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37594. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37595. * @param update the boolean update value actually passed to setParticles()
  37596. */
  37597. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  37598. };
  37599. /**
  37600. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  37601. * This will be passed three parameters.
  37602. * This does nothing and may be overwritten by the user.
  37603. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37604. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37605. * @param update the boolean update value actually passed to setParticles()
  37606. */
  37607. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  37608. };
  37609. return SolidParticleSystem;
  37610. }());
  37611. BABYLON.SolidParticleSystem = SolidParticleSystem;
  37612. })(BABYLON || (BABYLON = {}));
  37613. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  37614. /// <reference path="babylon.mesh.ts" />
  37615. var BABYLON;
  37616. (function (BABYLON) {
  37617. var GroundMesh = (function (_super) {
  37618. __extends(GroundMesh, _super);
  37619. function GroundMesh(name, scene) {
  37620. var _this = _super.call(this, name, scene) || this;
  37621. _this.generateOctree = false;
  37622. _this._worldInverse = new BABYLON.Matrix();
  37623. return _this;
  37624. }
  37625. GroundMesh.prototype.getClassName = function () {
  37626. return "GroundMesh";
  37627. };
  37628. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  37629. get: function () {
  37630. return Math.min(this._subdivisionsX, this._subdivisionsY);
  37631. },
  37632. enumerable: true,
  37633. configurable: true
  37634. });
  37635. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  37636. get: function () {
  37637. return this._subdivisionsX;
  37638. },
  37639. enumerable: true,
  37640. configurable: true
  37641. });
  37642. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  37643. get: function () {
  37644. return this._subdivisionsY;
  37645. },
  37646. enumerable: true,
  37647. configurable: true
  37648. });
  37649. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  37650. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  37651. this._subdivisionsX = chunksCount;
  37652. this._subdivisionsY = chunksCount;
  37653. this.subdivide(chunksCount);
  37654. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  37655. };
  37656. /**
  37657. * Returns a height (y) value in the Worl system :
  37658. * the ground altitude at the coordinates (x, z) expressed in the World system.
  37659. * Returns the ground y position if (x, z) are outside the ground surface.
  37660. */
  37661. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  37662. var world = this.getWorldMatrix();
  37663. var invMat = BABYLON.Tmp.Matrix[5];
  37664. world.invertToRef(invMat);
  37665. var tmpVect = BABYLON.Tmp.Vector3[8];
  37666. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  37667. x = tmpVect.x;
  37668. z = tmpVect.z;
  37669. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37670. return this.position.y;
  37671. }
  37672. if (!this._heightQuads || this._heightQuads.length == 0) {
  37673. this._initHeightQuads();
  37674. this._computeHeightQuads();
  37675. }
  37676. var facet = this._getFacetAt(x, z);
  37677. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  37678. // return y in the World system
  37679. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  37680. return tmpVect.y;
  37681. };
  37682. /**
  37683. * Returns a normalized vector (Vector3) orthogonal to the ground
  37684. * at the ground coordinates (x, z) expressed in the World system.
  37685. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  37686. */
  37687. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  37688. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  37689. this.getNormalAtCoordinatesToRef(x, z, normal);
  37690. return normal;
  37691. };
  37692. /**
  37693. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  37694. * at the ground coordinates (x, z) expressed in the World system.
  37695. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  37696. * Returns the GroundMesh.
  37697. */
  37698. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  37699. var world = this.getWorldMatrix();
  37700. var tmpMat = BABYLON.Tmp.Matrix[5];
  37701. world.invertToRef(tmpMat);
  37702. var tmpVect = BABYLON.Tmp.Vector3[8];
  37703. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  37704. x = tmpVect.x;
  37705. z = tmpVect.z;
  37706. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37707. return this;
  37708. }
  37709. if (!this._heightQuads || this._heightQuads.length == 0) {
  37710. this._initHeightQuads();
  37711. this._computeHeightQuads();
  37712. }
  37713. var facet = this._getFacetAt(x, z);
  37714. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  37715. return this;
  37716. };
  37717. /**
  37718. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  37719. * if the ground has been updated.
  37720. * This can be used in the render loop.
  37721. * Returns the GroundMesh.
  37722. */
  37723. GroundMesh.prototype.updateCoordinateHeights = function () {
  37724. if (!this._heightQuads || this._heightQuads.length == 0) {
  37725. this._initHeightQuads();
  37726. }
  37727. this._computeHeightQuads();
  37728. return this;
  37729. };
  37730. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  37731. GroundMesh.prototype._getFacetAt = function (x, z) {
  37732. // retrieve col and row from x, z coordinates in the ground local system
  37733. var subdivisionsX = this._subdivisionsX;
  37734. var subdivisionsY = this._subdivisionsY;
  37735. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  37736. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  37737. var quad = this._heightQuads[row * this._subdivisionsX + col];
  37738. var facet;
  37739. if (z < quad.slope.x * x + quad.slope.y) {
  37740. facet = quad.facet1;
  37741. }
  37742. else {
  37743. facet = quad.facet2;
  37744. }
  37745. return facet;
  37746. };
  37747. // Creates and populates the heightMap array with "facet" elements :
  37748. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  37749. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37750. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37751. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37752. // Returns the GroundMesh.
  37753. GroundMesh.prototype._initHeightQuads = function () {
  37754. var subdivisionsX = this._subdivisionsX;
  37755. var subdivisionsY = this._subdivisionsY;
  37756. this._heightQuads = new Array();
  37757. for (var row = 0; row < subdivisionsY; row++) {
  37758. for (var col = 0; col < subdivisionsX; col++) {
  37759. 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) };
  37760. this._heightQuads[row * subdivisionsX + col] = quad;
  37761. }
  37762. }
  37763. return this;
  37764. };
  37765. // Compute each quad element values and update the the heightMap array :
  37766. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37767. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37768. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37769. // Returns the GroundMesh.
  37770. GroundMesh.prototype._computeHeightQuads = function () {
  37771. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37772. var v1 = BABYLON.Tmp.Vector3[3];
  37773. var v2 = BABYLON.Tmp.Vector3[2];
  37774. var v3 = BABYLON.Tmp.Vector3[1];
  37775. var v4 = BABYLON.Tmp.Vector3[0];
  37776. var v1v2 = BABYLON.Tmp.Vector3[4];
  37777. var v1v3 = BABYLON.Tmp.Vector3[5];
  37778. var v1v4 = BABYLON.Tmp.Vector3[6];
  37779. var norm1 = BABYLON.Tmp.Vector3[7];
  37780. var norm2 = BABYLON.Tmp.Vector3[8];
  37781. var i = 0;
  37782. var j = 0;
  37783. var k = 0;
  37784. var cd = 0; // 2D slope coefficient : z = cd * x + h
  37785. var h = 0;
  37786. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  37787. var d2 = 0;
  37788. var subdivisionsX = this._subdivisionsX;
  37789. var subdivisionsY = this._subdivisionsY;
  37790. for (var row = 0; row < subdivisionsY; row++) {
  37791. for (var col = 0; col < subdivisionsX; col++) {
  37792. i = col * 3;
  37793. j = row * (subdivisionsX + 1) * 3;
  37794. k = (row + 1) * (subdivisionsX + 1) * 3;
  37795. v1.x = positions[j + i];
  37796. v1.y = positions[j + i + 1];
  37797. v1.z = positions[j + i + 2];
  37798. v2.x = positions[j + i + 3];
  37799. v2.y = positions[j + i + 4];
  37800. v2.z = positions[j + i + 5];
  37801. v3.x = positions[k + i];
  37802. v3.y = positions[k + i + 1];
  37803. v3.z = positions[k + i + 2];
  37804. v4.x = positions[k + i + 3];
  37805. v4.y = positions[k + i + 4];
  37806. v4.z = positions[k + i + 5];
  37807. // 2D slope V1V4
  37808. cd = (v4.z - v1.z) / (v4.x - v1.x);
  37809. h = v1.z - cd * v1.x; // v1 belongs to the slope
  37810. // facet equations :
  37811. // we compute each facet normal vector
  37812. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  37813. // we compute the value d by applying the equation to v1 which belongs to the plane
  37814. // then we store the facet equation in a Vector4
  37815. v2.subtractToRef(v1, v1v2);
  37816. v3.subtractToRef(v1, v1v3);
  37817. v4.subtractToRef(v1, v1v4);
  37818. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  37819. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  37820. norm1.normalize();
  37821. norm2.normalize();
  37822. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  37823. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  37824. var quad = this._heightQuads[row * subdivisionsX + col];
  37825. quad.slope.copyFromFloats(cd, h);
  37826. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  37827. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  37828. }
  37829. }
  37830. return this;
  37831. };
  37832. GroundMesh.prototype.serialize = function (serializationObject) {
  37833. _super.prototype.serialize.call(this, serializationObject);
  37834. serializationObject.subdivisionsX = this._subdivisionsX;
  37835. serializationObject.subdivisionsY = this._subdivisionsY;
  37836. serializationObject.minX = this._minX;
  37837. serializationObject.maxX = this._maxX;
  37838. serializationObject.minZ = this._minZ;
  37839. serializationObject.maxZ = this._maxZ;
  37840. serializationObject.width = this._width;
  37841. serializationObject.height = this._height;
  37842. };
  37843. GroundMesh.Parse = function (parsedMesh, scene) {
  37844. var result = new GroundMesh(parsedMesh.name, scene);
  37845. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  37846. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  37847. result._minX = parsedMesh.minX;
  37848. result._maxX = parsedMesh.maxX;
  37849. result._minZ = parsedMesh.minZ;
  37850. result._maxZ = parsedMesh.maxZ;
  37851. result._width = parsedMesh.width;
  37852. result._height = parsedMesh.height;
  37853. return result;
  37854. };
  37855. return GroundMesh;
  37856. }(BABYLON.Mesh));
  37857. BABYLON.GroundMesh = GroundMesh;
  37858. })(BABYLON || (BABYLON = {}));
  37859. //# sourceMappingURL=babylon.groundMesh.js.map
  37860. var BABYLON;
  37861. (function (BABYLON) {
  37862. /**
  37863. * Creates an instance based on a source mesh.
  37864. */
  37865. var InstancedMesh = (function (_super) {
  37866. __extends(InstancedMesh, _super);
  37867. function InstancedMesh(name, source) {
  37868. var _this = _super.call(this, name, source.getScene()) || this;
  37869. source.instances.push(_this);
  37870. _this._sourceMesh = source;
  37871. _this.position.copyFrom(source.position);
  37872. _this.rotation.copyFrom(source.rotation);
  37873. _this.scaling.copyFrom(source.scaling);
  37874. if (source.rotationQuaternion) {
  37875. _this.rotationQuaternion = source.rotationQuaternion.clone();
  37876. }
  37877. _this.infiniteDistance = source.infiniteDistance;
  37878. _this.setPivotMatrix(source.getPivotMatrix());
  37879. _this.refreshBoundingInfo();
  37880. _this._syncSubMeshes();
  37881. return _this;
  37882. }
  37883. /**
  37884. * Returns the string "InstancedMesh".
  37885. */
  37886. InstancedMesh.prototype.getClassName = function () {
  37887. return "InstancedMesh";
  37888. };
  37889. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  37890. // Methods
  37891. get: function () {
  37892. return this._sourceMesh.receiveShadows;
  37893. },
  37894. enumerable: true,
  37895. configurable: true
  37896. });
  37897. Object.defineProperty(InstancedMesh.prototype, "material", {
  37898. get: function () {
  37899. return this._sourceMesh.material;
  37900. },
  37901. enumerable: true,
  37902. configurable: true
  37903. });
  37904. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  37905. get: function () {
  37906. return this._sourceMesh.visibility;
  37907. },
  37908. enumerable: true,
  37909. configurable: true
  37910. });
  37911. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  37912. get: function () {
  37913. return this._sourceMesh.skeleton;
  37914. },
  37915. enumerable: true,
  37916. configurable: true
  37917. });
  37918. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  37919. get: function () {
  37920. return this._sourceMesh.renderingGroupId;
  37921. },
  37922. enumerable: true,
  37923. configurable: true
  37924. });
  37925. /**
  37926. * Returns the total number of vertices (integer).
  37927. */
  37928. InstancedMesh.prototype.getTotalVertices = function () {
  37929. return this._sourceMesh.getTotalVertices();
  37930. };
  37931. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  37932. get: function () {
  37933. return this._sourceMesh;
  37934. },
  37935. enumerable: true,
  37936. configurable: true
  37937. });
  37938. /**
  37939. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  37940. */
  37941. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  37942. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  37943. };
  37944. /**
  37945. * Sets the vertex data of the mesh geometry for the requested `kind`.
  37946. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  37947. * The `data` are either a numeric array either a Float32Array.
  37948. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  37949. * 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).
  37950. * Note that a new underlying VertexBuffer object is created each call.
  37951. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  37952. *
  37953. * Possible `kind` values :
  37954. * - BABYLON.VertexBuffer.PositionKind
  37955. * - BABYLON.VertexBuffer.UVKind
  37956. * - BABYLON.VertexBuffer.UV2Kind
  37957. * - BABYLON.VertexBuffer.UV3Kind
  37958. * - BABYLON.VertexBuffer.UV4Kind
  37959. * - BABYLON.VertexBuffer.UV5Kind
  37960. * - BABYLON.VertexBuffer.UV6Kind
  37961. * - BABYLON.VertexBuffer.ColorKind
  37962. * - BABYLON.VertexBuffer.MatricesIndicesKind
  37963. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  37964. * - BABYLON.VertexBuffer.MatricesWeightsKind
  37965. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  37966. *
  37967. * Returns the Mesh.
  37968. */
  37969. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  37970. if (this.sourceMesh) {
  37971. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  37972. }
  37973. return this.sourceMesh;
  37974. };
  37975. /**
  37976. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  37977. * If the mesh has no geometry, it is simply returned as it is.
  37978. * The `data` are either a numeric array either a Float32Array.
  37979. * No new underlying VertexBuffer object is created.
  37980. * 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.
  37981. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  37982. *
  37983. * Possible `kind` values :
  37984. * - BABYLON.VertexBuffer.PositionKind
  37985. * - BABYLON.VertexBuffer.UVKind
  37986. * - BABYLON.VertexBuffer.UV2Kind
  37987. * - BABYLON.VertexBuffer.UV3Kind
  37988. * - BABYLON.VertexBuffer.UV4Kind
  37989. * - BABYLON.VertexBuffer.UV5Kind
  37990. * - BABYLON.VertexBuffer.UV6Kind
  37991. * - BABYLON.VertexBuffer.ColorKind
  37992. * - BABYLON.VertexBuffer.MatricesIndicesKind
  37993. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  37994. * - BABYLON.VertexBuffer.MatricesWeightsKind
  37995. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  37996. *
  37997. * Returns the Mesh.
  37998. */
  37999. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  38000. if (this.sourceMesh) {
  38001. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  38002. }
  38003. return this.sourceMesh;
  38004. };
  38005. /**
  38006. * Sets the mesh indices.
  38007. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  38008. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  38009. * This method creates a new index buffer each call.
  38010. * Returns the Mesh.
  38011. */
  38012. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  38013. if (this.sourceMesh) {
  38014. this.sourceMesh.setIndices(indices, totalVertices);
  38015. }
  38016. return this.sourceMesh;
  38017. };
  38018. /**
  38019. * Boolean : True if the mesh owns the requested kind of data.
  38020. */
  38021. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  38022. return this._sourceMesh.isVerticesDataPresent(kind);
  38023. };
  38024. /**
  38025. * Returns an array of indices (IndicesArray).
  38026. */
  38027. InstancedMesh.prototype.getIndices = function () {
  38028. return this._sourceMesh.getIndices();
  38029. };
  38030. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  38031. get: function () {
  38032. return this._sourceMesh._positions;
  38033. },
  38034. enumerable: true,
  38035. configurable: true
  38036. });
  38037. /**
  38038. * Sets a new updated BoundingInfo to the mesh.
  38039. * Returns the mesh.
  38040. */
  38041. InstancedMesh.prototype.refreshBoundingInfo = function () {
  38042. var meshBB = this._sourceMesh.getBoundingInfo();
  38043. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  38044. this._updateBoundingInfo();
  38045. return this;
  38046. };
  38047. InstancedMesh.prototype._preActivate = function () {
  38048. if (this._currentLOD) {
  38049. this._currentLOD._preActivate();
  38050. }
  38051. return this;
  38052. };
  38053. InstancedMesh.prototype._activate = function (renderId) {
  38054. if (this._currentLOD) {
  38055. this._currentLOD._registerInstanceForRenderId(this, renderId);
  38056. }
  38057. return this;
  38058. };
  38059. /**
  38060. * Returns the current associated LOD AbstractMesh.
  38061. */
  38062. InstancedMesh.prototype.getLOD = function (camera) {
  38063. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  38064. if (this._currentLOD === this.sourceMesh) {
  38065. return this;
  38066. }
  38067. return this._currentLOD;
  38068. };
  38069. InstancedMesh.prototype._syncSubMeshes = function () {
  38070. this.releaseSubMeshes();
  38071. if (this._sourceMesh.subMeshes) {
  38072. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  38073. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  38074. }
  38075. }
  38076. return this;
  38077. };
  38078. InstancedMesh.prototype._generatePointsArray = function () {
  38079. return this._sourceMesh._generatePointsArray();
  38080. };
  38081. /**
  38082. * Creates a new InstancedMesh from the current mesh.
  38083. * - name (string) : the cloned mesh name
  38084. * - newParent (optional Node) : the optional Node to parent the clone to.
  38085. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  38086. *
  38087. * Returns the clone.
  38088. */
  38089. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  38090. var result = this._sourceMesh.createInstance(name);
  38091. // Deep copy
  38092. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  38093. // Bounding info
  38094. this.refreshBoundingInfo();
  38095. // Parent
  38096. if (newParent) {
  38097. result.parent = newParent;
  38098. }
  38099. if (!doNotCloneChildren) {
  38100. // Children
  38101. for (var index = 0; index < this.getScene().meshes.length; index++) {
  38102. var mesh = this.getScene().meshes[index];
  38103. if (mesh.parent === this) {
  38104. mesh.clone(mesh.name, result);
  38105. }
  38106. }
  38107. }
  38108. result.computeWorldMatrix(true);
  38109. return result;
  38110. };
  38111. /**
  38112. * Disposes the InstancedMesh.
  38113. * Returns nothing.
  38114. */
  38115. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  38116. // Remove from mesh
  38117. var index = this._sourceMesh.instances.indexOf(this);
  38118. this._sourceMesh.instances.splice(index, 1);
  38119. _super.prototype.dispose.call(this, doNotRecurse);
  38120. };
  38121. return InstancedMesh;
  38122. }(BABYLON.AbstractMesh));
  38123. BABYLON.InstancedMesh = InstancedMesh;
  38124. })(BABYLON || (BABYLON = {}));
  38125. //# sourceMappingURL=babylon.instancedMesh.js.map
  38126. /// <reference path="babylon.mesh.ts" />
  38127. var BABYLON;
  38128. (function (BABYLON) {
  38129. var LinesMesh = (function (_super) {
  38130. __extends(LinesMesh, _super);
  38131. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  38132. if (parent === void 0) { parent = null; }
  38133. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  38134. _this.useVertexColor = useVertexColor;
  38135. _this.color = new BABYLON.Color3(1, 1, 1);
  38136. _this.alpha = 1;
  38137. if (source) {
  38138. _this.color = source.color.clone();
  38139. _this.alpha = source.alpha;
  38140. _this.useVertexColor = source.useVertexColor;
  38141. }
  38142. _this._intersectionThreshold = 0.1;
  38143. var options = {
  38144. attributes: [BABYLON.VertexBuffer.PositionKind],
  38145. uniforms: ["world", "viewProjection"],
  38146. needAlphaBlending: false,
  38147. };
  38148. if (!useVertexColor) {
  38149. options.uniforms.push("color");
  38150. options.needAlphaBlending = true;
  38151. }
  38152. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  38153. return _this;
  38154. }
  38155. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  38156. /**
  38157. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38158. * This margin is expressed in world space coordinates, so its value may vary.
  38159. * Default value is 0.1
  38160. * @returns the intersection Threshold value.
  38161. */
  38162. get: function () {
  38163. return this._intersectionThreshold;
  38164. },
  38165. /**
  38166. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38167. * This margin is expressed in world space coordinates, so its value may vary.
  38168. * @param value the new threshold to apply
  38169. */
  38170. set: function (value) {
  38171. if (this._intersectionThreshold === value) {
  38172. return;
  38173. }
  38174. this._intersectionThreshold = value;
  38175. if (this.geometry) {
  38176. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  38177. }
  38178. },
  38179. enumerable: true,
  38180. configurable: true
  38181. });
  38182. /**
  38183. * Returns the string "LineMesh"
  38184. */
  38185. LinesMesh.prototype.getClassName = function () {
  38186. return "LinesMesh";
  38187. };
  38188. Object.defineProperty(LinesMesh.prototype, "material", {
  38189. get: function () {
  38190. return this._colorShader;
  38191. },
  38192. enumerable: true,
  38193. configurable: true
  38194. });
  38195. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  38196. get: function () {
  38197. return false;
  38198. },
  38199. enumerable: true,
  38200. configurable: true
  38201. });
  38202. LinesMesh.prototype.createInstance = function (name) {
  38203. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  38204. return null;
  38205. };
  38206. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  38207. // VBOs
  38208. this._geometry._bind(this._colorShader.getEffect());
  38209. // Color
  38210. if (!this.useVertexColor) {
  38211. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  38212. }
  38213. return this;
  38214. };
  38215. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  38216. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  38217. return this;
  38218. }
  38219. var engine = this.getScene().getEngine();
  38220. // Draw order
  38221. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  38222. return this;
  38223. };
  38224. LinesMesh.prototype.dispose = function (doNotRecurse) {
  38225. this._colorShader.dispose();
  38226. _super.prototype.dispose.call(this, doNotRecurse);
  38227. };
  38228. /**
  38229. * Returns a new LineMesh object cloned from the current one.
  38230. */
  38231. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  38232. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  38233. };
  38234. return LinesMesh;
  38235. }(BABYLON.Mesh));
  38236. BABYLON.LinesMesh = LinesMesh;
  38237. })(BABYLON || (BABYLON = {}));
  38238. //# sourceMappingURL=babylon.linesMesh.js.map
  38239. var BABYLON;
  38240. (function (BABYLON) {
  38241. var ShaderMaterial = (function (_super) {
  38242. __extends(ShaderMaterial, _super);
  38243. function ShaderMaterial(name, scene, shaderPath, options) {
  38244. var _this = _super.call(this, name, scene) || this;
  38245. _this._textures = {};
  38246. _this._textureArrays = {};
  38247. _this._floats = {};
  38248. _this._floatsArrays = {};
  38249. _this._colors3 = {};
  38250. _this._colors4 = {};
  38251. _this._vectors2 = {};
  38252. _this._vectors3 = {};
  38253. _this._vectors4 = {};
  38254. _this._matrices = {};
  38255. _this._matrices3x3 = {};
  38256. _this._matrices2x2 = {};
  38257. _this._vectors3Arrays = {};
  38258. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  38259. _this._shaderPath = shaderPath;
  38260. options.needAlphaBlending = options.needAlphaBlending || false;
  38261. options.needAlphaTesting = options.needAlphaTesting || false;
  38262. options.attributes = options.attributes || ["position", "normal", "uv"];
  38263. options.uniforms = options.uniforms || ["worldViewProjection"];
  38264. options.uniformBuffers = options.uniformBuffers || [];
  38265. options.samplers = options.samplers || [];
  38266. options.defines = options.defines || [];
  38267. _this._options = options;
  38268. return _this;
  38269. }
  38270. ShaderMaterial.prototype.getClassName = function () {
  38271. return "ShaderMaterial";
  38272. };
  38273. ShaderMaterial.prototype.needAlphaBlending = function () {
  38274. return this._options.needAlphaBlending;
  38275. };
  38276. ShaderMaterial.prototype.needAlphaTesting = function () {
  38277. return this._options.needAlphaTesting;
  38278. };
  38279. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  38280. if (this._options.uniforms.indexOf(uniformName) === -1) {
  38281. this._options.uniforms.push(uniformName);
  38282. }
  38283. };
  38284. ShaderMaterial.prototype.setTexture = function (name, texture) {
  38285. if (this._options.samplers.indexOf(name) === -1) {
  38286. this._options.samplers.push(name);
  38287. }
  38288. this._textures[name] = texture;
  38289. return this;
  38290. };
  38291. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  38292. if (this._options.samplers.indexOf(name) === -1) {
  38293. this._options.samplers.push(name);
  38294. }
  38295. this._checkUniform(name);
  38296. this._textureArrays[name] = textures;
  38297. return this;
  38298. };
  38299. ShaderMaterial.prototype.setFloat = function (name, value) {
  38300. this._checkUniform(name);
  38301. this._floats[name] = value;
  38302. return this;
  38303. };
  38304. ShaderMaterial.prototype.setFloats = function (name, value) {
  38305. this._checkUniform(name);
  38306. this._floatsArrays[name] = value;
  38307. return this;
  38308. };
  38309. ShaderMaterial.prototype.setColor3 = function (name, value) {
  38310. this._checkUniform(name);
  38311. this._colors3[name] = value;
  38312. return this;
  38313. };
  38314. ShaderMaterial.prototype.setColor4 = function (name, value) {
  38315. this._checkUniform(name);
  38316. this._colors4[name] = value;
  38317. return this;
  38318. };
  38319. ShaderMaterial.prototype.setVector2 = function (name, value) {
  38320. this._checkUniform(name);
  38321. this._vectors2[name] = value;
  38322. return this;
  38323. };
  38324. ShaderMaterial.prototype.setVector3 = function (name, value) {
  38325. this._checkUniform(name);
  38326. this._vectors3[name] = value;
  38327. return this;
  38328. };
  38329. ShaderMaterial.prototype.setVector4 = function (name, value) {
  38330. this._checkUniform(name);
  38331. this._vectors4[name] = value;
  38332. return this;
  38333. };
  38334. ShaderMaterial.prototype.setMatrix = function (name, value) {
  38335. this._checkUniform(name);
  38336. this._matrices[name] = value;
  38337. return this;
  38338. };
  38339. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  38340. this._checkUniform(name);
  38341. this._matrices3x3[name] = value;
  38342. return this;
  38343. };
  38344. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  38345. this._checkUniform(name);
  38346. this._matrices2x2[name] = value;
  38347. return this;
  38348. };
  38349. ShaderMaterial.prototype.setArray3 = function (name, value) {
  38350. this._checkUniform(name);
  38351. this._vectors3Arrays[name] = value;
  38352. return this;
  38353. };
  38354. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  38355. if (!mesh) {
  38356. return true;
  38357. }
  38358. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  38359. return false;
  38360. }
  38361. return false;
  38362. };
  38363. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  38364. var scene = this.getScene();
  38365. var engine = scene.getEngine();
  38366. if (!this.checkReadyOnEveryCall) {
  38367. if (this._renderId === scene.getRenderId()) {
  38368. if (this._checkCache(scene, mesh, useInstances)) {
  38369. return true;
  38370. }
  38371. }
  38372. }
  38373. // Instances
  38374. var defines = [];
  38375. var attribs = [];
  38376. var fallbacks = new BABYLON.EffectFallbacks();
  38377. if (useInstances) {
  38378. defines.push("#define INSTANCES");
  38379. }
  38380. for (var index = 0; index < this._options.defines.length; index++) {
  38381. defines.push(this._options.defines[index]);
  38382. }
  38383. for (var index = 0; index < this._options.attributes.length; index++) {
  38384. attribs.push(this._options.attributes[index]);
  38385. }
  38386. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38387. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38388. defines.push("#define VERTEXCOLOR");
  38389. }
  38390. // Bones
  38391. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  38392. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38393. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38394. if (mesh.numBoneInfluencers > 4) {
  38395. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38396. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38397. }
  38398. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38399. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38400. fallbacks.addCPUSkinningFallback(0, mesh);
  38401. }
  38402. else {
  38403. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38404. }
  38405. // Textures
  38406. for (var name in this._textures) {
  38407. if (!this._textures[name].isReady()) {
  38408. return false;
  38409. }
  38410. }
  38411. // Alpha test
  38412. if (engine.getAlphaTesting()) {
  38413. defines.push("#define ALPHATEST");
  38414. }
  38415. var previousEffect = this._effect;
  38416. var join = defines.join("\n");
  38417. this._effect = engine.createEffect(this._shaderPath, {
  38418. attributes: attribs,
  38419. uniformsNames: this._options.uniforms,
  38420. uniformBuffersNames: this._options.uniformBuffers,
  38421. samplers: this._options.samplers,
  38422. defines: join,
  38423. fallbacks: fallbacks,
  38424. onCompiled: this.onCompiled,
  38425. onError: this.onError
  38426. }, engine);
  38427. if (!this._effect.isReady()) {
  38428. return false;
  38429. }
  38430. if (previousEffect !== this._effect) {
  38431. scene.resetCachedMaterial();
  38432. }
  38433. this._renderId = scene.getRenderId();
  38434. return true;
  38435. };
  38436. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38437. var scene = this.getScene();
  38438. if (this._options.uniforms.indexOf("world") !== -1) {
  38439. this._effect.setMatrix("world", world);
  38440. }
  38441. if (this._options.uniforms.indexOf("worldView") !== -1) {
  38442. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  38443. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  38444. }
  38445. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  38446. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  38447. }
  38448. };
  38449. ShaderMaterial.prototype.bind = function (world, mesh) {
  38450. // Std values
  38451. this.bindOnlyWorldMatrix(world);
  38452. if (this.getScene().getCachedMaterial() !== this) {
  38453. if (this._options.uniforms.indexOf("view") !== -1) {
  38454. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  38455. }
  38456. if (this._options.uniforms.indexOf("projection") !== -1) {
  38457. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  38458. }
  38459. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  38460. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  38461. }
  38462. // Bones
  38463. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  38464. var name;
  38465. // Texture
  38466. for (name in this._textures) {
  38467. this._effect.setTexture(name, this._textures[name]);
  38468. }
  38469. // Texture arrays
  38470. for (name in this._textureArrays) {
  38471. this._effect.setTextureArray(name, this._textureArrays[name]);
  38472. }
  38473. // Float
  38474. for (name in this._floats) {
  38475. this._effect.setFloat(name, this._floats[name]);
  38476. }
  38477. // Float s
  38478. for (name in this._floatsArrays) {
  38479. this._effect.setArray(name, this._floatsArrays[name]);
  38480. }
  38481. // Color3
  38482. for (name in this._colors3) {
  38483. this._effect.setColor3(name, this._colors3[name]);
  38484. }
  38485. // Color4
  38486. for (name in this._colors4) {
  38487. var color = this._colors4[name];
  38488. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  38489. }
  38490. // Vector2
  38491. for (name in this._vectors2) {
  38492. this._effect.setVector2(name, this._vectors2[name]);
  38493. }
  38494. // Vector3
  38495. for (name in this._vectors3) {
  38496. this._effect.setVector3(name, this._vectors3[name]);
  38497. }
  38498. // Vector4
  38499. for (name in this._vectors4) {
  38500. this._effect.setVector4(name, this._vectors4[name]);
  38501. }
  38502. // Matrix
  38503. for (name in this._matrices) {
  38504. this._effect.setMatrix(name, this._matrices[name]);
  38505. }
  38506. // Matrix 3x3
  38507. for (name in this._matrices3x3) {
  38508. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  38509. }
  38510. // Matrix 2x2
  38511. for (name in this._matrices2x2) {
  38512. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  38513. }
  38514. // Vector3Array
  38515. for (name in this._vectors3Arrays) {
  38516. this._effect.setArray3(name, this._vectors3Arrays[name]);
  38517. }
  38518. }
  38519. this._afterBind(mesh);
  38520. };
  38521. ShaderMaterial.prototype.clone = function (name) {
  38522. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  38523. return newShaderMaterial;
  38524. };
  38525. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38526. if (forceDisposeTextures) {
  38527. var name;
  38528. for (name in this._textures) {
  38529. this._textures[name].dispose();
  38530. }
  38531. for (name in this._textureArrays) {
  38532. var array = this._textureArrays[name];
  38533. for (var index = 0; index < array.length; index++) {
  38534. array[index].dispose();
  38535. }
  38536. }
  38537. }
  38538. this._textures = {};
  38539. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38540. };
  38541. ShaderMaterial.prototype.serialize = function () {
  38542. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38543. serializationObject.customType = "BABYLON.ShaderMaterial";
  38544. serializationObject.options = this._options;
  38545. serializationObject.shaderPath = this._shaderPath;
  38546. var name;
  38547. // Texture
  38548. serializationObject.textures = {};
  38549. for (name in this._textures) {
  38550. serializationObject.textures[name] = this._textures[name].serialize();
  38551. }
  38552. // Texture arrays
  38553. serializationObject.textureArrays = {};
  38554. for (name in this._textureArrays) {
  38555. serializationObject.textureArrays[name] = [];
  38556. var array = this._textureArrays[name];
  38557. for (var index = 0; index < array.length; index++) {
  38558. serializationObject.textureArrays[name].push(array[index].serialize());
  38559. }
  38560. }
  38561. // Float
  38562. serializationObject.floats = {};
  38563. for (name in this._floats) {
  38564. serializationObject.floats[name] = this._floats[name];
  38565. }
  38566. // Float s
  38567. serializationObject.floatArrays = {};
  38568. for (name in this._floatsArrays) {
  38569. serializationObject.floatArrays[name] = this._floatsArrays[name];
  38570. }
  38571. // Color3
  38572. serializationObject.colors3 = {};
  38573. for (name in this._colors3) {
  38574. serializationObject.colors3[name] = this._colors3[name].asArray();
  38575. }
  38576. // Color4
  38577. serializationObject.colors4 = {};
  38578. for (name in this._colors4) {
  38579. serializationObject.colors4[name] = this._colors4[name].asArray();
  38580. }
  38581. // Vector2
  38582. serializationObject.vectors2 = {};
  38583. for (name in this._vectors2) {
  38584. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  38585. }
  38586. // Vector3
  38587. serializationObject.vectors3 = {};
  38588. for (name in this._vectors3) {
  38589. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  38590. }
  38591. // Vector4
  38592. serializationObject.vectors4 = {};
  38593. for (name in this._vectors4) {
  38594. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  38595. }
  38596. // Matrix
  38597. serializationObject.matrices = {};
  38598. for (name in this._matrices) {
  38599. serializationObject.matrices[name] = this._matrices[name].asArray();
  38600. }
  38601. // Matrix 3x3
  38602. serializationObject.matrices3x3 = {};
  38603. for (name in this._matrices3x3) {
  38604. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  38605. }
  38606. // Matrix 2x2
  38607. serializationObject.matrices2x2 = {};
  38608. for (name in this._matrices2x2) {
  38609. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  38610. }
  38611. // Vector3Array
  38612. serializationObject.vectors3Arrays = {};
  38613. for (name in this._vectors3Arrays) {
  38614. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  38615. }
  38616. return serializationObject;
  38617. };
  38618. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  38619. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  38620. var name;
  38621. // Texture
  38622. for (name in source.textures) {
  38623. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  38624. }
  38625. // Texture arrays
  38626. for (name in source.textureArrays) {
  38627. var array = source.textureArrays[name];
  38628. var textureArray = new Array();
  38629. for (var index = 0; index < array.length; index++) {
  38630. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  38631. }
  38632. material.setTextureArray(name, textureArray);
  38633. }
  38634. // Float
  38635. for (name in source.floats) {
  38636. material.setFloat(name, source.floats[name]);
  38637. }
  38638. // Float s
  38639. for (name in source.floatsArrays) {
  38640. material.setFloats(name, source.floatsArrays[name]);
  38641. }
  38642. // Color3
  38643. for (name in source.colors3) {
  38644. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  38645. }
  38646. // Color4
  38647. for (name in source.colors4) {
  38648. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  38649. }
  38650. // Vector2
  38651. for (name in source.vectors2) {
  38652. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  38653. }
  38654. // Vector3
  38655. for (name in source.vectors3) {
  38656. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  38657. }
  38658. // Vector4
  38659. for (name in source.vectors4) {
  38660. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  38661. }
  38662. // Matrix
  38663. for (name in source.matrices) {
  38664. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  38665. }
  38666. // Matrix 3x3
  38667. for (name in source.matrices3x3) {
  38668. material.setMatrix3x3(name, source.matrices3x3[name]);
  38669. }
  38670. // Matrix 2x2
  38671. for (name in source.matrices2x2) {
  38672. material.setMatrix2x2(name, source.matrices2x2[name]);
  38673. }
  38674. // Vector3Array
  38675. for (name in source.vectors3Arrays) {
  38676. material.setArray3(name, source.vectors3Arrays[name]);
  38677. }
  38678. return material;
  38679. };
  38680. return ShaderMaterial;
  38681. }(BABYLON.Material));
  38682. BABYLON.ShaderMaterial = ShaderMaterial;
  38683. })(BABYLON || (BABYLON = {}));
  38684. //# sourceMappingURL=babylon.shaderMaterial.js.map
  38685. var BABYLON;
  38686. (function (BABYLON) {
  38687. var MeshBuilder = (function () {
  38688. function MeshBuilder() {
  38689. }
  38690. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  38691. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  38692. return BABYLON.Mesh.DOUBLESIDE;
  38693. }
  38694. if (orientation === undefined || orientation === null) {
  38695. return BABYLON.Mesh.FRONTSIDE;
  38696. }
  38697. return orientation;
  38698. };
  38699. /**
  38700. * Creates a box mesh.
  38701. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  38702. * The parameter `size` sets the size (float) of each box side (default 1).
  38703. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  38704. * 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).
  38705. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  38706. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38707. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38708. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38709. */
  38710. MeshBuilder.CreateBox = function (name, options, scene) {
  38711. var box = new BABYLON.Mesh(name, scene);
  38712. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38713. box.sideOrientation = options.sideOrientation;
  38714. var vertexData = BABYLON.VertexData.CreateBox(options);
  38715. vertexData.applyToMesh(box, options.updatable);
  38716. return box;
  38717. };
  38718. /**
  38719. * Creates a sphere mesh.
  38720. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  38721. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  38722. * 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`).
  38723. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  38724. * 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
  38725. * 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).
  38726. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38727. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38728. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38729. */
  38730. MeshBuilder.CreateSphere = function (name, options, scene) {
  38731. var sphere = new BABYLON.Mesh(name, scene);
  38732. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38733. sphere.sideOrientation = options.sideOrientation;
  38734. var vertexData = BABYLON.VertexData.CreateSphere(options);
  38735. vertexData.applyToMesh(sphere, options.updatable);
  38736. return sphere;
  38737. };
  38738. /**
  38739. * Creates a plane polygonal mesh. By default, this is a disc.
  38740. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  38741. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  38742. * 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.
  38743. * 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
  38744. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38745. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38746. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38747. */
  38748. MeshBuilder.CreateDisc = function (name, options, scene) {
  38749. var disc = new BABYLON.Mesh(name, scene);
  38750. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38751. disc.sideOrientation = options.sideOrientation;
  38752. var vertexData = BABYLON.VertexData.CreateDisc(options);
  38753. vertexData.applyToMesh(disc, options.updatable);
  38754. return disc;
  38755. };
  38756. /**
  38757. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  38758. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  38759. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  38760. * 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`).
  38761. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  38762. * 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.
  38763. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38764. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38765. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38766. */
  38767. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  38768. var sphere = new BABYLON.Mesh(name, scene);
  38769. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38770. sphere.sideOrientation = options.sideOrientation;
  38771. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  38772. vertexData.applyToMesh(sphere, options.updatable);
  38773. return sphere;
  38774. };
  38775. ;
  38776. /**
  38777. * Creates a ribbon mesh.
  38778. * 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.
  38779. *
  38780. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  38781. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  38782. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  38783. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  38784. * 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.
  38785. * 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.
  38786. * 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
  38787. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38788. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38789. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  38790. * 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.
  38791. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  38792. * 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
  38793. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  38794. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  38795. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38796. */
  38797. MeshBuilder.CreateRibbon = function (name, options, scene) {
  38798. var pathArray = options.pathArray;
  38799. var closeArray = options.closeArray;
  38800. var closePath = options.closePath;
  38801. var offset = options.offset;
  38802. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38803. var instance = options.instance;
  38804. var updatable = options.updatable;
  38805. if (instance) {
  38806. // positionFunction : ribbon case
  38807. // only pathArray and sideOrientation parameters are taken into account for positions update
  38808. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  38809. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  38810. var positionFunction = function (positions) {
  38811. var minlg = pathArray[0].length;
  38812. var i = 0;
  38813. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  38814. for (var si = 1; si <= ns; si++) {
  38815. for (var p = 0; p < pathArray.length; p++) {
  38816. var path = pathArray[p];
  38817. var l = path.length;
  38818. minlg = (minlg < l) ? minlg : l;
  38819. var j = 0;
  38820. while (j < minlg) {
  38821. positions[i] = path[j].x;
  38822. positions[i + 1] = path[j].y;
  38823. positions[i + 2] = path[j].z;
  38824. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  38825. BABYLON.Tmp.Vector3[0].x = path[j].x;
  38826. }
  38827. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  38828. BABYLON.Tmp.Vector3[1].x = path[j].x;
  38829. }
  38830. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  38831. BABYLON.Tmp.Vector3[0].y = path[j].y;
  38832. }
  38833. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  38834. BABYLON.Tmp.Vector3[1].y = path[j].y;
  38835. }
  38836. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  38837. BABYLON.Tmp.Vector3[0].z = path[j].z;
  38838. }
  38839. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  38840. BABYLON.Tmp.Vector3[1].z = path[j].z;
  38841. }
  38842. j++;
  38843. i += 3;
  38844. }
  38845. if (instance._closePath) {
  38846. positions[i] = path[0].x;
  38847. positions[i + 1] = path[0].y;
  38848. positions[i + 2] = path[0].z;
  38849. i += 3;
  38850. }
  38851. }
  38852. }
  38853. };
  38854. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38855. positionFunction(positions);
  38856. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  38857. instance._boundingInfo.update(instance._worldMatrix);
  38858. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  38859. if (options.colors) {
  38860. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38861. for (var c = 0; c < options.colors.length; c++) {
  38862. colors[c * 4] = options.colors[c].r;
  38863. colors[c * 4 + 1] = options.colors[c].g;
  38864. colors[c * 4 + 2] = options.colors[c].b;
  38865. colors[c * 4 + 3] = options.colors[c].a;
  38866. }
  38867. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  38868. }
  38869. if (options.uvs) {
  38870. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38871. for (var i = 0; i < options.uvs.length; i++) {
  38872. uvs[i * 2] = options.uvs[i].x;
  38873. uvs[i * 2 + 1] = options.uvs[i].y;
  38874. }
  38875. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  38876. }
  38877. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  38878. var indices = instance.getIndices();
  38879. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38880. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  38881. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  38882. if (instance._closePath) {
  38883. var indexFirst = 0;
  38884. var indexLast = 0;
  38885. for (var p = 0; p < pathArray.length; p++) {
  38886. indexFirst = instance._idx[p] * 3;
  38887. if (p + 1 < pathArray.length) {
  38888. indexLast = (instance._idx[p + 1] - 1) * 3;
  38889. }
  38890. else {
  38891. indexLast = normals.length - 3;
  38892. }
  38893. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38894. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38895. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38896. normals[indexLast] = normals[indexFirst];
  38897. normals[indexLast + 1] = normals[indexFirst + 1];
  38898. normals[indexLast + 2] = normals[indexFirst + 2];
  38899. }
  38900. }
  38901. if (!(instance.areNormalsFrozen)) {
  38902. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  38903. }
  38904. }
  38905. return instance;
  38906. }
  38907. else {
  38908. var ribbon = new BABYLON.Mesh(name, scene);
  38909. ribbon.sideOrientation = sideOrientation;
  38910. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  38911. if (closePath) {
  38912. ribbon._idx = vertexData._idx;
  38913. }
  38914. ribbon._closePath = closePath;
  38915. ribbon._closeArray = closeArray;
  38916. vertexData.applyToMesh(ribbon, updatable);
  38917. return ribbon;
  38918. }
  38919. };
  38920. /**
  38921. * Creates a cylinder or a cone mesh.
  38922. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  38923. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  38924. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  38925. * 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.
  38926. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  38927. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  38928. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  38929. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  38930. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  38931. * 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).
  38932. * 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
  38933. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  38934. * 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
  38935. * 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.
  38936. * If `enclose` is false, a ring surface is one element.
  38937. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  38938. * 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
  38939. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38940. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38941. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38942. */
  38943. MeshBuilder.CreateCylinder = function (name, options, scene) {
  38944. var cylinder = new BABYLON.Mesh(name, scene);
  38945. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38946. cylinder.sideOrientation = options.sideOrientation;
  38947. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  38948. vertexData.applyToMesh(cylinder, options.updatable);
  38949. return cylinder;
  38950. };
  38951. /**
  38952. * Creates a torus mesh.
  38953. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  38954. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  38955. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  38956. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  38957. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38958. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38959. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38960. */
  38961. MeshBuilder.CreateTorus = function (name, options, scene) {
  38962. var torus = new BABYLON.Mesh(name, scene);
  38963. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38964. torus.sideOrientation = options.sideOrientation;
  38965. var vertexData = BABYLON.VertexData.CreateTorus(options);
  38966. vertexData.applyToMesh(torus, options.updatable);
  38967. return torus;
  38968. };
  38969. /**
  38970. * Creates a torus knot mesh.
  38971. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  38972. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  38973. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  38974. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  38975. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  38976. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38977. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38978. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38979. */
  38980. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  38981. var torusKnot = new BABYLON.Mesh(name, scene);
  38982. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38983. torusKnot.sideOrientation = options.sideOrientation;
  38984. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  38985. vertexData.applyToMesh(torusKnot, options.updatable);
  38986. return torusKnot;
  38987. };
  38988. /**
  38989. * Creates a line system mesh.
  38990. * A line system is a pool of many lines gathered in a single mesh.
  38991. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  38992. * 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.
  38993. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  38994. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  38995. * 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
  38996. * 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
  38997. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  38998. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38999. */
  39000. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  39001. var instance = options.instance;
  39002. var lines = options.lines;
  39003. if (instance) {
  39004. var positionFunction = function (positions) {
  39005. var i = 0;
  39006. for (var l = 0; l < lines.length; l++) {
  39007. var points = lines[l];
  39008. for (var p = 0; p < points.length; p++) {
  39009. positions[i] = points[p].x;
  39010. positions[i + 1] = points[p].y;
  39011. positions[i + 2] = points[p].z;
  39012. i += 3;
  39013. }
  39014. }
  39015. };
  39016. instance.updateMeshPositions(positionFunction, false);
  39017. return instance;
  39018. }
  39019. // line system creation
  39020. var lineSystem = new BABYLON.LinesMesh(name, scene);
  39021. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  39022. vertexData.applyToMesh(lineSystem, options.updatable);
  39023. return lineSystem;
  39024. };
  39025. /**
  39026. * Creates a line mesh.
  39027. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  39028. * 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.
  39029. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  39030. * The parameter `points` is an array successive Vector3.
  39031. * 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
  39032. * When updating an instance, remember that only point positions can change, not the number of points.
  39033. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39034. */
  39035. MeshBuilder.CreateLines = function (name, options, scene) {
  39036. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  39037. return lines;
  39038. };
  39039. /**
  39040. * Creates a dashed line mesh.
  39041. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  39042. * 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.
  39043. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  39044. * The parameter `points` is an array successive Vector3.
  39045. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  39046. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  39047. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  39048. * 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
  39049. * When updating an instance, remember that only point positions can change, not the number of points.
  39050. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39051. */
  39052. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  39053. var points = options.points;
  39054. var instance = options.instance;
  39055. var gapSize = options.gapSize;
  39056. var dashNb = options.dashNb;
  39057. var dashSize = options.dashSize;
  39058. if (instance) {
  39059. var positionFunction = function (positions) {
  39060. var curvect = BABYLON.Vector3.Zero();
  39061. var nbSeg = positions.length / 6;
  39062. var lg = 0;
  39063. var nb = 0;
  39064. var shft = 0;
  39065. var dashshft = 0;
  39066. var curshft = 0;
  39067. var p = 0;
  39068. var i = 0;
  39069. var j = 0;
  39070. for (i = 0; i < points.length - 1; i++) {
  39071. points[i + 1].subtractToRef(points[i], curvect);
  39072. lg += curvect.length();
  39073. }
  39074. shft = lg / nbSeg;
  39075. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  39076. for (i = 0; i < points.length - 1; i++) {
  39077. points[i + 1].subtractToRef(points[i], curvect);
  39078. nb = Math.floor(curvect.length() / shft);
  39079. curvect.normalize();
  39080. j = 0;
  39081. while (j < nb && p < positions.length) {
  39082. curshft = shft * j;
  39083. positions[p] = points[i].x + curshft * curvect.x;
  39084. positions[p + 1] = points[i].y + curshft * curvect.y;
  39085. positions[p + 2] = points[i].z + curshft * curvect.z;
  39086. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  39087. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  39088. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  39089. p += 6;
  39090. j++;
  39091. }
  39092. }
  39093. while (p < positions.length) {
  39094. positions[p] = points[i].x;
  39095. positions[p + 1] = points[i].y;
  39096. positions[p + 2] = points[i].z;
  39097. p += 3;
  39098. }
  39099. };
  39100. instance.updateMeshPositions(positionFunction, false);
  39101. return instance;
  39102. }
  39103. // dashed lines creation
  39104. var dashedLines = new BABYLON.LinesMesh(name, scene);
  39105. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  39106. vertexData.applyToMesh(dashedLines, options.updatable);
  39107. dashedLines.dashSize = dashSize;
  39108. dashedLines.gapSize = gapSize;
  39109. return dashedLines;
  39110. };
  39111. /**
  39112. * Creates an extruded shape mesh.
  39113. * 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.
  39114. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  39115. *
  39116. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  39117. * 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
  39118. * extruded along the Z axis.
  39119. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  39120. * 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.
  39121. * The parameter `scale` (float, default 1) is the value to scale the shape.
  39122. * 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
  39123. * 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
  39124. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  39125. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39126. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39127. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39128. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39129. */
  39130. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  39131. var path = options.path;
  39132. var shape = options.shape;
  39133. var scale = options.scale || 1;
  39134. var rotation = options.rotation || 0;
  39135. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  39136. var updatable = options.updatable;
  39137. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39138. var instance = options.instance;
  39139. var invertUV = options.invertUV || false;
  39140. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  39141. };
  39142. /**
  39143. * Creates an custom extruded shape mesh.
  39144. * 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.
  39145. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  39146. *
  39147. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  39148. * 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
  39149. * extruded along the Z axis.
  39150. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  39151. * 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
  39152. * and the distance of this point from the begining of the path :
  39153. * ```javascript
  39154. * var rotationFunction = function(i, distance) {
  39155. * // do things
  39156. * return rotationValue; }
  39157. * ```
  39158. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  39159. * 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
  39160. * and the distance of this point from the begining of the path :
  39161. * ```javascript
  39162. * var scaleFunction = function(i, distance) {
  39163. * // do things
  39164. * return scaleValue;}
  39165. * ```
  39166. * It must returns a float value that will be the scale value applied to the shape on each path point.
  39167. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  39168. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  39169. * 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
  39170. * 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
  39171. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  39172. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39173. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39174. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39175. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39176. */
  39177. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  39178. var path = options.path;
  39179. var shape = options.shape;
  39180. var scaleFunction = options.scaleFunction || (function () { return 1; });
  39181. var rotationFunction = options.rotationFunction || (function () { return 0; });
  39182. var ribbonCloseArray = options.ribbonCloseArray || false;
  39183. var ribbonClosePath = options.ribbonClosePath || false;
  39184. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  39185. var updatable = options.updatable;
  39186. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39187. var instance = options.instance;
  39188. var invertUV = options.invertUV || false;
  39189. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  39190. };
  39191. /**
  39192. * Creates lathe mesh.
  39193. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  39194. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  39195. *
  39196. * 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
  39197. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  39198. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  39199. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  39200. * 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.
  39201. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  39202. * 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
  39203. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39204. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39205. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39206. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39207. */
  39208. MeshBuilder.CreateLathe = function (name, options, scene) {
  39209. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  39210. var closed = (options.closed === undefined) ? true : options.closed;
  39211. var shape = options.shape;
  39212. var radius = options.radius || 1;
  39213. var tessellation = options.tessellation || 64;
  39214. var updatable = options.updatable;
  39215. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39216. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  39217. var pi2 = Math.PI * 2;
  39218. var paths = new Array();
  39219. var invertUV = options.invertUV || false;
  39220. var i = 0;
  39221. var p = 0;
  39222. var step = pi2 / tessellation * arc;
  39223. var rotated;
  39224. var path = new Array();
  39225. ;
  39226. for (i = 0; i <= tessellation; i++) {
  39227. var path = [];
  39228. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  39229. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  39230. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  39231. }
  39232. for (p = 0; p < shape.length; p++) {
  39233. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  39234. path.push(rotated);
  39235. }
  39236. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  39237. 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));
  39238. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  39239. }
  39240. paths.push(path);
  39241. }
  39242. // lathe ribbon
  39243. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  39244. return lathe;
  39245. };
  39246. /**
  39247. * Creates a plane mesh.
  39248. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  39249. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  39250. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  39251. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  39252. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39253. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39254. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39255. */
  39256. MeshBuilder.CreatePlane = function (name, options, scene) {
  39257. var plane = new BABYLON.Mesh(name, scene);
  39258. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39259. plane.sideOrientation = options.sideOrientation;
  39260. var vertexData = BABYLON.VertexData.CreatePlane(options);
  39261. vertexData.applyToMesh(plane, options.updatable);
  39262. if (options.sourcePlane) {
  39263. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  39264. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  39265. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  39266. plane.rotate(vectorProduct, product);
  39267. }
  39268. return plane;
  39269. };
  39270. /**
  39271. * Creates a ground mesh.
  39272. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  39273. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  39274. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  39275. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39276. */
  39277. MeshBuilder.CreateGround = function (name, options, scene) {
  39278. var ground = new BABYLON.GroundMesh(name, scene);
  39279. ground._setReady(false);
  39280. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39281. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39282. ground._width = options.width || 1;
  39283. ground._height = options.height || 1;
  39284. ground._maxX = ground._width / 2;
  39285. ground._maxZ = ground._height / 2;
  39286. ground._minX = -ground._maxX;
  39287. ground._minZ = -ground._maxZ;
  39288. var vertexData = BABYLON.VertexData.CreateGround(options);
  39289. vertexData.applyToMesh(ground, options.updatable);
  39290. ground._setReady(true);
  39291. return ground;
  39292. };
  39293. /**
  39294. * Creates a tiled ground mesh.
  39295. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  39296. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  39297. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  39298. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  39299. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  39300. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  39301. * numbers of subdivisions on the ground width and height of each tile.
  39302. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39303. */
  39304. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  39305. var tiledGround = new BABYLON.Mesh(name, scene);
  39306. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  39307. vertexData.applyToMesh(tiledGround, options.updatable);
  39308. return tiledGround;
  39309. };
  39310. /**
  39311. * Creates a ground mesh from a height map.
  39312. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  39313. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  39314. * The parameter `url` sets the URL of the height map image resource.
  39315. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  39316. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  39317. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  39318. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  39319. * 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.
  39320. * 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).
  39321. * This function is passed the newly built mesh :
  39322. * ```javascript
  39323. * function(mesh) { // do things
  39324. * return; }
  39325. * ```
  39326. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39327. */
  39328. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  39329. var width = options.width || 10.0;
  39330. var height = options.height || 10.0;
  39331. var subdivisions = options.subdivisions || 1 | 0;
  39332. var minHeight = options.minHeight || 0.0;
  39333. var maxHeight = options.maxHeight || 10.0;
  39334. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39335. var updatable = options.updatable;
  39336. var onReady = options.onReady;
  39337. var ground = new BABYLON.GroundMesh(name, scene);
  39338. ground._subdivisionsX = subdivisions;
  39339. ground._subdivisionsY = subdivisions;
  39340. ground._width = width;
  39341. ground._height = height;
  39342. ground._maxX = ground._width / 2.0;
  39343. ground._maxZ = ground._height / 2.0;
  39344. ground._minX = -ground._maxX;
  39345. ground._minZ = -ground._maxZ;
  39346. ground._setReady(false);
  39347. var onload = function (img) {
  39348. // Getting height map data
  39349. var canvas = document.createElement("canvas");
  39350. var context = canvas.getContext("2d");
  39351. var bufferWidth = img.width;
  39352. var bufferHeight = img.height;
  39353. canvas.width = bufferWidth;
  39354. canvas.height = bufferHeight;
  39355. context.drawImage(img, 0, 0);
  39356. // Create VertexData from map data
  39357. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  39358. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  39359. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  39360. width: width, height: height,
  39361. subdivisions: subdivisions,
  39362. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  39363. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  39364. });
  39365. vertexData.applyToMesh(ground, updatable);
  39366. ground._setReady(true);
  39367. //execute ready callback, if set
  39368. if (onReady) {
  39369. onReady(ground);
  39370. }
  39371. };
  39372. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  39373. return ground;
  39374. };
  39375. /**
  39376. * Creates a tube mesh.
  39377. * 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.
  39378. *
  39379. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  39380. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  39381. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  39382. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  39383. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  39384. * 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.
  39385. * It must return a radius value (positive float) :
  39386. * ```javascript
  39387. * var radiusFunction = function(i, distance) {
  39388. * // do things
  39389. * return radius; }
  39390. * ```
  39391. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  39392. * 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
  39393. * 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
  39394. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39395. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39396. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39397. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39398. */
  39399. MeshBuilder.CreateTube = function (name, options, scene) {
  39400. var path = options.path;
  39401. var radius = options.radius || 1.0;
  39402. var tessellation = options.tessellation || 64 | 0;
  39403. var radiusFunction = options.radiusFunction;
  39404. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  39405. var invertUV = options.invertUV || false;
  39406. var updatable = options.updatable;
  39407. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39408. var instance = options.instance;
  39409. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  39410. // tube geometry
  39411. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  39412. var tangents = path3D.getTangents();
  39413. var normals = path3D.getNormals();
  39414. var distances = path3D.getDistances();
  39415. var pi2 = Math.PI * 2;
  39416. var step = pi2 / tessellation * arc;
  39417. var returnRadius = function () { return radius; };
  39418. var radiusFunctionFinal = radiusFunction || returnRadius;
  39419. var circlePath;
  39420. var rad;
  39421. var normal;
  39422. var rotated;
  39423. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  39424. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  39425. for (var i = 0; i < path.length; i++) {
  39426. rad = radiusFunctionFinal(i, distances[i]); // current radius
  39427. circlePath = Array(); // current circle array
  39428. normal = normals[i]; // current normal
  39429. for (var t = 0; t < tessellation; t++) {
  39430. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  39431. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  39432. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  39433. rotated.scaleInPlace(rad).addInPlace(path[i]);
  39434. circlePath[t] = rotated;
  39435. }
  39436. circlePaths[index] = circlePath;
  39437. index++;
  39438. }
  39439. // cap
  39440. var capPath = function (nbPoints, pathIndex) {
  39441. var pointCap = Array();
  39442. for (var i = 0; i < nbPoints; i++) {
  39443. pointCap.push(path[pathIndex]);
  39444. }
  39445. return pointCap;
  39446. };
  39447. switch (cap) {
  39448. case BABYLON.Mesh.NO_CAP:
  39449. break;
  39450. case BABYLON.Mesh.CAP_START:
  39451. circlePaths[0] = capPath(tessellation, 0);
  39452. circlePaths[1] = circlePaths[2].slice(0);
  39453. break;
  39454. case BABYLON.Mesh.CAP_END:
  39455. circlePaths[index] = circlePaths[index - 1].slice(0);
  39456. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  39457. break;
  39458. case BABYLON.Mesh.CAP_ALL:
  39459. circlePaths[0] = capPath(tessellation, 0);
  39460. circlePaths[1] = circlePaths[2].slice(0);
  39461. circlePaths[index] = circlePaths[index - 1].slice(0);
  39462. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  39463. break;
  39464. default:
  39465. break;
  39466. }
  39467. return circlePaths;
  39468. };
  39469. var path3D;
  39470. var pathArray;
  39471. if (instance) {
  39472. var arc = options.arc || instance.arc;
  39473. path3D = (instance.path3D).update(path);
  39474. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  39475. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  39476. instance.path3D = path3D;
  39477. instance.pathArray = pathArray;
  39478. instance.arc = arc;
  39479. return instance;
  39480. }
  39481. // tube creation
  39482. path3D = new BABYLON.Path3D(path);
  39483. var newPathArray = new Array();
  39484. cap = (cap < 0 || cap > 3) ? 0 : cap;
  39485. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  39486. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  39487. tube.pathArray = pathArray;
  39488. tube.path3D = path3D;
  39489. tube.tessellation = tessellation;
  39490. tube.cap = cap;
  39491. tube.arc = options.arc;
  39492. return tube;
  39493. };
  39494. /**
  39495. * Creates a polyhedron mesh.
  39496. *
  39497. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  39498. * 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
  39499. * to choose the wanted type.
  39500. * The parameter `size` (positive float, default 1) sets the polygon size.
  39501. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  39502. * 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`.
  39503. * 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
  39504. * 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)`).
  39505. * 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
  39506. * 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.
  39507. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39508. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39509. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39510. */
  39511. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  39512. var polyhedron = new BABYLON.Mesh(name, scene);
  39513. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39514. polyhedron.sideOrientation = options.sideOrientation;
  39515. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  39516. vertexData.applyToMesh(polyhedron, options.updatable);
  39517. return polyhedron;
  39518. };
  39519. /**
  39520. * Creates a decal mesh.
  39521. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  39522. * 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.
  39523. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  39524. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  39525. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  39526. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  39527. */
  39528. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  39529. var indices = sourceMesh.getIndices();
  39530. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39531. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39532. var position = options.position || BABYLON.Vector3.Zero();
  39533. var normal = options.normal || BABYLON.Vector3.Up();
  39534. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  39535. var angle = options.angle || 0;
  39536. // Getting correct rotation
  39537. if (!normal) {
  39538. var target = new BABYLON.Vector3(0, 0, 1);
  39539. var camera = sourceMesh.getScene().activeCamera;
  39540. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  39541. normal = camera.globalPosition.subtract(cameraWorldTarget);
  39542. }
  39543. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  39544. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  39545. var pitch = Math.atan2(normal.y, len);
  39546. // Matrix
  39547. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  39548. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  39549. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  39550. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  39551. var vertexData = new BABYLON.VertexData();
  39552. vertexData.indices = [];
  39553. vertexData.positions = [];
  39554. vertexData.normals = [];
  39555. vertexData.uvs = [];
  39556. var currentVertexDataIndex = 0;
  39557. var extractDecalVector3 = function (indexId) {
  39558. var vertexId = indices[indexId];
  39559. var result = new BABYLON.PositionNormalVertex();
  39560. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  39561. // Send vector to decal local world
  39562. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  39563. // Get normal
  39564. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  39565. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  39566. return result;
  39567. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  39568. var clip = function (vertices, axis) {
  39569. if (vertices.length === 0) {
  39570. return vertices;
  39571. }
  39572. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  39573. var clipVertices = function (v0, v1) {
  39574. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  39575. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  39576. };
  39577. var result = new Array();
  39578. for (var index = 0; index < vertices.length; index += 3) {
  39579. var v1Out;
  39580. var v2Out;
  39581. var v3Out;
  39582. var total = 0;
  39583. var nV1, nV2, nV3, nV4;
  39584. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  39585. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  39586. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  39587. v1Out = d1 > 0;
  39588. v2Out = d2 > 0;
  39589. v3Out = d3 > 0;
  39590. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  39591. switch (total) {
  39592. case 0:
  39593. result.push(vertices[index]);
  39594. result.push(vertices[index + 1]);
  39595. result.push(vertices[index + 2]);
  39596. break;
  39597. case 1:
  39598. if (v1Out) {
  39599. nV1 = vertices[index + 1];
  39600. nV2 = vertices[index + 2];
  39601. nV3 = clipVertices(vertices[index], nV1);
  39602. nV4 = clipVertices(vertices[index], nV2);
  39603. }
  39604. if (v2Out) {
  39605. nV1 = vertices[index];
  39606. nV2 = vertices[index + 2];
  39607. nV3 = clipVertices(vertices[index + 1], nV1);
  39608. nV4 = clipVertices(vertices[index + 1], nV2);
  39609. result.push(nV3);
  39610. result.push(nV2.clone());
  39611. result.push(nV1.clone());
  39612. result.push(nV2.clone());
  39613. result.push(nV3.clone());
  39614. result.push(nV4);
  39615. break;
  39616. }
  39617. if (v3Out) {
  39618. nV1 = vertices[index];
  39619. nV2 = vertices[index + 1];
  39620. nV3 = clipVertices(vertices[index + 2], nV1);
  39621. nV4 = clipVertices(vertices[index + 2], nV2);
  39622. }
  39623. result.push(nV1.clone());
  39624. result.push(nV2.clone());
  39625. result.push(nV3);
  39626. result.push(nV4);
  39627. result.push(nV3.clone());
  39628. result.push(nV2.clone());
  39629. break;
  39630. case 2:
  39631. if (!v1Out) {
  39632. nV1 = vertices[index].clone();
  39633. nV2 = clipVertices(nV1, vertices[index + 1]);
  39634. nV3 = clipVertices(nV1, vertices[index + 2]);
  39635. result.push(nV1);
  39636. result.push(nV2);
  39637. result.push(nV3);
  39638. }
  39639. if (!v2Out) {
  39640. nV1 = vertices[index + 1].clone();
  39641. nV2 = clipVertices(nV1, vertices[index + 2]);
  39642. nV3 = clipVertices(nV1, vertices[index]);
  39643. result.push(nV1);
  39644. result.push(nV2);
  39645. result.push(nV3);
  39646. }
  39647. if (!v3Out) {
  39648. nV1 = vertices[index + 2].clone();
  39649. nV2 = clipVertices(nV1, vertices[index]);
  39650. nV3 = clipVertices(nV1, vertices[index + 1]);
  39651. result.push(nV1);
  39652. result.push(nV2);
  39653. result.push(nV3);
  39654. }
  39655. break;
  39656. case 3:
  39657. break;
  39658. }
  39659. }
  39660. return result;
  39661. };
  39662. for (var index = 0; index < indices.length; index += 3) {
  39663. var faceVertices = new Array();
  39664. faceVertices.push(extractDecalVector3(index));
  39665. faceVertices.push(extractDecalVector3(index + 1));
  39666. faceVertices.push(extractDecalVector3(index + 2));
  39667. // Clip
  39668. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  39669. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  39670. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  39671. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  39672. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  39673. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  39674. if (faceVertices.length === 0) {
  39675. continue;
  39676. }
  39677. // Add UVs and get back to world
  39678. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  39679. var vertex = faceVertices[vIndex];
  39680. //TODO check for Int32Array | Uint32Array | Uint16Array
  39681. vertexData.indices.push(currentVertexDataIndex);
  39682. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  39683. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  39684. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  39685. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  39686. currentVertexDataIndex++;
  39687. }
  39688. }
  39689. // Return mesh
  39690. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  39691. vertexData.applyToMesh(decal);
  39692. decal.position = position.clone();
  39693. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  39694. return decal;
  39695. };
  39696. // Privates
  39697. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  39698. // extrusion geometry
  39699. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  39700. var tangents = path3D.getTangents();
  39701. var normals = path3D.getNormals();
  39702. var binormals = path3D.getBinormals();
  39703. var distances = path3D.getDistances();
  39704. var angle = 0;
  39705. var returnScale = function () { return scale; };
  39706. var returnRotation = function () { return rotation; };
  39707. var rotate = custom ? rotateFunction : returnRotation;
  39708. var scl = custom ? scaleFunction : returnScale;
  39709. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  39710. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  39711. for (var i = 0; i < curve.length; i++) {
  39712. var shapePath = new Array();
  39713. var angleStep = rotate(i, distances[i]);
  39714. var scaleRatio = scl(i, distances[i]);
  39715. for (var p = 0; p < shape.length; p++) {
  39716. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  39717. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  39718. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  39719. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  39720. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  39721. shapePath[p] = rotated;
  39722. }
  39723. shapePaths[index] = shapePath;
  39724. angle += angleStep;
  39725. index++;
  39726. }
  39727. // cap
  39728. var capPath = function (shapePath) {
  39729. var pointCap = Array();
  39730. var barycenter = BABYLON.Vector3.Zero();
  39731. var i;
  39732. for (i = 0; i < shapePath.length; i++) {
  39733. barycenter.addInPlace(shapePath[i]);
  39734. }
  39735. barycenter.scaleInPlace(1.0 / shapePath.length);
  39736. for (i = 0; i < shapePath.length; i++) {
  39737. pointCap.push(barycenter);
  39738. }
  39739. return pointCap;
  39740. };
  39741. switch (cap) {
  39742. case BABYLON.Mesh.NO_CAP:
  39743. break;
  39744. case BABYLON.Mesh.CAP_START:
  39745. shapePaths[0] = capPath(shapePaths[2]);
  39746. shapePaths[1] = shapePaths[2];
  39747. break;
  39748. case BABYLON.Mesh.CAP_END:
  39749. shapePaths[index] = shapePaths[index - 1];
  39750. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  39751. break;
  39752. case BABYLON.Mesh.CAP_ALL:
  39753. shapePaths[0] = capPath(shapePaths[2]);
  39754. shapePaths[1] = shapePaths[2];
  39755. shapePaths[index] = shapePaths[index - 1];
  39756. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  39757. break;
  39758. default:
  39759. break;
  39760. }
  39761. return shapePaths;
  39762. };
  39763. var path3D;
  39764. var pathArray;
  39765. if (instance) {
  39766. path3D = (instance.path3D).update(curve);
  39767. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  39768. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  39769. return instance;
  39770. }
  39771. // extruded shape creation
  39772. path3D = new BABYLON.Path3D(curve);
  39773. var newShapePaths = new Array();
  39774. cap = (cap < 0 || cap > 3) ? 0 : cap;
  39775. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  39776. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  39777. extrudedGeneric.pathArray = pathArray;
  39778. extrudedGeneric.path3D = path3D;
  39779. extrudedGeneric.cap = cap;
  39780. return extrudedGeneric;
  39781. };
  39782. return MeshBuilder;
  39783. }());
  39784. BABYLON.MeshBuilder = MeshBuilder;
  39785. })(BABYLON || (BABYLON = {}));
  39786. //# sourceMappingURL=babylon.meshBuilder.js.map
  39787. var BABYLON;
  39788. (function (BABYLON) {
  39789. var AudioEngine = (function () {
  39790. function AudioEngine() {
  39791. this._audioContext = null;
  39792. this._audioContextInitialized = false;
  39793. this.canUseWebAudio = false;
  39794. this.WarnedWebAudioUnsupported = false;
  39795. this.unlocked = false;
  39796. this.isMP3supported = false;
  39797. this.isOGGsupported = false;
  39798. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  39799. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  39800. this.canUseWebAudio = true;
  39801. }
  39802. var audioElem = document.createElement('audio');
  39803. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  39804. this.isMP3supported = true;
  39805. }
  39806. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  39807. this.isOGGsupported = true;
  39808. }
  39809. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  39810. this._unlockiOSaudio();
  39811. }
  39812. else {
  39813. this.unlocked = true;
  39814. }
  39815. }
  39816. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  39817. get: function () {
  39818. if (!this._audioContextInitialized) {
  39819. this._initializeAudioContext();
  39820. }
  39821. return this._audioContext;
  39822. },
  39823. enumerable: true,
  39824. configurable: true
  39825. });
  39826. AudioEngine.prototype._unlockiOSaudio = function () {
  39827. var _this = this;
  39828. var unlockaudio = function () {
  39829. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  39830. var source = _this.audioContext.createBufferSource();
  39831. source.buffer = buffer;
  39832. source.connect(_this.audioContext.destination);
  39833. source.start(0);
  39834. setTimeout(function () {
  39835. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  39836. _this.unlocked = true;
  39837. window.removeEventListener('touchend', unlockaudio, false);
  39838. if (_this.onAudioUnlocked) {
  39839. _this.onAudioUnlocked();
  39840. }
  39841. }
  39842. }, 0);
  39843. };
  39844. window.addEventListener('touchend', unlockaudio, false);
  39845. };
  39846. AudioEngine.prototype._initializeAudioContext = function () {
  39847. try {
  39848. if (this.canUseWebAudio) {
  39849. this._audioContext = new AudioContext();
  39850. // create a global volume gain node
  39851. this.masterGain = this._audioContext.createGain();
  39852. this.masterGain.gain.value = 1;
  39853. this.masterGain.connect(this._audioContext.destination);
  39854. this._audioContextInitialized = true;
  39855. }
  39856. }
  39857. catch (e) {
  39858. this.canUseWebAudio = false;
  39859. BABYLON.Tools.Error("Web Audio: " + e.message);
  39860. }
  39861. };
  39862. AudioEngine.prototype.dispose = function () {
  39863. if (this.canUseWebAudio && this._audioContextInitialized) {
  39864. if (this._connectedAnalyser) {
  39865. this._connectedAnalyser.stopDebugCanvas();
  39866. this._connectedAnalyser.dispose();
  39867. this.masterGain.disconnect();
  39868. this.masterGain.connect(this._audioContext.destination);
  39869. this._connectedAnalyser = null;
  39870. }
  39871. this.masterGain.gain.value = 1;
  39872. }
  39873. this.WarnedWebAudioUnsupported = false;
  39874. };
  39875. AudioEngine.prototype.getGlobalVolume = function () {
  39876. if (this.canUseWebAudio && this._audioContextInitialized) {
  39877. return this.masterGain.gain.value;
  39878. }
  39879. else {
  39880. return -1;
  39881. }
  39882. };
  39883. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  39884. if (this.canUseWebAudio && this._audioContextInitialized) {
  39885. this.masterGain.gain.value = newVolume;
  39886. }
  39887. };
  39888. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  39889. if (this._connectedAnalyser) {
  39890. this._connectedAnalyser.stopDebugCanvas();
  39891. }
  39892. if (this.canUseWebAudio && this._audioContextInitialized) {
  39893. this._connectedAnalyser = analyser;
  39894. this.masterGain.disconnect();
  39895. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  39896. }
  39897. };
  39898. return AudioEngine;
  39899. }());
  39900. BABYLON.AudioEngine = AudioEngine;
  39901. })(BABYLON || (BABYLON = {}));
  39902. //# sourceMappingURL=babylon.audioEngine.js.map
  39903. var BABYLON;
  39904. (function (BABYLON) {
  39905. var Sound = (function () {
  39906. /**
  39907. * Create a sound and attach it to a scene
  39908. * @param name Name of your sound
  39909. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  39910. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  39911. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  39912. */
  39913. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  39914. var _this = this;
  39915. this.autoplay = false;
  39916. this.loop = false;
  39917. this.useCustomAttenuation = false;
  39918. this.spatialSound = false;
  39919. this.refDistance = 1;
  39920. this.rolloffFactor = 1;
  39921. this.maxDistance = 100;
  39922. this.distanceModel = "linear";
  39923. this._panningModel = "equalpower";
  39924. this._playbackRate = 1;
  39925. this._streaming = false;
  39926. this._startTime = 0;
  39927. this._startOffset = 0;
  39928. this._position = BABYLON.Vector3.Zero();
  39929. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  39930. this._volume = 1;
  39931. this._isLoaded = false;
  39932. this._isReadyToPlay = false;
  39933. this.isPlaying = false;
  39934. this.isPaused = false;
  39935. this._isDirectional = false;
  39936. // Used if you'd like to create a directional sound.
  39937. // If not set, the sound will be omnidirectional
  39938. this._coneInnerAngle = 360;
  39939. this._coneOuterAngle = 360;
  39940. this._coneOuterGain = 0;
  39941. this._isOutputConnected = false;
  39942. this._urlType = "Unknown";
  39943. this.name = name;
  39944. this._scene = scene;
  39945. this._readyToPlayCallback = readyToPlayCallback;
  39946. // Default custom attenuation function is a linear attenuation
  39947. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  39948. if (currentDistance < maxDistance) {
  39949. return currentVolume * (1 - currentDistance / maxDistance);
  39950. }
  39951. else {
  39952. return 0;
  39953. }
  39954. };
  39955. if (options) {
  39956. this.autoplay = options.autoplay || false;
  39957. this.loop = options.loop || false;
  39958. // if volume === 0, we need another way to check this option
  39959. if (options.volume !== undefined) {
  39960. this._volume = options.volume;
  39961. }
  39962. this.spatialSound = options.spatialSound || false;
  39963. this.maxDistance = options.maxDistance || 100;
  39964. this.useCustomAttenuation = options.useCustomAttenuation || false;
  39965. this.rolloffFactor = options.rolloffFactor || 1;
  39966. this.refDistance = options.refDistance || 1;
  39967. this.distanceModel = options.distanceModel || "linear";
  39968. this._playbackRate = options.playbackRate || 1;
  39969. this._streaming = options.streaming || false;
  39970. }
  39971. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39972. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  39973. this._soundGain.gain.value = this._volume;
  39974. this._inputAudioNode = this._soundGain;
  39975. this._ouputAudioNode = this._soundGain;
  39976. if (this.spatialSound) {
  39977. this._createSpatialParameters();
  39978. }
  39979. this._scene.mainSoundTrack.AddSound(this);
  39980. var validParameter = true;
  39981. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  39982. if (urlOrArrayBuffer) {
  39983. if (typeof (urlOrArrayBuffer) === "string")
  39984. this._urlType = "String";
  39985. if (Array.isArray(urlOrArrayBuffer))
  39986. this._urlType = "Array";
  39987. if (urlOrArrayBuffer instanceof ArrayBuffer)
  39988. this._urlType = "ArrayBuffer";
  39989. var urls = [];
  39990. var codecSupportedFound = false;
  39991. switch (this._urlType) {
  39992. case "ArrayBuffer":
  39993. if (urlOrArrayBuffer.byteLength > 0) {
  39994. codecSupportedFound = true;
  39995. this._soundLoaded(urlOrArrayBuffer);
  39996. }
  39997. break;
  39998. case "String":
  39999. urls.push(urlOrArrayBuffer);
  40000. case "Array":
  40001. if (urls.length === 0)
  40002. urls = urlOrArrayBuffer;
  40003. // If we found a supported format, we load it immediately and stop the loop
  40004. for (var i = 0; i < urls.length; i++) {
  40005. var url = urls[i];
  40006. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  40007. codecSupportedFound = true;
  40008. }
  40009. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  40010. codecSupportedFound = true;
  40011. }
  40012. if (url.indexOf(".wav", url.length - 4) !== -1) {
  40013. codecSupportedFound = true;
  40014. }
  40015. if (codecSupportedFound) {
  40016. // Loading sound using XHR2
  40017. if (!this._streaming) {
  40018. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  40019. }
  40020. else {
  40021. this._htmlAudioElement = new Audio(url);
  40022. this._htmlAudioElement.controls = false;
  40023. this._htmlAudioElement.loop = this.loop;
  40024. this._htmlAudioElement.crossOrigin = "anonymous";
  40025. this._htmlAudioElement.preload = "auto";
  40026. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  40027. _this._isReadyToPlay = true;
  40028. if (_this.autoplay) {
  40029. _this.play();
  40030. }
  40031. if (_this._readyToPlayCallback) {
  40032. _this._readyToPlayCallback();
  40033. }
  40034. });
  40035. document.body.appendChild(this._htmlAudioElement);
  40036. }
  40037. break;
  40038. }
  40039. }
  40040. break;
  40041. default:
  40042. validParameter = false;
  40043. break;
  40044. }
  40045. if (!validParameter) {
  40046. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  40047. }
  40048. else {
  40049. if (!codecSupportedFound) {
  40050. this._isReadyToPlay = true;
  40051. // Simulating a ready to play event to avoid breaking code path
  40052. if (this._readyToPlayCallback) {
  40053. window.setTimeout(function () {
  40054. _this._readyToPlayCallback();
  40055. }, 1000);
  40056. }
  40057. }
  40058. }
  40059. }
  40060. }
  40061. else {
  40062. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  40063. this._scene.mainSoundTrack.AddSound(this);
  40064. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  40065. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  40066. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  40067. }
  40068. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  40069. if (this._readyToPlayCallback) {
  40070. window.setTimeout(function () {
  40071. _this._readyToPlayCallback();
  40072. }, 1000);
  40073. }
  40074. }
  40075. }
  40076. Sound.prototype.dispose = function () {
  40077. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  40078. if (this.isPlaying) {
  40079. this.stop();
  40080. }
  40081. this._isReadyToPlay = false;
  40082. if (this.soundTrackId === -1) {
  40083. this._scene.mainSoundTrack.RemoveSound(this);
  40084. }
  40085. else {
  40086. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  40087. }
  40088. if (this._soundGain) {
  40089. this._soundGain.disconnect();
  40090. this._soundGain = null;
  40091. }
  40092. if (this._soundPanner) {
  40093. this._soundPanner.disconnect();
  40094. this._soundPanner = null;
  40095. }
  40096. if (this._soundSource) {
  40097. this._soundSource.disconnect();
  40098. this._soundSource = null;
  40099. }
  40100. this._audioBuffer = null;
  40101. if (this._htmlAudioElement) {
  40102. this._htmlAudioElement.pause();
  40103. this._htmlAudioElement.src = "";
  40104. document.body.removeChild(this._htmlAudioElement);
  40105. }
  40106. if (this._connectedMesh) {
  40107. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  40108. this._connectedMesh = null;
  40109. }
  40110. }
  40111. };
  40112. Sound.prototype.isReady = function () {
  40113. return this._isReadyToPlay;
  40114. };
  40115. Sound.prototype._soundLoaded = function (audioData) {
  40116. var _this = this;
  40117. this._isLoaded = true;
  40118. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  40119. _this._audioBuffer = buffer;
  40120. _this._isReadyToPlay = true;
  40121. if (_this.autoplay) {
  40122. _this.play();
  40123. }
  40124. if (_this._readyToPlayCallback) {
  40125. _this._readyToPlayCallback();
  40126. }
  40127. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  40128. };
  40129. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  40130. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40131. this._audioBuffer = audioBuffer;
  40132. this._isReadyToPlay = true;
  40133. }
  40134. };
  40135. Sound.prototype.updateOptions = function (options) {
  40136. if (options) {
  40137. this.loop = options.loop || this.loop;
  40138. this.maxDistance = options.maxDistance || this.maxDistance;
  40139. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  40140. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  40141. this.refDistance = options.refDistance || this.refDistance;
  40142. this.distanceModel = options.distanceModel || this.distanceModel;
  40143. this._playbackRate = options.playbackRate || this._playbackRate;
  40144. this._updateSpatialParameters();
  40145. if (this.isPlaying) {
  40146. if (this._streaming) {
  40147. this._htmlAudioElement.playbackRate = this._playbackRate;
  40148. }
  40149. else {
  40150. this._soundSource.playbackRate.value = this._playbackRate;
  40151. }
  40152. }
  40153. }
  40154. };
  40155. Sound.prototype._createSpatialParameters = function () {
  40156. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40157. if (this._scene.headphone) {
  40158. this._panningModel = "HRTF";
  40159. }
  40160. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  40161. this._updateSpatialParameters();
  40162. this._soundPanner.connect(this._ouputAudioNode);
  40163. this._inputAudioNode = this._soundPanner;
  40164. }
  40165. };
  40166. Sound.prototype._updateSpatialParameters = function () {
  40167. if (this.spatialSound) {
  40168. if (this.useCustomAttenuation) {
  40169. // Tricks to disable in a way embedded Web Audio attenuation
  40170. this._soundPanner.distanceModel = "linear";
  40171. this._soundPanner.maxDistance = Number.MAX_VALUE;
  40172. this._soundPanner.refDistance = 1;
  40173. this._soundPanner.rolloffFactor = 1;
  40174. this._soundPanner.panningModel = this._panningModel;
  40175. }
  40176. else {
  40177. this._soundPanner.distanceModel = this.distanceModel;
  40178. this._soundPanner.maxDistance = this.maxDistance;
  40179. this._soundPanner.refDistance = this.refDistance;
  40180. this._soundPanner.rolloffFactor = this.rolloffFactor;
  40181. this._soundPanner.panningModel = this._panningModel;
  40182. }
  40183. }
  40184. };
  40185. Sound.prototype.switchPanningModelToHRTF = function () {
  40186. this._panningModel = "HRTF";
  40187. this._switchPanningModel();
  40188. };
  40189. Sound.prototype.switchPanningModelToEqualPower = function () {
  40190. this._panningModel = "equalpower";
  40191. this._switchPanningModel();
  40192. };
  40193. Sound.prototype._switchPanningModel = function () {
  40194. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  40195. this._soundPanner.panningModel = this._panningModel;
  40196. }
  40197. };
  40198. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  40199. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40200. if (this._isOutputConnected) {
  40201. this._ouputAudioNode.disconnect();
  40202. }
  40203. this._ouputAudioNode.connect(soundTrackAudioNode);
  40204. this._isOutputConnected = true;
  40205. }
  40206. };
  40207. /**
  40208. * Transform this sound into a directional source
  40209. * @param coneInnerAngle Size of the inner cone in degree
  40210. * @param coneOuterAngle Size of the outer cone in degree
  40211. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  40212. */
  40213. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  40214. if (coneOuterAngle < coneInnerAngle) {
  40215. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  40216. return;
  40217. }
  40218. this._coneInnerAngle = coneInnerAngle;
  40219. this._coneOuterAngle = coneOuterAngle;
  40220. this._coneOuterGain = coneOuterGain;
  40221. this._isDirectional = true;
  40222. if (this.isPlaying && this.loop) {
  40223. this.stop();
  40224. this.play();
  40225. }
  40226. };
  40227. Sound.prototype.setPosition = function (newPosition) {
  40228. this._position = newPosition;
  40229. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  40230. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  40231. }
  40232. };
  40233. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  40234. this._localDirection = newLocalDirection;
  40235. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  40236. this._updateDirection();
  40237. }
  40238. };
  40239. Sound.prototype._updateDirection = function () {
  40240. var mat = this._connectedMesh.getWorldMatrix();
  40241. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  40242. direction.normalize();
  40243. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  40244. };
  40245. Sound.prototype.updateDistanceFromListener = function () {
  40246. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  40247. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  40248. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  40249. }
  40250. };
  40251. Sound.prototype.setAttenuationFunction = function (callback) {
  40252. this._customAttenuationFunction = callback;
  40253. };
  40254. /**
  40255. * Play the sound
  40256. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  40257. * @param offset (optional) Start the sound setting it at a specific time
  40258. */
  40259. Sound.prototype.play = function (time, offset) {
  40260. var _this = this;
  40261. if (this._isReadyToPlay && this._scene.audioEnabled) {
  40262. try {
  40263. if (this._startOffset < 0) {
  40264. time = -this._startOffset;
  40265. this._startOffset = 0;
  40266. }
  40267. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  40268. if (!this._soundSource || !this._streamingSource) {
  40269. if (this.spatialSound) {
  40270. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  40271. if (this._isDirectional) {
  40272. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  40273. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  40274. this._soundPanner.coneOuterGain = this._coneOuterGain;
  40275. if (this._connectedMesh) {
  40276. this._updateDirection();
  40277. }
  40278. else {
  40279. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  40280. }
  40281. }
  40282. }
  40283. }
  40284. if (this._streaming) {
  40285. if (!this._streamingSource) {
  40286. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  40287. this._htmlAudioElement.onended = function () { _this._onended(); };
  40288. this._htmlAudioElement.playbackRate = this._playbackRate;
  40289. }
  40290. this._streamingSource.disconnect();
  40291. this._streamingSource.connect(this._inputAudioNode);
  40292. this._htmlAudioElement.play();
  40293. }
  40294. else {
  40295. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  40296. this._soundSource.buffer = this._audioBuffer;
  40297. this._soundSource.connect(this._inputAudioNode);
  40298. this._soundSource.loop = this.loop;
  40299. this._soundSource.playbackRate.value = this._playbackRate;
  40300. this._soundSource.onended = function () { _this._onended(); };
  40301. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  40302. }
  40303. this._startTime = startTime;
  40304. this.isPlaying = true;
  40305. this.isPaused = false;
  40306. }
  40307. catch (ex) {
  40308. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  40309. }
  40310. }
  40311. };
  40312. Sound.prototype._onended = function () {
  40313. this.isPlaying = false;
  40314. if (this.onended) {
  40315. this.onended();
  40316. }
  40317. };
  40318. /**
  40319. * Stop the sound
  40320. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  40321. */
  40322. Sound.prototype.stop = function (time) {
  40323. if (this.isPlaying) {
  40324. if (this._streaming) {
  40325. this._htmlAudioElement.pause();
  40326. // Test needed for Firefox or it will generate an Invalid State Error
  40327. if (this._htmlAudioElement.currentTime > 0) {
  40328. this._htmlAudioElement.currentTime = 0;
  40329. }
  40330. }
  40331. else {
  40332. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  40333. this._soundSource.stop(stopTime);
  40334. this._soundSource.onended = null;
  40335. if (!this.isPaused) {
  40336. this._startOffset = 0;
  40337. }
  40338. }
  40339. this.isPlaying = false;
  40340. }
  40341. };
  40342. Sound.prototype.pause = function () {
  40343. if (this.isPlaying) {
  40344. this.isPaused = true;
  40345. if (this._streaming) {
  40346. this._htmlAudioElement.pause();
  40347. }
  40348. else {
  40349. this.stop(0);
  40350. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  40351. }
  40352. }
  40353. };
  40354. Sound.prototype.setVolume = function (newVolume, time) {
  40355. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40356. if (time) {
  40357. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  40358. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  40359. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  40360. }
  40361. else {
  40362. this._soundGain.gain.value = newVolume;
  40363. }
  40364. }
  40365. this._volume = newVolume;
  40366. };
  40367. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  40368. this._playbackRate = newPlaybackRate;
  40369. if (this.isPlaying) {
  40370. if (this._streaming) {
  40371. this._htmlAudioElement.playbackRate = this._playbackRate;
  40372. }
  40373. else {
  40374. this._soundSource.playbackRate.value = this._playbackRate;
  40375. }
  40376. }
  40377. };
  40378. Sound.prototype.getVolume = function () {
  40379. return this._volume;
  40380. };
  40381. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  40382. var _this = this;
  40383. if (this._connectedMesh) {
  40384. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  40385. this._registerFunc = null;
  40386. }
  40387. this._connectedMesh = meshToConnectTo;
  40388. if (!this.spatialSound) {
  40389. this.spatialSound = true;
  40390. this._createSpatialParameters();
  40391. if (this.isPlaying && this.loop) {
  40392. this.stop();
  40393. this.play();
  40394. }
  40395. }
  40396. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  40397. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  40398. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  40399. };
  40400. Sound.prototype.detachFromMesh = function () {
  40401. if (this._connectedMesh) {
  40402. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  40403. this._registerFunc = null;
  40404. this._connectedMesh = null;
  40405. }
  40406. };
  40407. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  40408. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  40409. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  40410. this._updateDirection();
  40411. }
  40412. };
  40413. Sound.prototype.clone = function () {
  40414. var _this = this;
  40415. if (!this._streaming) {
  40416. var setBufferAndRun = function () {
  40417. if (_this._isReadyToPlay) {
  40418. clonedSound._audioBuffer = _this.getAudioBuffer();
  40419. clonedSound._isReadyToPlay = true;
  40420. if (clonedSound.autoplay) {
  40421. clonedSound.play();
  40422. }
  40423. }
  40424. else {
  40425. window.setTimeout(setBufferAndRun, 300);
  40426. }
  40427. };
  40428. var currentOptions = {
  40429. autoplay: this.autoplay, loop: this.loop,
  40430. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  40431. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  40432. refDistance: this.refDistance, distanceModel: this.distanceModel
  40433. };
  40434. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  40435. if (this.useCustomAttenuation) {
  40436. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  40437. }
  40438. clonedSound.setPosition(this._position);
  40439. clonedSound.setPlaybackRate(this._playbackRate);
  40440. setBufferAndRun();
  40441. return clonedSound;
  40442. }
  40443. else {
  40444. return null;
  40445. }
  40446. };
  40447. Sound.prototype.getAudioBuffer = function () {
  40448. return this._audioBuffer;
  40449. };
  40450. Sound.prototype.serialize = function () {
  40451. var serializationObject = {
  40452. name: this.name,
  40453. url: this.name,
  40454. autoplay: this.autoplay,
  40455. loop: this.loop,
  40456. volume: this._volume,
  40457. spatialSound: this.spatialSound,
  40458. maxDistance: this.maxDistance,
  40459. rolloffFactor: this.rolloffFactor,
  40460. refDistance: this.refDistance,
  40461. distanceModel: this.distanceModel,
  40462. playbackRate: this._playbackRate,
  40463. panningModel: this._panningModel,
  40464. soundTrackId: this.soundTrackId
  40465. };
  40466. if (this.spatialSound) {
  40467. if (this._connectedMesh)
  40468. serializationObject.connectedMeshId = this._connectedMesh.id;
  40469. serializationObject.position = this._position.asArray();
  40470. serializationObject.refDistance = this.refDistance;
  40471. serializationObject.distanceModel = this.distanceModel;
  40472. serializationObject.isDirectional = this._isDirectional;
  40473. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  40474. serializationObject.coneInnerAngle = this._coneInnerAngle;
  40475. serializationObject.coneOuterAngle = this._coneOuterAngle;
  40476. serializationObject.coneOuterGain = this._coneOuterGain;
  40477. }
  40478. return serializationObject;
  40479. };
  40480. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  40481. var soundName = parsedSound.name;
  40482. var soundUrl;
  40483. if (parsedSound.url) {
  40484. soundUrl = rootUrl + parsedSound.url;
  40485. }
  40486. else {
  40487. soundUrl = rootUrl + soundName;
  40488. }
  40489. var options = {
  40490. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  40491. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  40492. rolloffFactor: parsedSound.rolloffFactor,
  40493. refDistance: parsedSound.refDistance,
  40494. distanceModel: parsedSound.distanceModel,
  40495. playbackRate: parsedSound.playbackRate
  40496. };
  40497. var newSound;
  40498. if (!sourceSound) {
  40499. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  40500. scene._addPendingData(newSound);
  40501. }
  40502. else {
  40503. var setBufferAndRun = function () {
  40504. if (sourceSound._isReadyToPlay) {
  40505. newSound._audioBuffer = sourceSound.getAudioBuffer();
  40506. newSound._isReadyToPlay = true;
  40507. if (newSound.autoplay) {
  40508. newSound.play();
  40509. }
  40510. }
  40511. else {
  40512. window.setTimeout(setBufferAndRun, 300);
  40513. }
  40514. };
  40515. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  40516. setBufferAndRun();
  40517. }
  40518. if (parsedSound.position) {
  40519. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  40520. newSound.setPosition(soundPosition);
  40521. }
  40522. if (parsedSound.isDirectional) {
  40523. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  40524. if (parsedSound.localDirectionToMesh) {
  40525. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  40526. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  40527. }
  40528. }
  40529. if (parsedSound.connectedMeshId) {
  40530. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  40531. if (connectedMesh) {
  40532. newSound.attachToMesh(connectedMesh);
  40533. }
  40534. }
  40535. return newSound;
  40536. };
  40537. return Sound;
  40538. }());
  40539. BABYLON.Sound = Sound;
  40540. })(BABYLON || (BABYLON = {}));
  40541. //# sourceMappingURL=babylon.sound.js.map
  40542. var BABYLON;
  40543. (function (BABYLON) {
  40544. var SoundTrack = (function () {
  40545. function SoundTrack(scene, options) {
  40546. this.id = -1;
  40547. this._isMainTrack = false;
  40548. this._isInitialized = false;
  40549. this._scene = scene;
  40550. this.soundCollection = new Array();
  40551. this._options = options;
  40552. if (!this._isMainTrack) {
  40553. this._scene.soundTracks.push(this);
  40554. this.id = this._scene.soundTracks.length - 1;
  40555. }
  40556. }
  40557. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  40558. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40559. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  40560. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  40561. if (this._options) {
  40562. if (this._options.volume) {
  40563. this._outputAudioNode.gain.value = this._options.volume;
  40564. }
  40565. if (this._options.mainTrack) {
  40566. this._isMainTrack = this._options.mainTrack;
  40567. }
  40568. }
  40569. this._isInitialized = true;
  40570. }
  40571. };
  40572. SoundTrack.prototype.dispose = function () {
  40573. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40574. if (this._connectedAnalyser) {
  40575. this._connectedAnalyser.stopDebugCanvas();
  40576. }
  40577. while (this.soundCollection.length) {
  40578. this.soundCollection[0].dispose();
  40579. }
  40580. if (this._outputAudioNode) {
  40581. this._outputAudioNode.disconnect();
  40582. }
  40583. this._outputAudioNode = null;
  40584. }
  40585. };
  40586. SoundTrack.prototype.AddSound = function (sound) {
  40587. if (!this._isInitialized) {
  40588. this._initializeSoundTrackAudioGraph();
  40589. }
  40590. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40591. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  40592. }
  40593. if (sound.soundTrackId) {
  40594. if (sound.soundTrackId === -1) {
  40595. this._scene.mainSoundTrack.RemoveSound(sound);
  40596. }
  40597. else {
  40598. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  40599. }
  40600. }
  40601. this.soundCollection.push(sound);
  40602. sound.soundTrackId = this.id;
  40603. };
  40604. SoundTrack.prototype.RemoveSound = function (sound) {
  40605. var index = this.soundCollection.indexOf(sound);
  40606. if (index !== -1) {
  40607. this.soundCollection.splice(index, 1);
  40608. }
  40609. };
  40610. SoundTrack.prototype.setVolume = function (newVolume) {
  40611. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40612. this._outputAudioNode.gain.value = newVolume;
  40613. }
  40614. };
  40615. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  40616. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40617. for (var i = 0; i < this.soundCollection.length; i++) {
  40618. this.soundCollection[i].switchPanningModelToHRTF();
  40619. }
  40620. }
  40621. };
  40622. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  40623. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40624. for (var i = 0; i < this.soundCollection.length; i++) {
  40625. this.soundCollection[i].switchPanningModelToEqualPower();
  40626. }
  40627. }
  40628. };
  40629. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  40630. if (this._connectedAnalyser) {
  40631. this._connectedAnalyser.stopDebugCanvas();
  40632. }
  40633. this._connectedAnalyser = analyser;
  40634. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40635. this._outputAudioNode.disconnect();
  40636. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  40637. }
  40638. };
  40639. return SoundTrack;
  40640. }());
  40641. BABYLON.SoundTrack = SoundTrack;
  40642. })(BABYLON || (BABYLON = {}));
  40643. //# sourceMappingURL=babylon.soundtrack.js.map
  40644. var BABYLON;
  40645. (function (BABYLON) {
  40646. var Analyser = (function () {
  40647. function Analyser(scene) {
  40648. this.SMOOTHING = 0.75;
  40649. this.FFT_SIZE = 512;
  40650. this.BARGRAPHAMPLITUDE = 256;
  40651. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  40652. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  40653. this._scene = scene;
  40654. this._audioEngine = BABYLON.Engine.audioEngine;
  40655. if (this._audioEngine.canUseWebAudio) {
  40656. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  40657. this._webAudioAnalyser.minDecibels = -140;
  40658. this._webAudioAnalyser.maxDecibels = 0;
  40659. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  40660. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  40661. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  40662. }
  40663. }
  40664. Analyser.prototype.getFrequencyBinCount = function () {
  40665. if (this._audioEngine.canUseWebAudio) {
  40666. return this._webAudioAnalyser.frequencyBinCount;
  40667. }
  40668. else {
  40669. return 0;
  40670. }
  40671. };
  40672. Analyser.prototype.getByteFrequencyData = function () {
  40673. if (this._audioEngine.canUseWebAudio) {
  40674. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40675. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40676. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  40677. }
  40678. return this._byteFreqs;
  40679. };
  40680. Analyser.prototype.getByteTimeDomainData = function () {
  40681. if (this._audioEngine.canUseWebAudio) {
  40682. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40683. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40684. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  40685. }
  40686. return this._byteTime;
  40687. };
  40688. Analyser.prototype.getFloatFrequencyData = function () {
  40689. if (this._audioEngine.canUseWebAudio) {
  40690. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40691. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40692. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  40693. }
  40694. return this._floatFreqs;
  40695. };
  40696. Analyser.prototype.drawDebugCanvas = function () {
  40697. var _this = this;
  40698. if (this._audioEngine.canUseWebAudio) {
  40699. if (!this._debugCanvas) {
  40700. this._debugCanvas = document.createElement("canvas");
  40701. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  40702. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  40703. this._debugCanvas.style.position = "absolute";
  40704. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  40705. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  40706. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  40707. document.body.appendChild(this._debugCanvas);
  40708. this._registerFunc = function () {
  40709. _this.drawDebugCanvas();
  40710. };
  40711. this._scene.registerBeforeRender(this._registerFunc);
  40712. }
  40713. if (this._registerFunc) {
  40714. var workingArray = this.getByteFrequencyData();
  40715. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  40716. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  40717. // Draw the frequency domain chart.
  40718. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  40719. var value = workingArray[i];
  40720. var percent = value / this.BARGRAPHAMPLITUDE;
  40721. var height = this.DEBUGCANVASSIZE.height * percent;
  40722. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  40723. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  40724. var hue = i / this.getFrequencyBinCount() * 360;
  40725. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  40726. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  40727. }
  40728. }
  40729. }
  40730. };
  40731. Analyser.prototype.stopDebugCanvas = function () {
  40732. if (this._debugCanvas) {
  40733. this._scene.unregisterBeforeRender(this._registerFunc);
  40734. this._registerFunc = null;
  40735. document.body.removeChild(this._debugCanvas);
  40736. this._debugCanvas = null;
  40737. this._debugCanvasContext = null;
  40738. }
  40739. };
  40740. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  40741. if (this._audioEngine.canUseWebAudio) {
  40742. inputAudioNode.connect(this._webAudioAnalyser);
  40743. this._webAudioAnalyser.connect(outputAudioNode);
  40744. }
  40745. };
  40746. Analyser.prototype.dispose = function () {
  40747. if (this._audioEngine.canUseWebAudio) {
  40748. this._webAudioAnalyser.disconnect();
  40749. }
  40750. };
  40751. return Analyser;
  40752. }());
  40753. BABYLON.Analyser = Analyser;
  40754. })(BABYLON || (BABYLON = {}));
  40755. //# sourceMappingURL=babylon.analyser.js.map
  40756. var BABYLON;
  40757. (function (BABYLON) {
  40758. var CubeTexture = (function (_super) {
  40759. __extends(CubeTexture, _super);
  40760. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  40761. if (onLoad === void 0) { onLoad = null; }
  40762. if (onError === void 0) { onError = null; }
  40763. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  40764. var _this = _super.call(this, scene) || this;
  40765. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  40766. _this.name = rootUrl;
  40767. _this.url = rootUrl;
  40768. _this._noMipmap = noMipmap;
  40769. _this.hasAlpha = false;
  40770. _this._format = format;
  40771. if (!rootUrl && !files) {
  40772. return _this;
  40773. }
  40774. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  40775. if (!files) {
  40776. if (!extensions) {
  40777. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  40778. }
  40779. files = [];
  40780. for (var index = 0; index < extensions.length; index++) {
  40781. files.push(rootUrl + extensions[index]);
  40782. }
  40783. _this._extensions = extensions;
  40784. }
  40785. _this._files = files;
  40786. if (!_this._texture) {
  40787. if (!scene.useDelayedTextureLoading) {
  40788. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  40789. }
  40790. else {
  40791. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40792. }
  40793. }
  40794. else if (onLoad) {
  40795. if (_this._texture.isReady) {
  40796. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  40797. }
  40798. else {
  40799. _this._texture.onLoadedCallbacks.push(onLoad);
  40800. }
  40801. }
  40802. _this.isCube = true;
  40803. _this._textureMatrix = BABYLON.Matrix.Identity();
  40804. return _this;
  40805. }
  40806. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  40807. return new CubeTexture("", scene, null, noMipmap, files);
  40808. };
  40809. // Methods
  40810. CubeTexture.prototype.delayLoad = function () {
  40811. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40812. return;
  40813. }
  40814. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40815. this._texture = this._getFromCache(this.url, this._noMipmap);
  40816. if (!this._texture) {
  40817. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  40818. }
  40819. };
  40820. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  40821. return this._textureMatrix;
  40822. };
  40823. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40824. var texture = BABYLON.SerializationHelper.Parse(function () {
  40825. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  40826. }, parsedTexture, scene);
  40827. // Animations
  40828. if (parsedTexture.animations) {
  40829. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  40830. var parsedAnimation = parsedTexture.animations[animationIndex];
  40831. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  40832. }
  40833. }
  40834. return texture;
  40835. };
  40836. CubeTexture.prototype.clone = function () {
  40837. var _this = this;
  40838. return BABYLON.SerializationHelper.Clone(function () {
  40839. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  40840. }, this);
  40841. };
  40842. return CubeTexture;
  40843. }(BABYLON.BaseTexture));
  40844. BABYLON.CubeTexture = CubeTexture;
  40845. })(BABYLON || (BABYLON = {}));
  40846. //# sourceMappingURL=babylon.cubeTexture.js.map
  40847. var BABYLON;
  40848. (function (BABYLON) {
  40849. var RenderTargetTexture = (function (_super) {
  40850. __extends(RenderTargetTexture, _super);
  40851. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  40852. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  40853. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40854. if (isCube === void 0) { isCube = false; }
  40855. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40856. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  40857. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  40858. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  40859. _this.isCube = isCube;
  40860. /**
  40861. * Use this list to define the list of mesh you want to render.
  40862. */
  40863. _this.renderList = new Array();
  40864. _this.renderParticles = true;
  40865. _this.renderSprites = false;
  40866. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  40867. // Events
  40868. /**
  40869. * An event triggered when the texture is unbind.
  40870. * @type {BABYLON.Observable}
  40871. */
  40872. _this.onAfterUnbindObservable = new BABYLON.Observable();
  40873. /**
  40874. * An event triggered before rendering the texture
  40875. * @type {BABYLON.Observable}
  40876. */
  40877. _this.onBeforeRenderObservable = new BABYLON.Observable();
  40878. /**
  40879. * An event triggered after rendering the texture
  40880. * @type {BABYLON.Observable}
  40881. */
  40882. _this.onAfterRenderObservable = new BABYLON.Observable();
  40883. /**
  40884. * An event triggered after the texture clear
  40885. * @type {BABYLON.Observable}
  40886. */
  40887. _this.onClearObservable = new BABYLON.Observable();
  40888. _this._currentRefreshId = -1;
  40889. _this._refreshRate = 1;
  40890. _this._samples = 1;
  40891. _this.name = name;
  40892. _this.isRenderTarget = true;
  40893. _this._size = size;
  40894. _this._generateMipMaps = generateMipMaps;
  40895. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  40896. _this._renderTargetOptions = {
  40897. generateMipMaps: generateMipMaps,
  40898. type: type,
  40899. samplingMode: samplingMode,
  40900. generateDepthBuffer: generateDepthBuffer,
  40901. generateStencilBuffer: generateStencilBuffer
  40902. };
  40903. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  40904. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40905. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40906. }
  40907. if (isCube) {
  40908. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  40909. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  40910. _this._textureMatrix = BABYLON.Matrix.Identity();
  40911. }
  40912. else {
  40913. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  40914. }
  40915. // Rendering groups
  40916. _this._renderingManager = new BABYLON.RenderingManager(scene);
  40917. return _this;
  40918. }
  40919. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  40920. get: function () {
  40921. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  40922. },
  40923. enumerable: true,
  40924. configurable: true
  40925. });
  40926. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  40927. get: function () {
  40928. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  40929. },
  40930. enumerable: true,
  40931. configurable: true
  40932. });
  40933. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  40934. get: function () {
  40935. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  40936. },
  40937. enumerable: true,
  40938. configurable: true
  40939. });
  40940. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  40941. set: function (callback) {
  40942. if (this._onAfterUnbindObserver) {
  40943. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  40944. }
  40945. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  40946. },
  40947. enumerable: true,
  40948. configurable: true
  40949. });
  40950. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  40951. set: function (callback) {
  40952. if (this._onBeforeRenderObserver) {
  40953. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  40954. }
  40955. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  40956. },
  40957. enumerable: true,
  40958. configurable: true
  40959. });
  40960. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  40961. set: function (callback) {
  40962. if (this._onAfterRenderObserver) {
  40963. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  40964. }
  40965. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  40966. },
  40967. enumerable: true,
  40968. configurable: true
  40969. });
  40970. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  40971. set: function (callback) {
  40972. if (this._onClearObserver) {
  40973. this.onClearObservable.remove(this._onClearObserver);
  40974. }
  40975. this._onClearObserver = this.onClearObservable.add(callback);
  40976. },
  40977. enumerable: true,
  40978. configurable: true
  40979. });
  40980. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  40981. get: function () {
  40982. return this._samples;
  40983. },
  40984. set: function (value) {
  40985. if (this._samples === value) {
  40986. return;
  40987. }
  40988. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  40989. },
  40990. enumerable: true,
  40991. configurable: true
  40992. });
  40993. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  40994. this._currentRefreshId = -1;
  40995. };
  40996. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  40997. get: function () {
  40998. return this._refreshRate;
  40999. },
  41000. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  41001. set: function (value) {
  41002. this._refreshRate = value;
  41003. this.resetRefreshCounter();
  41004. },
  41005. enumerable: true,
  41006. configurable: true
  41007. });
  41008. RenderTargetTexture.prototype._shouldRender = function () {
  41009. if (this._currentRefreshId === -1) {
  41010. this._currentRefreshId = 1;
  41011. return true;
  41012. }
  41013. if (this.refreshRate === this._currentRefreshId) {
  41014. this._currentRefreshId = 1;
  41015. return true;
  41016. }
  41017. this._currentRefreshId++;
  41018. return false;
  41019. };
  41020. RenderTargetTexture.prototype.isReady = function () {
  41021. if (!this.getScene().renderTargetsEnabled) {
  41022. return false;
  41023. }
  41024. return _super.prototype.isReady.call(this);
  41025. };
  41026. RenderTargetTexture.prototype.getRenderSize = function () {
  41027. return this._size;
  41028. };
  41029. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  41030. get: function () {
  41031. return true;
  41032. },
  41033. enumerable: true,
  41034. configurable: true
  41035. });
  41036. RenderTargetTexture.prototype.scale = function (ratio) {
  41037. var newSize = this._size * ratio;
  41038. this.resize(newSize);
  41039. };
  41040. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  41041. if (this.isCube) {
  41042. return this._textureMatrix;
  41043. }
  41044. return _super.prototype.getReflectionTextureMatrix.call(this);
  41045. };
  41046. RenderTargetTexture.prototype.resize = function (size) {
  41047. this.releaseInternalTexture();
  41048. if (this.isCube) {
  41049. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  41050. }
  41051. else {
  41052. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  41053. }
  41054. };
  41055. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  41056. var scene = this.getScene();
  41057. var engine = scene.getEngine();
  41058. if (this.useCameraPostProcesses !== undefined) {
  41059. useCameraPostProcess = this.useCameraPostProcesses;
  41060. }
  41061. if (this._waitingRenderList) {
  41062. this.renderList = [];
  41063. for (var index = 0; index < this._waitingRenderList.length; index++) {
  41064. var id = this._waitingRenderList[index];
  41065. this.renderList.push(scene.getMeshByID(id));
  41066. }
  41067. delete this._waitingRenderList;
  41068. }
  41069. // Is predicate defined?
  41070. if (this.renderListPredicate) {
  41071. this.renderList.splice(0); // Clear previous renderList
  41072. var sceneMeshes = this.getScene().meshes;
  41073. for (var index = 0; index < sceneMeshes.length; index++) {
  41074. var mesh = sceneMeshes[index];
  41075. if (this.renderListPredicate(mesh)) {
  41076. this.renderList.push(mesh);
  41077. }
  41078. }
  41079. }
  41080. if (this.renderList && this.renderList.length === 0) {
  41081. return;
  41082. }
  41083. // Set custom projection.
  41084. // Needs to be before binding to prevent changing the aspect ratio.
  41085. if (this.activeCamera) {
  41086. engine.setViewport(this.activeCamera.viewport);
  41087. if (this.activeCamera !== scene.activeCamera) {
  41088. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  41089. }
  41090. }
  41091. else {
  41092. engine.setViewport(scene.activeCamera.viewport);
  41093. }
  41094. // Prepare renderingManager
  41095. this._renderingManager.reset();
  41096. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  41097. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  41098. var sceneRenderId = scene.getRenderId();
  41099. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  41100. var mesh = currentRenderList[meshIndex];
  41101. if (mesh) {
  41102. if (!mesh.isReady()) {
  41103. // Reset _currentRefreshId
  41104. this.resetRefreshCounter();
  41105. continue;
  41106. }
  41107. mesh._preActivateForIntermediateRendering(sceneRenderId);
  41108. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  41109. mesh._activate(sceneRenderId);
  41110. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  41111. var subMesh = mesh.subMeshes[subIndex];
  41112. scene._activeIndices.addCount(subMesh.indexCount, false);
  41113. this._renderingManager.dispatch(subMesh);
  41114. }
  41115. }
  41116. }
  41117. }
  41118. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  41119. var particleSystem = scene.particleSystems[particleIndex];
  41120. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  41121. continue;
  41122. }
  41123. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  41124. this._renderingManager.dispatchParticles(particleSystem);
  41125. }
  41126. }
  41127. if (this.isCube) {
  41128. for (var face = 0; face < 6; face++) {
  41129. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  41130. scene.incrementRenderId();
  41131. scene.resetCachedMaterial();
  41132. }
  41133. }
  41134. else {
  41135. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  41136. }
  41137. this.onAfterUnbindObservable.notifyObservers(this);
  41138. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  41139. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  41140. }
  41141. engine.setViewport(scene.activeCamera.viewport);
  41142. scene.resetCachedMaterial();
  41143. };
  41144. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  41145. var _this = this;
  41146. var scene = this.getScene();
  41147. var engine = scene.getEngine();
  41148. // Bind
  41149. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  41150. if (this.isCube) {
  41151. engine.bindFramebuffer(this._texture, faceIndex);
  41152. }
  41153. else {
  41154. engine.bindFramebuffer(this._texture);
  41155. }
  41156. }
  41157. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  41158. // Clear
  41159. if (this.onClearObservable.hasObservers()) {
  41160. this.onClearObservable.notifyObservers(engine);
  41161. }
  41162. else {
  41163. engine.clear(scene.clearColor, true, true, true);
  41164. }
  41165. if (!this._doNotChangeAspectRatio) {
  41166. scene.updateTransformMatrix(true);
  41167. }
  41168. // Render
  41169. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  41170. if (useCameraPostProcess) {
  41171. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  41172. }
  41173. if (!this._doNotChangeAspectRatio) {
  41174. scene.updateTransformMatrix(true);
  41175. }
  41176. // Dump ?
  41177. if (dumpForDebug) {
  41178. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  41179. }
  41180. // Unbind
  41181. if (!this.isCube || faceIndex === 5) {
  41182. if (this.isCube) {
  41183. if (faceIndex === 5) {
  41184. engine.generateMipMapsForCubemap(this._texture);
  41185. }
  41186. }
  41187. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  41188. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  41189. });
  41190. }
  41191. else {
  41192. this.onAfterRenderObservable.notifyObservers(faceIndex);
  41193. }
  41194. };
  41195. /**
  41196. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  41197. * This allowed control for front to back rendering or reversly depending of the special needs.
  41198. *
  41199. * @param renderingGroupId The rendering group id corresponding to its index
  41200. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  41201. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  41202. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  41203. */
  41204. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  41205. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  41206. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  41207. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  41208. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  41209. };
  41210. /**
  41211. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  41212. *
  41213. * @param renderingGroupId The rendering group id corresponding to its index
  41214. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  41215. */
  41216. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  41217. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  41218. };
  41219. RenderTargetTexture.prototype.clone = function () {
  41220. var textureSize = this.getSize();
  41221. 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);
  41222. // Base texture
  41223. newTexture.hasAlpha = this.hasAlpha;
  41224. newTexture.level = this.level;
  41225. // RenderTarget Texture
  41226. newTexture.coordinatesMode = this.coordinatesMode;
  41227. newTexture.renderList = this.renderList.slice(0);
  41228. return newTexture;
  41229. };
  41230. RenderTargetTexture.prototype.serialize = function () {
  41231. if (!this.name) {
  41232. return null;
  41233. }
  41234. var serializationObject = _super.prototype.serialize.call(this);
  41235. serializationObject.renderTargetSize = this.getRenderSize();
  41236. serializationObject.renderList = [];
  41237. for (var index = 0; index < this.renderList.length; index++) {
  41238. serializationObject.renderList.push(this.renderList[index].id);
  41239. }
  41240. return serializationObject;
  41241. };
  41242. return RenderTargetTexture;
  41243. }(BABYLON.Texture));
  41244. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  41245. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  41246. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  41247. BABYLON.RenderTargetTexture = RenderTargetTexture;
  41248. })(BABYLON || (BABYLON = {}));
  41249. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  41250. /// <reference path="babylon.renderTargetTexture.ts" />
  41251. var BABYLON;
  41252. (function (BABYLON) {
  41253. var MirrorTexture = (function (_super) {
  41254. __extends(MirrorTexture, _super);
  41255. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  41256. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41257. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  41258. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  41259. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  41260. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  41261. _this._transformMatrix = BABYLON.Matrix.Zero();
  41262. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  41263. _this.onBeforeRenderObservable.add(function () {
  41264. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  41265. _this._savedViewMatrix = scene.getViewMatrix();
  41266. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  41267. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  41268. scene.clipPlane = _this.mirrorPlane;
  41269. scene.getEngine().cullBackFaces = false;
  41270. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  41271. });
  41272. _this.onAfterRenderObservable.add(function () {
  41273. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  41274. scene.getEngine().cullBackFaces = true;
  41275. scene._mirroredCameraPosition = null;
  41276. delete scene.clipPlane;
  41277. });
  41278. return _this;
  41279. }
  41280. MirrorTexture.prototype.clone = function () {
  41281. var textureSize = this.getSize();
  41282. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  41283. // Base texture
  41284. newTexture.hasAlpha = this.hasAlpha;
  41285. newTexture.level = this.level;
  41286. // Mirror Texture
  41287. newTexture.mirrorPlane = this.mirrorPlane.clone();
  41288. newTexture.renderList = this.renderList.slice(0);
  41289. return newTexture;
  41290. };
  41291. MirrorTexture.prototype.serialize = function () {
  41292. if (!this.name) {
  41293. return null;
  41294. }
  41295. var serializationObject = _super.prototype.serialize.call(this);
  41296. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  41297. return serializationObject;
  41298. };
  41299. return MirrorTexture;
  41300. }(BABYLON.RenderTargetTexture));
  41301. BABYLON.MirrorTexture = MirrorTexture;
  41302. })(BABYLON || (BABYLON = {}));
  41303. //# sourceMappingURL=babylon.mirrorTexture.js.map
  41304. /// <reference path="babylon.renderTargetTexture.ts" />
  41305. var BABYLON;
  41306. (function (BABYLON) {
  41307. /**
  41308. * Creates a refraction texture used by refraction channel of the standard material.
  41309. * @param name the texture name
  41310. * @param size size of the underlying texture
  41311. * @param scene root scene
  41312. */
  41313. var RefractionTexture = (function (_super) {
  41314. __extends(RefractionTexture, _super);
  41315. function RefractionTexture(name, size, scene, generateMipMaps) {
  41316. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  41317. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  41318. _this.depth = 2.0;
  41319. _this.onBeforeRenderObservable.add(function () {
  41320. scene.clipPlane = _this.refractionPlane;
  41321. });
  41322. _this.onAfterRenderObservable.add(function () {
  41323. delete scene.clipPlane;
  41324. });
  41325. return _this;
  41326. }
  41327. RefractionTexture.prototype.clone = function () {
  41328. var textureSize = this.getSize();
  41329. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  41330. // Base texture
  41331. newTexture.hasAlpha = this.hasAlpha;
  41332. newTexture.level = this.level;
  41333. // Refraction Texture
  41334. newTexture.refractionPlane = this.refractionPlane.clone();
  41335. newTexture.renderList = this.renderList.slice(0);
  41336. newTexture.depth = this.depth;
  41337. return newTexture;
  41338. };
  41339. RefractionTexture.prototype.serialize = function () {
  41340. if (!this.name) {
  41341. return null;
  41342. }
  41343. var serializationObject = _super.prototype.serialize.call(this);
  41344. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  41345. serializationObject.depth = this.depth;
  41346. return serializationObject;
  41347. };
  41348. return RefractionTexture;
  41349. }(BABYLON.RenderTargetTexture));
  41350. BABYLON.RefractionTexture = RefractionTexture;
  41351. })(BABYLON || (BABYLON = {}));
  41352. //# sourceMappingURL=babylon.refractionTexture.js.map
  41353. /// <reference path="babylon.texture.ts" />
  41354. var BABYLON;
  41355. (function (BABYLON) {
  41356. var DynamicTexture = (function (_super) {
  41357. __extends(DynamicTexture, _super);
  41358. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  41359. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41360. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  41361. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  41362. _this.name = name;
  41363. var engine = _this.getScene().getEngine();
  41364. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41365. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41366. _this._generateMipMaps = generateMipMaps;
  41367. if (options.getContext) {
  41368. _this._canvas = options;
  41369. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  41370. }
  41371. else {
  41372. _this._canvas = document.createElement("canvas");
  41373. if (options.width) {
  41374. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  41375. }
  41376. else {
  41377. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  41378. }
  41379. }
  41380. var textureSize = _this.getSize();
  41381. _this._canvas.width = textureSize.width;
  41382. _this._canvas.height = textureSize.height;
  41383. _this._context = _this._canvas.getContext("2d");
  41384. return _this;
  41385. }
  41386. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  41387. get: function () {
  41388. return true;
  41389. },
  41390. enumerable: true,
  41391. configurable: true
  41392. });
  41393. DynamicTexture.prototype._recreate = function (textureSize) {
  41394. this._canvas.width = textureSize.width;
  41395. this._canvas.height = textureSize.height;
  41396. this.releaseInternalTexture();
  41397. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  41398. };
  41399. DynamicTexture.prototype.scale = function (ratio) {
  41400. var textureSize = this.getSize();
  41401. textureSize.width *= ratio;
  41402. textureSize.height *= ratio;
  41403. this._recreate(textureSize);
  41404. };
  41405. DynamicTexture.prototype.scaleTo = function (width, height) {
  41406. var textureSize = this.getSize();
  41407. textureSize.width = width;
  41408. textureSize.height = height;
  41409. this._recreate(textureSize);
  41410. };
  41411. DynamicTexture.prototype.getContext = function () {
  41412. return this._context;
  41413. };
  41414. DynamicTexture.prototype.clear = function () {
  41415. var size = this.getSize();
  41416. this._context.fillRect(0, 0, size.width, size.height);
  41417. };
  41418. DynamicTexture.prototype.update = function (invertY) {
  41419. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  41420. };
  41421. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  41422. if (update === void 0) { update = true; }
  41423. var size = this.getSize();
  41424. if (clearColor) {
  41425. this._context.fillStyle = clearColor;
  41426. this._context.fillRect(0, 0, size.width, size.height);
  41427. }
  41428. this._context.font = font;
  41429. if (x === null || x === undefined) {
  41430. var textSize = this._context.measureText(text);
  41431. x = (size.width - textSize.width) / 2;
  41432. }
  41433. if (y === null || y === undefined) {
  41434. var fontSize = parseInt((font.replace(/\D/g, '')));
  41435. ;
  41436. y = (size.height / 2) + (fontSize / 3.65);
  41437. }
  41438. this._context.fillStyle = color;
  41439. this._context.fillText(text, x, y);
  41440. if (update) {
  41441. this.update(invertY);
  41442. }
  41443. };
  41444. DynamicTexture.prototype.clone = function () {
  41445. var textureSize = this.getSize();
  41446. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  41447. // Base texture
  41448. newTexture.hasAlpha = this.hasAlpha;
  41449. newTexture.level = this.level;
  41450. // Dynamic Texture
  41451. newTexture.wrapU = this.wrapU;
  41452. newTexture.wrapV = this.wrapV;
  41453. return newTexture;
  41454. };
  41455. return DynamicTexture;
  41456. }(BABYLON.Texture));
  41457. BABYLON.DynamicTexture = DynamicTexture;
  41458. })(BABYLON || (BABYLON = {}));
  41459. //# sourceMappingURL=babylon.dynamicTexture.js.map
  41460. var BABYLON;
  41461. (function (BABYLON) {
  41462. var VideoTexture = (function (_super) {
  41463. __extends(VideoTexture, _super);
  41464. /**
  41465. * Creates a video texture.
  41466. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  41467. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  41468. * @param {BABYLON.Scene} scene is obviously the current scene.
  41469. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  41470. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  41471. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  41472. */
  41473. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  41474. if (generateMipMaps === void 0) { generateMipMaps = false; }
  41475. if (invertY === void 0) { invertY = false; }
  41476. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41477. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  41478. _this._autoLaunch = true;
  41479. var urls;
  41480. _this.name = name;
  41481. if (urlsOrVideo instanceof HTMLVideoElement) {
  41482. _this.video = urlsOrVideo;
  41483. }
  41484. else {
  41485. urls = urlsOrVideo;
  41486. _this.video = document.createElement("video");
  41487. _this.video.autoplay = false;
  41488. _this.video.loop = true;
  41489. }
  41490. _this._generateMipMaps = generateMipMaps;
  41491. _this._samplingMode = samplingMode;
  41492. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  41493. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  41494. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  41495. }
  41496. else {
  41497. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41498. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41499. _this._generateMipMaps = false;
  41500. }
  41501. if (urls) {
  41502. _this.video.addEventListener("canplay", function () {
  41503. _this._createTexture();
  41504. });
  41505. urls.forEach(function (url) {
  41506. var source = document.createElement("source");
  41507. source.src = url;
  41508. _this.video.appendChild(source);
  41509. });
  41510. }
  41511. else {
  41512. _this._createTexture();
  41513. }
  41514. _this._lastUpdate = BABYLON.Tools.Now;
  41515. return _this;
  41516. }
  41517. VideoTexture.prototype._createTexture = function () {
  41518. var _this = this;
  41519. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  41520. if (this._autoLaunch) {
  41521. this._autoLaunch = false;
  41522. this.video.play();
  41523. }
  41524. this.video.addEventListener("playing", function () {
  41525. _this._texture.isReady = true;
  41526. });
  41527. };
  41528. VideoTexture.prototype.update = function () {
  41529. var now = BABYLON.Tools.Now;
  41530. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  41531. return false;
  41532. }
  41533. this._lastUpdate = now;
  41534. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  41535. return true;
  41536. };
  41537. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  41538. var video = document.createElement("video");
  41539. var constraintsDeviceId;
  41540. if (constraints && constraints.deviceId) {
  41541. constraintsDeviceId = {
  41542. exact: constraints.deviceId
  41543. };
  41544. }
  41545. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  41546. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  41547. if (navigator.getUserMedia) {
  41548. navigator.getUserMedia({
  41549. video: {
  41550. deviceId: constraintsDeviceId,
  41551. width: {
  41552. min: (constraints && constraints.minWidth) || 256,
  41553. max: (constraints && constraints.maxWidth) || 640
  41554. },
  41555. height: {
  41556. min: (constraints && constraints.minHeight) || 256,
  41557. max: (constraints && constraints.maxHeight) || 480
  41558. }
  41559. }
  41560. }, function (stream) {
  41561. if (video.mozSrcObject !== undefined) {
  41562. video.mozSrcObject = stream;
  41563. }
  41564. else {
  41565. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  41566. }
  41567. video.play();
  41568. if (onReady) {
  41569. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  41570. }
  41571. }, function (e) {
  41572. BABYLON.Tools.Error(e.name);
  41573. });
  41574. }
  41575. };
  41576. return VideoTexture;
  41577. }(BABYLON.Texture));
  41578. BABYLON.VideoTexture = VideoTexture;
  41579. })(BABYLON || (BABYLON = {}));
  41580. //# sourceMappingURL=babylon.videoTexture.js.map
  41581. var BABYLON;
  41582. (function (BABYLON) {
  41583. var RawTexture = (function (_super) {
  41584. __extends(RawTexture, _super);
  41585. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  41586. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41587. if (invertY === void 0) { invertY = false; }
  41588. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41589. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  41590. _this.format = format;
  41591. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  41592. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41593. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41594. return _this;
  41595. }
  41596. RawTexture.prototype.update = function (data) {
  41597. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  41598. };
  41599. // Statics
  41600. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41601. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41602. if (invertY === void 0) { invertY = false; }
  41603. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41604. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  41605. };
  41606. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41607. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41608. if (invertY === void 0) { invertY = false; }
  41609. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41610. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  41611. };
  41612. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41613. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41614. if (invertY === void 0) { invertY = false; }
  41615. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41616. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  41617. };
  41618. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41619. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41620. if (invertY === void 0) { invertY = false; }
  41621. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41622. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  41623. };
  41624. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41625. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41626. if (invertY === void 0) { invertY = false; }
  41627. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41628. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  41629. };
  41630. return RawTexture;
  41631. }(BABYLON.Texture));
  41632. BABYLON.RawTexture = RawTexture;
  41633. })(BABYLON || (BABYLON = {}));
  41634. //# sourceMappingURL=babylon.rawTexture.js.map
  41635. var BABYLON;
  41636. (function (BABYLON) {
  41637. var PostProcess = (function () {
  41638. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  41639. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  41640. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41641. this.name = name;
  41642. this.width = -1;
  41643. this.height = -1;
  41644. /*
  41645. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  41646. Can only be used on a single postprocess or on the last one of a chain.
  41647. */
  41648. this.enablePixelPerfectMode = false;
  41649. this.samples = 1;
  41650. this._reusable = false;
  41651. this._textures = new BABYLON.SmartArray(2);
  41652. this._currentRenderTextureInd = 0;
  41653. this._scaleRatio = new BABYLON.Vector2(1, 1);
  41654. // Events
  41655. /**
  41656. * An event triggered when the postprocess is activated.
  41657. * @type {BABYLON.Observable}
  41658. */
  41659. this.onActivateObservable = new BABYLON.Observable();
  41660. /**
  41661. * An event triggered when the postprocess changes its size.
  41662. * @type {BABYLON.Observable}
  41663. */
  41664. this.onSizeChangedObservable = new BABYLON.Observable();
  41665. /**
  41666. * An event triggered when the postprocess applies its effect.
  41667. * @type {BABYLON.Observable}
  41668. */
  41669. this.onApplyObservable = new BABYLON.Observable();
  41670. /**
  41671. * An event triggered before rendering the postprocess
  41672. * @type {BABYLON.Observable}
  41673. */
  41674. this.onBeforeRenderObservable = new BABYLON.Observable();
  41675. /**
  41676. * An event triggered after rendering the postprocess
  41677. * @type {BABYLON.Observable}
  41678. */
  41679. this.onAfterRenderObservable = new BABYLON.Observable();
  41680. if (camera != null) {
  41681. this._camera = camera;
  41682. this._scene = camera.getScene();
  41683. camera.attachPostProcess(this);
  41684. this._engine = this._scene.getEngine();
  41685. }
  41686. else {
  41687. this._engine = engine;
  41688. }
  41689. this._options = options;
  41690. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  41691. this._reusable = reusable || false;
  41692. this._textureType = textureType;
  41693. this._samplers = samplers || [];
  41694. this._samplers.push("textureSampler");
  41695. this._fragmentUrl = fragmentUrl;
  41696. this._parameters = parameters || [];
  41697. this._parameters.push("scale");
  41698. this.updateEffect(defines);
  41699. }
  41700. Object.defineProperty(PostProcess.prototype, "onActivate", {
  41701. set: function (callback) {
  41702. if (this._onActivateObserver) {
  41703. this.onActivateObservable.remove(this._onActivateObserver);
  41704. }
  41705. this._onActivateObserver = this.onActivateObservable.add(callback);
  41706. },
  41707. enumerable: true,
  41708. configurable: true
  41709. });
  41710. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  41711. set: function (callback) {
  41712. if (this._onSizeChangedObserver) {
  41713. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  41714. }
  41715. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  41716. },
  41717. enumerable: true,
  41718. configurable: true
  41719. });
  41720. Object.defineProperty(PostProcess.prototype, "onApply", {
  41721. set: function (callback) {
  41722. if (this._onApplyObserver) {
  41723. this.onApplyObservable.remove(this._onApplyObserver);
  41724. }
  41725. this._onApplyObserver = this.onApplyObservable.add(callback);
  41726. },
  41727. enumerable: true,
  41728. configurable: true
  41729. });
  41730. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  41731. set: function (callback) {
  41732. if (this._onBeforeRenderObserver) {
  41733. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  41734. }
  41735. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  41736. },
  41737. enumerable: true,
  41738. configurable: true
  41739. });
  41740. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  41741. set: function (callback) {
  41742. if (this._onAfterRenderObserver) {
  41743. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  41744. }
  41745. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  41746. },
  41747. enumerable: true,
  41748. configurable: true
  41749. });
  41750. PostProcess.prototype.updateEffect = function (defines) {
  41751. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  41752. };
  41753. PostProcess.prototype.isReusable = function () {
  41754. return this._reusable;
  41755. };
  41756. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  41757. PostProcess.prototype.markTextureDirty = function () {
  41758. this.width = -1;
  41759. };
  41760. PostProcess.prototype.activate = function (camera, sourceTexture) {
  41761. var _this = this;
  41762. camera = camera || this._camera;
  41763. var scene = camera.getScene();
  41764. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  41765. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  41766. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  41767. var desiredWidth = this._options.width || requiredWidth;
  41768. var desiredHeight = this._options.height || requiredHeight;
  41769. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  41770. if (!this._options.width) {
  41771. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  41772. }
  41773. if (!this._options.height) {
  41774. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  41775. }
  41776. }
  41777. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  41778. if (this._textures.length > 0) {
  41779. for (var i = 0; i < this._textures.length; i++) {
  41780. this._engine._releaseTexture(this._textures.data[i]);
  41781. }
  41782. this._textures.reset();
  41783. }
  41784. this.width = desiredWidth;
  41785. this.height = desiredHeight;
  41786. var textureSize = { width: this.width, height: this.height };
  41787. var textureOptions = {
  41788. generateMipMaps: false,
  41789. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  41790. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  41791. samplingMode: this.renderTargetSamplingMode,
  41792. type: this._textureType
  41793. };
  41794. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  41795. if (this._reusable) {
  41796. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  41797. }
  41798. this.onSizeChangedObservable.notifyObservers(this);
  41799. }
  41800. this._textures.forEach(function (texture) {
  41801. if (texture.samples !== _this.samples) {
  41802. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  41803. }
  41804. });
  41805. if (this.enablePixelPerfectMode) {
  41806. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  41807. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  41808. }
  41809. else {
  41810. this._scaleRatio.copyFromFloats(1, 1);
  41811. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  41812. }
  41813. this.onActivateObservable.notifyObservers(camera);
  41814. // Clear
  41815. if (this.clearColor) {
  41816. this._engine.clear(this.clearColor, true, true, true);
  41817. }
  41818. else {
  41819. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  41820. }
  41821. if (this._reusable) {
  41822. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  41823. }
  41824. };
  41825. Object.defineProperty(PostProcess.prototype, "isSupported", {
  41826. get: function () {
  41827. return this._effect.isSupported;
  41828. },
  41829. enumerable: true,
  41830. configurable: true
  41831. });
  41832. PostProcess.prototype.apply = function () {
  41833. // Check
  41834. if (!this._effect.isReady())
  41835. return null;
  41836. // States
  41837. this._engine.enableEffect(this._effect);
  41838. this._engine.setState(false);
  41839. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41840. this._engine.setDepthBuffer(false);
  41841. this._engine.setDepthWrite(false);
  41842. // Texture
  41843. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  41844. // Parameters
  41845. this._effect.setVector2("scale", this._scaleRatio);
  41846. this.onApplyObservable.notifyObservers(this._effect);
  41847. return this._effect;
  41848. };
  41849. PostProcess.prototype.dispose = function (camera) {
  41850. camera = camera || this._camera;
  41851. if (this._textures.length > 0) {
  41852. for (var i = 0; i < this._textures.length; i++) {
  41853. this._engine._releaseTexture(this._textures.data[i]);
  41854. }
  41855. }
  41856. this._textures.dispose();
  41857. if (!camera) {
  41858. return;
  41859. }
  41860. camera.detachPostProcess(this);
  41861. var index = camera._postProcesses.indexOf(this);
  41862. if (index === 0 && camera._postProcesses.length > 0) {
  41863. this._camera._postProcesses[0].markTextureDirty();
  41864. }
  41865. this.onActivateObservable.clear();
  41866. this.onAfterRenderObservable.clear();
  41867. this.onApplyObservable.clear();
  41868. this.onBeforeRenderObservable.clear();
  41869. this.onSizeChangedObservable.clear();
  41870. };
  41871. return PostProcess;
  41872. }());
  41873. BABYLON.PostProcess = PostProcess;
  41874. })(BABYLON || (BABYLON = {}));
  41875. //# sourceMappingURL=babylon.postProcess.js.map
  41876. var BABYLON;
  41877. (function (BABYLON) {
  41878. var PassPostProcess = (function (_super) {
  41879. __extends(PassPostProcess, _super);
  41880. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41881. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41882. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  41883. }
  41884. return PassPostProcess;
  41885. }(BABYLON.PostProcess));
  41886. BABYLON.PassPostProcess = PassPostProcess;
  41887. })(BABYLON || (BABYLON = {}));
  41888. //# sourceMappingURL=babylon.passPostProcess.js.map
  41889. var BABYLON;
  41890. (function (BABYLON) {
  41891. var ShadowGenerator = (function () {
  41892. /**
  41893. * Creates a ShadowGenerator object.
  41894. * A ShadowGenerator is the required tool to use the shadows.
  41895. * Each light casting shadows needs to use its own ShadowGenerator.
  41896. * Required parameters :
  41897. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  41898. * - `light` : the light object generating the shadows.
  41899. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  41900. */
  41901. function ShadowGenerator(mapSize, light) {
  41902. var _this = this;
  41903. // Members
  41904. this._filter = ShadowGenerator.FILTER_NONE;
  41905. this.blurScale = 2;
  41906. this._blurBoxOffset = 0;
  41907. this._bias = 0.00005;
  41908. this._lightDirection = BABYLON.Vector3.Zero();
  41909. this.forceBackFacesOnly = false;
  41910. this._darkness = 0;
  41911. this._transparencyShadow = false;
  41912. this._viewMatrix = BABYLON.Matrix.Zero();
  41913. this._projectionMatrix = BABYLON.Matrix.Zero();
  41914. this._transformMatrix = BABYLON.Matrix.Zero();
  41915. this._worldViewProjection = BABYLON.Matrix.Zero();
  41916. this._currentFaceIndex = 0;
  41917. this._currentFaceIndexCache = 0;
  41918. this._useFullFloat = true;
  41919. this._light = light;
  41920. this._scene = light.getScene();
  41921. this._mapSize = mapSize;
  41922. light._shadowGenerator = this;
  41923. light._markMeshesAsLightDirty();
  41924. // Texture type fallback from float to int if not supported.
  41925. var textureType;
  41926. var caps = this._scene.getEngine().getCaps();
  41927. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  41928. this._useFullFloat = true;
  41929. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  41930. }
  41931. else {
  41932. this._useFullFloat = false;
  41933. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  41934. }
  41935. // Render target
  41936. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  41937. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41938. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41939. this._shadowMap.anisotropicFilteringLevel = 1;
  41940. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41941. this._shadowMap.renderParticles = false;
  41942. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  41943. _this._currentFaceIndex = faceIndex;
  41944. });
  41945. this._shadowMap.onAfterUnbindObservable.add(function () {
  41946. if (!_this.useBlurExponentialShadowMap) {
  41947. return;
  41948. }
  41949. if (!_this._shadowMap2) {
  41950. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  41951. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41952. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41953. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41954. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine(), false, textureType);
  41955. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  41956. effect.setTexture("textureSampler", _this._shadowMap);
  41957. });
  41958. _this.blurBoxOffset = 1;
  41959. }
  41960. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  41961. });
  41962. // Custom render function
  41963. var renderSubMesh = function (subMesh) {
  41964. var mesh = subMesh.getRenderingMesh();
  41965. var scene = _this._scene;
  41966. var engine = scene.getEngine();
  41967. // Culling
  41968. engine.setState(subMesh.getMaterial().backFaceCulling);
  41969. // Managing instances
  41970. var batch = mesh._getInstancesRenderList(subMesh._id);
  41971. if (batch.mustReturn) {
  41972. return;
  41973. }
  41974. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  41975. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  41976. engine.enableEffect(_this._effect);
  41977. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  41978. var material = subMesh.getMaterial();
  41979. _this._effect.setFloat2("biasAndScale", _this.bias, _this.depthScale);
  41980. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  41981. _this._effect.setVector3("lightPosition", _this.getLight().position);
  41982. if (_this.getLight().needCube()) {
  41983. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  41984. }
  41985. // Alpha test
  41986. if (material && material.needAlphaTesting()) {
  41987. var alphaTexture = material.getAlphaTestTexture();
  41988. _this._effect.setTexture("diffuseSampler", alphaTexture);
  41989. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  41990. }
  41991. // Bones
  41992. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  41993. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  41994. }
  41995. if (_this.forceBackFacesOnly) {
  41996. engine.setState(true, 0, false, true);
  41997. }
  41998. // Draw
  41999. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  42000. if (_this.forceBackFacesOnly) {
  42001. engine.setState(true, 0, false, false);
  42002. }
  42003. }
  42004. else {
  42005. // Need to reset refresh rate of the shadowMap
  42006. _this._shadowMap.resetRefreshCounter();
  42007. }
  42008. };
  42009. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  42010. var index;
  42011. for (index = 0; index < opaqueSubMeshes.length; index++) {
  42012. renderSubMesh(opaqueSubMeshes.data[index]);
  42013. }
  42014. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  42015. renderSubMesh(alphaTestSubMeshes.data[index]);
  42016. }
  42017. if (_this._transparencyShadow) {
  42018. for (index = 0; index < transparentSubMeshes.length; index++) {
  42019. renderSubMesh(transparentSubMeshes.data[index]);
  42020. }
  42021. }
  42022. };
  42023. this._shadowMap.onClearObservable.add(function (engine) {
  42024. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  42025. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  42026. }
  42027. else {
  42028. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  42029. }
  42030. });
  42031. }
  42032. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  42033. // Static
  42034. get: function () {
  42035. return ShadowGenerator._FILTER_NONE;
  42036. },
  42037. enumerable: true,
  42038. configurable: true
  42039. });
  42040. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  42041. get: function () {
  42042. return ShadowGenerator._FILTER_POISSONSAMPLING;
  42043. },
  42044. enumerable: true,
  42045. configurable: true
  42046. });
  42047. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  42048. get: function () {
  42049. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  42050. },
  42051. enumerable: true,
  42052. configurable: true
  42053. });
  42054. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  42055. get: function () {
  42056. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  42057. },
  42058. enumerable: true,
  42059. configurable: true
  42060. });
  42061. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  42062. get: function () {
  42063. return this._bias;
  42064. },
  42065. set: function (bias) {
  42066. this._bias = bias;
  42067. },
  42068. enumerable: true,
  42069. configurable: true
  42070. });
  42071. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  42072. get: function () {
  42073. return this._blurBoxOffset;
  42074. },
  42075. set: function (value) {
  42076. var _this = this;
  42077. if (this._blurBoxOffset === value) {
  42078. return;
  42079. }
  42080. this._blurBoxOffset = value;
  42081. if (this._boxBlurPostprocess) {
  42082. this._boxBlurPostprocess.dispose();
  42083. }
  42084. var textureType;
  42085. var caps = this._scene.getEngine().getCaps();
  42086. if (this._useFullFloat) {
  42087. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  42088. }
  42089. else {
  42090. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  42091. }
  42092. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value, textureType);
  42093. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  42094. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  42095. });
  42096. },
  42097. enumerable: true,
  42098. configurable: true
  42099. });
  42100. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  42101. get: function () {
  42102. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  42103. },
  42104. set: function (value) {
  42105. this._depthScale = value;
  42106. },
  42107. enumerable: true,
  42108. configurable: true
  42109. });
  42110. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  42111. get: function () {
  42112. return this._filter;
  42113. },
  42114. set: function (value) {
  42115. if (this._filter === value) {
  42116. return;
  42117. }
  42118. this._filter = value;
  42119. if (this.usePoissonSampling || this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  42120. this._shadowMap.anisotropicFilteringLevel = 16;
  42121. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  42122. }
  42123. else {
  42124. this._shadowMap.anisotropicFilteringLevel = 1;
  42125. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  42126. }
  42127. this._light._markMeshesAsLightDirty();
  42128. },
  42129. enumerable: true,
  42130. configurable: true
  42131. });
  42132. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  42133. get: function () {
  42134. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  42135. return this.useExponentialShadowMap;
  42136. },
  42137. set: function (value) {
  42138. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  42139. this.useExponentialShadowMap = value;
  42140. },
  42141. enumerable: true,
  42142. configurable: true
  42143. });
  42144. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  42145. get: function () {
  42146. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  42147. },
  42148. set: function (value) {
  42149. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  42150. },
  42151. enumerable: true,
  42152. configurable: true
  42153. });
  42154. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  42155. get: function () {
  42156. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  42157. },
  42158. set: function (value) {
  42159. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  42160. },
  42161. enumerable: true,
  42162. configurable: true
  42163. });
  42164. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  42165. get: function () {
  42166. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  42167. return this.useBlurExponentialShadowMap;
  42168. },
  42169. set: function (value) {
  42170. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  42171. this.useBlurExponentialShadowMap = value;
  42172. },
  42173. enumerable: true,
  42174. configurable: true
  42175. });
  42176. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  42177. get: function () {
  42178. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  42179. },
  42180. set: function (value) {
  42181. if (this._light.needCube() && value) {
  42182. this.useExponentialShadowMap = true; // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  42183. }
  42184. else {
  42185. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  42186. }
  42187. },
  42188. enumerable: true,
  42189. configurable: true
  42190. });
  42191. /**
  42192. * Boolean : true when the ShadowGenerator is finally computed.
  42193. */
  42194. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  42195. var defines = [];
  42196. if (this._useFullFloat) {
  42197. defines.push("#define FULLFLOAT");
  42198. }
  42199. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  42200. defines.push("#define ESM");
  42201. }
  42202. if (this.getLight().needCube()) {
  42203. defines.push("#define CUBEMAP");
  42204. }
  42205. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42206. var mesh = subMesh.getMesh();
  42207. var material = subMesh.getMaterial();
  42208. // Alpha test
  42209. if (material && material.needAlphaTesting()) {
  42210. defines.push("#define ALPHATEST");
  42211. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42212. attribs.push(BABYLON.VertexBuffer.UVKind);
  42213. defines.push("#define UV1");
  42214. }
  42215. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  42216. var alphaTexture = material.getAlphaTestTexture();
  42217. if (alphaTexture.coordinatesIndex === 1) {
  42218. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42219. defines.push("#define UV2");
  42220. }
  42221. }
  42222. }
  42223. // Bones
  42224. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42225. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42226. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42227. if (mesh.numBoneInfluencers > 4) {
  42228. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42229. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42230. }
  42231. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  42232. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  42233. }
  42234. else {
  42235. defines.push("#define NUM_BONE_INFLUENCERS 0");
  42236. }
  42237. // Instances
  42238. if (useInstances) {
  42239. defines.push("#define INSTANCES");
  42240. attribs.push("world0");
  42241. attribs.push("world1");
  42242. attribs.push("world2");
  42243. attribs.push("world3");
  42244. }
  42245. // Get correct effect
  42246. var join = defines.join("\n");
  42247. if (this._cachedDefines !== join) {
  42248. this._cachedDefines = join;
  42249. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  42250. }
  42251. return this._effect.isReady();
  42252. };
  42253. /**
  42254. * Returns a RenderTargetTexture object : the shadow map texture.
  42255. */
  42256. ShadowGenerator.prototype.getShadowMap = function () {
  42257. return this._shadowMap;
  42258. };
  42259. /**
  42260. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  42261. */
  42262. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  42263. if (this._shadowMap2) {
  42264. return this._shadowMap2;
  42265. }
  42266. return this._shadowMap;
  42267. };
  42268. /**
  42269. * Returns the associated light object.
  42270. */
  42271. ShadowGenerator.prototype.getLight = function () {
  42272. return this._light;
  42273. };
  42274. // Methods
  42275. /**
  42276. * Returns a Matrix object : the updated transformation matrix.
  42277. */
  42278. ShadowGenerator.prototype.getTransformMatrix = function () {
  42279. var scene = this._scene;
  42280. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  42281. return this._transformMatrix;
  42282. }
  42283. this._currentRenderID = scene.getRenderId();
  42284. this._currentFaceIndexCache = this._currentFaceIndex;
  42285. var lightPosition = this._light.position;
  42286. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  42287. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  42288. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  42289. }
  42290. if (this._light.computeTransformedPosition()) {
  42291. lightPosition = this._light.transformedPosition;
  42292. }
  42293. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  42294. this._cachedPosition = lightPosition.clone();
  42295. this._cachedDirection = this._lightDirection.clone();
  42296. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  42297. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  42298. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  42299. }
  42300. return this._transformMatrix;
  42301. };
  42302. /**
  42303. * Returns the darkness value (float).
  42304. */
  42305. ShadowGenerator.prototype.getDarkness = function () {
  42306. return this._darkness;
  42307. };
  42308. /**
  42309. * Sets the ShadowGenerator darkness value (float <= 1.0).
  42310. * Returns the ShadowGenerator.
  42311. */
  42312. ShadowGenerator.prototype.setDarkness = function (darkness) {
  42313. if (darkness >= 1.0)
  42314. this._darkness = 1.0;
  42315. else if (darkness <= 0.0)
  42316. this._darkness = 0.0;
  42317. else
  42318. this._darkness = darkness;
  42319. return this;
  42320. };
  42321. /**
  42322. * Sets the ability to have transparent shadow (boolean).
  42323. * Returns the ShadowGenerator.
  42324. */
  42325. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  42326. this._transparencyShadow = hasShadow;
  42327. return this;
  42328. };
  42329. ShadowGenerator.prototype._packHalf = function (depth) {
  42330. var scale = depth * 255.0;
  42331. var fract = scale - Math.floor(scale);
  42332. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  42333. };
  42334. /**
  42335. * Disposes the ShadowGenerator.
  42336. * Returns nothing.
  42337. */
  42338. ShadowGenerator.prototype.dispose = function () {
  42339. this._shadowMap.dispose();
  42340. if (this._shadowMap2) {
  42341. this._shadowMap2.dispose();
  42342. }
  42343. if (this._downSamplePostprocess) {
  42344. this._downSamplePostprocess.dispose();
  42345. }
  42346. if (this._boxBlurPostprocess) {
  42347. this._boxBlurPostprocess.dispose();
  42348. }
  42349. this._light._shadowGenerator = null;
  42350. this._light._markMeshesAsLightDirty();
  42351. };
  42352. /**
  42353. * Serializes the ShadowGenerator and returns a serializationObject.
  42354. */
  42355. ShadowGenerator.prototype.serialize = function () {
  42356. var serializationObject = {};
  42357. serializationObject.lightId = this._light.id;
  42358. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  42359. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  42360. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  42361. serializationObject.usePoissonSampling = this.usePoissonSampling;
  42362. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  42363. serializationObject.depthScale = this.depthScale;
  42364. serializationObject.darkness = this.getDarkness();
  42365. serializationObject.renderList = [];
  42366. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  42367. var mesh = this.getShadowMap().renderList[meshIndex];
  42368. serializationObject.renderList.push(mesh.id);
  42369. }
  42370. return serializationObject;
  42371. };
  42372. /**
  42373. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  42374. */
  42375. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  42376. //casting to point light, as light is missing the position attr and typescript complains.
  42377. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  42378. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  42379. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  42380. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  42381. meshes.forEach(function (mesh) {
  42382. shadowGenerator.getShadowMap().renderList.push(mesh);
  42383. });
  42384. }
  42385. if (parsedShadowGenerator.usePoissonSampling) {
  42386. shadowGenerator.usePoissonSampling = true;
  42387. }
  42388. else if (parsedShadowGenerator.useExponentialShadowMap) {
  42389. shadowGenerator.useExponentialShadowMap = true;
  42390. }
  42391. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  42392. shadowGenerator.useBlurExponentialShadowMap = true;
  42393. }
  42394. else if (parsedShadowGenerator.useVarianceShadowMap) {
  42395. shadowGenerator.useExponentialShadowMap = true;
  42396. }
  42397. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  42398. shadowGenerator.useBlurExponentialShadowMap = true;
  42399. }
  42400. if (parsedShadowGenerator.depthScale) {
  42401. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  42402. }
  42403. if (parsedShadowGenerator.blurScale) {
  42404. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  42405. }
  42406. if (parsedShadowGenerator.blurBoxOffset) {
  42407. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  42408. }
  42409. if (parsedShadowGenerator.bias !== undefined) {
  42410. shadowGenerator.bias = parsedShadowGenerator.bias;
  42411. }
  42412. if (parsedShadowGenerator.darkness) {
  42413. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  42414. }
  42415. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  42416. return shadowGenerator;
  42417. };
  42418. return ShadowGenerator;
  42419. }());
  42420. ShadowGenerator._FILTER_NONE = 0;
  42421. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  42422. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  42423. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  42424. BABYLON.ShadowGenerator = ShadowGenerator;
  42425. })(BABYLON || (BABYLON = {}));
  42426. //# sourceMappingURL=babylon.shadowGenerator.js.map
  42427. var BABYLON;
  42428. (function (BABYLON) {
  42429. var DefaultLoadingScreen = (function () {
  42430. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  42431. if (_loadingText === void 0) { _loadingText = ""; }
  42432. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  42433. var _this = this;
  42434. this._renderingCanvas = _renderingCanvas;
  42435. this._loadingText = _loadingText;
  42436. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  42437. // Resize
  42438. this._resizeLoadingUI = function () {
  42439. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  42440. _this._loadingDiv.style.position = "absolute";
  42441. _this._loadingDiv.style.left = canvasRect.left + "px";
  42442. _this._loadingDiv.style.top = canvasRect.top + "px";
  42443. _this._loadingDiv.style.width = canvasRect.width + "px";
  42444. _this._loadingDiv.style.height = canvasRect.height + "px";
  42445. };
  42446. }
  42447. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  42448. var _this = this;
  42449. if (this._loadingDiv) {
  42450. // Do not add a loading screen if there is already one
  42451. return;
  42452. }
  42453. this._loadingDiv = document.createElement("div");
  42454. this._loadingDiv.id = "babylonjsLoadingDiv";
  42455. this._loadingDiv.style.opacity = "0";
  42456. this._loadingDiv.style.transition = "opacity 1.5s ease";
  42457. // Loading text
  42458. this._loadingTextDiv = document.createElement("div");
  42459. this._loadingTextDiv.style.position = "absolute";
  42460. this._loadingTextDiv.style.left = "0";
  42461. this._loadingTextDiv.style.top = "50%";
  42462. this._loadingTextDiv.style.marginTop = "80px";
  42463. this._loadingTextDiv.style.width = "100%";
  42464. this._loadingTextDiv.style.height = "20px";
  42465. this._loadingTextDiv.style.fontFamily = "Arial";
  42466. this._loadingTextDiv.style.fontSize = "14px";
  42467. this._loadingTextDiv.style.color = "white";
  42468. this._loadingTextDiv.style.textAlign = "center";
  42469. this._loadingTextDiv.innerHTML = "Loading";
  42470. this._loadingDiv.appendChild(this._loadingTextDiv);
  42471. //set the predefined text
  42472. this._loadingTextDiv.innerHTML = this._loadingText;
  42473. // Loading img
  42474. var imgBack = new Image();
  42475. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
  42476. imgBack.style.position = "absolute";
  42477. imgBack.style.left = "50%";
  42478. imgBack.style.top = "50%";
  42479. imgBack.style.marginLeft = "-50px";
  42480. imgBack.style.marginTop = "-50px";
  42481. imgBack.style.transition = "transform 1.0s ease";
  42482. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  42483. var deg = 360;
  42484. var onTransitionEnd = function () {
  42485. deg += 360;
  42486. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  42487. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  42488. };
  42489. imgBack.addEventListener("transitionend", onTransitionEnd);
  42490. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  42491. this._loadingDiv.appendChild(imgBack);
  42492. // front image
  42493. var imgFront = new Image();
  42494. imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
  42495. imgFront.style.position = "absolute";
  42496. imgFront.style.left = "50%";
  42497. imgFront.style.top = "50%";
  42498. imgFront.style.marginLeft = "-50px";
  42499. imgFront.style.marginTop = "-50px";
  42500. this._loadingDiv.appendChild(imgFront);
  42501. this._resizeLoadingUI();
  42502. window.addEventListener("resize", this._resizeLoadingUI);
  42503. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42504. document.body.appendChild(this._loadingDiv);
  42505. setTimeout(function () {
  42506. _this._loadingDiv.style.opacity = "1";
  42507. imgBack.style.transform = "rotateZ(360deg)";
  42508. imgBack.style.webkitTransform = "rotateZ(360deg)";
  42509. }, 0);
  42510. };
  42511. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  42512. var _this = this;
  42513. if (!this._loadingDiv) {
  42514. return;
  42515. }
  42516. var onTransitionEnd = function () {
  42517. if (!_this._loadingDiv) {
  42518. return;
  42519. }
  42520. document.body.removeChild(_this._loadingDiv);
  42521. window.removeEventListener("resize", _this._resizeLoadingUI);
  42522. _this._loadingDiv = null;
  42523. };
  42524. this._loadingDiv.style.opacity = "0";
  42525. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  42526. };
  42527. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  42528. set: function (text) {
  42529. this._loadingText = text;
  42530. if (this._loadingTextDiv) {
  42531. this._loadingTextDiv.innerHTML = this._loadingText;
  42532. }
  42533. },
  42534. enumerable: true,
  42535. configurable: true
  42536. });
  42537. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  42538. get: function () {
  42539. return this._loadingDivBackgroundColor;
  42540. },
  42541. set: function (color) {
  42542. this._loadingDivBackgroundColor = color;
  42543. if (!this._loadingDiv) {
  42544. return;
  42545. }
  42546. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42547. },
  42548. enumerable: true,
  42549. configurable: true
  42550. });
  42551. return DefaultLoadingScreen;
  42552. }());
  42553. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  42554. })(BABYLON || (BABYLON = {}));
  42555. //# sourceMappingURL=babylon.loadingScreen.js.map
  42556. var BABYLON;
  42557. (function (BABYLON) {
  42558. var SceneLoader = (function () {
  42559. function SceneLoader() {
  42560. }
  42561. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  42562. get: function () {
  42563. return 0;
  42564. },
  42565. enumerable: true,
  42566. configurable: true
  42567. });
  42568. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  42569. get: function () {
  42570. return 1;
  42571. },
  42572. enumerable: true,
  42573. configurable: true
  42574. });
  42575. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  42576. get: function () {
  42577. return 2;
  42578. },
  42579. enumerable: true,
  42580. configurable: true
  42581. });
  42582. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  42583. get: function () {
  42584. return 3;
  42585. },
  42586. enumerable: true,
  42587. configurable: true
  42588. });
  42589. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  42590. get: function () {
  42591. return SceneLoader._ForceFullSceneLoadingForIncremental;
  42592. },
  42593. set: function (value) {
  42594. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  42595. },
  42596. enumerable: true,
  42597. configurable: true
  42598. });
  42599. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  42600. get: function () {
  42601. return SceneLoader._ShowLoadingScreen;
  42602. },
  42603. set: function (value) {
  42604. SceneLoader._ShowLoadingScreen = value;
  42605. },
  42606. enumerable: true,
  42607. configurable: true
  42608. });
  42609. Object.defineProperty(SceneLoader, "loggingLevel", {
  42610. get: function () {
  42611. return SceneLoader._loggingLevel;
  42612. },
  42613. set: function (value) {
  42614. SceneLoader._loggingLevel = value;
  42615. },
  42616. enumerable: true,
  42617. configurable: true
  42618. });
  42619. SceneLoader._getDefaultPlugin = function () {
  42620. return SceneLoader._registeredPlugins[".babylon"];
  42621. };
  42622. SceneLoader._getPluginForExtension = function (extension) {
  42623. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  42624. if (registeredPlugin) {
  42625. return registeredPlugin;
  42626. }
  42627. return SceneLoader._getDefaultPlugin();
  42628. };
  42629. SceneLoader._getPluginForFilename = function (sceneFilename) {
  42630. if (sceneFilename.name) {
  42631. sceneFilename = sceneFilename.name;
  42632. }
  42633. var dotPosition = sceneFilename.lastIndexOf(".");
  42634. var queryStringPosition = sceneFilename.indexOf("?");
  42635. if (queryStringPosition === -1) {
  42636. queryStringPosition = sceneFilename.length;
  42637. }
  42638. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  42639. return SceneLoader._getPluginForExtension(extension);
  42640. };
  42641. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  42642. SceneLoader._getDirectLoad = function (sceneFilename) {
  42643. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  42644. return sceneFilename.substr(5);
  42645. }
  42646. return null;
  42647. };
  42648. // Public functions
  42649. SceneLoader.GetPluginForExtension = function (extension) {
  42650. return SceneLoader._getPluginForExtension(extension).plugin;
  42651. };
  42652. SceneLoader.RegisterPlugin = function (plugin) {
  42653. if (typeof plugin.extensions === "string") {
  42654. var extension = plugin.extensions;
  42655. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  42656. plugin: plugin,
  42657. isBinary: false
  42658. };
  42659. }
  42660. else {
  42661. var extensions = plugin.extensions;
  42662. Object.keys(extensions).forEach(function (extension) {
  42663. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  42664. plugin: plugin,
  42665. isBinary: extensions[extension].isBinary
  42666. };
  42667. });
  42668. }
  42669. };
  42670. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  42671. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  42672. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  42673. return;
  42674. }
  42675. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  42676. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  42677. return;
  42678. }
  42679. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  42680. var loadingToken = {};
  42681. scene._addPendingData(loadingToken);
  42682. var manifestChecked = function (success) {
  42683. scene.database = database;
  42684. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  42685. var plugin = registeredPlugin.plugin;
  42686. var useArrayBuffer = registeredPlugin.isBinary;
  42687. var importMeshFromData = function (data) {
  42688. var meshes = [];
  42689. var particleSystems = [];
  42690. var skeletons = [];
  42691. if (scene.isDisposed) {
  42692. if (onerror) {
  42693. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  42694. }
  42695. return;
  42696. }
  42697. try {
  42698. if (plugin.importMesh) {
  42699. var syncedPlugin = plugin;
  42700. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  42701. if (onerror) {
  42702. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  42703. }
  42704. scene._removePendingData(loadingToken);
  42705. return;
  42706. }
  42707. if (onsuccess) {
  42708. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  42709. onsuccess(meshes, particleSystems, skeletons);
  42710. scene._removePendingData(loadingToken);
  42711. }
  42712. }
  42713. else {
  42714. var asyncedPlugin = plugin;
  42715. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  42716. if (onsuccess) {
  42717. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  42718. onsuccess(meshes, particleSystems, skeletons);
  42719. scene._removePendingData(loadingToken);
  42720. }
  42721. }, function () {
  42722. if (onerror) {
  42723. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  42724. }
  42725. scene._removePendingData(loadingToken);
  42726. });
  42727. }
  42728. }
  42729. catch (e) {
  42730. if (onerror) {
  42731. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  42732. }
  42733. scene._removePendingData(loadingToken);
  42734. }
  42735. };
  42736. if (directLoad) {
  42737. importMeshFromData(directLoad);
  42738. return;
  42739. }
  42740. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  42741. importMeshFromData(data);
  42742. }, progressCallBack, database, useArrayBuffer, function () {
  42743. if (onerror) {
  42744. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  42745. }
  42746. });
  42747. };
  42748. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  42749. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  42750. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  42751. }
  42752. else {
  42753. // If the scene is a data stream or offline support is not enabled, it's a direct load
  42754. manifestChecked(true);
  42755. }
  42756. };
  42757. /**
  42758. * Load a scene
  42759. * @param rootUrl a string that defines the root url for scene and resources
  42760. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  42761. * @param engine is the instance of BABYLON.Engine to use to create the scene
  42762. */
  42763. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  42764. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  42765. };
  42766. /**
  42767. * Append a scene
  42768. * @param rootUrl a string that defines the root url for scene and resources
  42769. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  42770. * @param scene is the instance of BABYLON.Scene to append to
  42771. */
  42772. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  42773. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  42774. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  42775. return;
  42776. }
  42777. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  42778. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  42779. var plugin = registeredPlugin.plugin;
  42780. var useArrayBuffer = registeredPlugin.isBinary;
  42781. var database;
  42782. var loadingToken = {};
  42783. scene._addPendingData(loadingToken);
  42784. if (SceneLoader.ShowLoadingScreen) {
  42785. scene.getEngine().displayLoadingUI();
  42786. }
  42787. var loadSceneFromData = function (data) {
  42788. scene.database = database;
  42789. if (plugin.load) {
  42790. var syncedPlugin = plugin;
  42791. if (!syncedPlugin.load(scene, data, rootUrl)) {
  42792. if (onerror) {
  42793. onerror(scene);
  42794. }
  42795. scene._removePendingData(loadingToken);
  42796. scene.getEngine().hideLoadingUI();
  42797. return;
  42798. }
  42799. if (onsuccess) {
  42800. onsuccess(scene);
  42801. }
  42802. scene._removePendingData(loadingToken);
  42803. }
  42804. else {
  42805. var asyncedPlugin = plugin;
  42806. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  42807. if (onsuccess) {
  42808. onsuccess(scene);
  42809. }
  42810. scene._removePendingData(loadingToken);
  42811. }, function () {
  42812. if (onerror) {
  42813. onerror(scene);
  42814. }
  42815. scene._removePendingData(loadingToken);
  42816. scene.getEngine().hideLoadingUI();
  42817. });
  42818. }
  42819. if (SceneLoader.ShowLoadingScreen) {
  42820. scene.executeWhenReady(function () {
  42821. scene.getEngine().hideLoadingUI();
  42822. });
  42823. }
  42824. };
  42825. var manifestChecked = function (success) {
  42826. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  42827. };
  42828. if (directLoad) {
  42829. loadSceneFromData(directLoad);
  42830. return;
  42831. }
  42832. if (rootUrl.indexOf("file:") === -1) {
  42833. if (scene.getEngine().enableOfflineSupport) {
  42834. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  42835. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  42836. }
  42837. else {
  42838. manifestChecked(true);
  42839. }
  42840. }
  42841. else {
  42842. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  42843. }
  42844. };
  42845. return SceneLoader;
  42846. }());
  42847. // Flags
  42848. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  42849. SceneLoader._ShowLoadingScreen = true;
  42850. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  42851. // Members
  42852. SceneLoader._registeredPlugins = {};
  42853. BABYLON.SceneLoader = SceneLoader;
  42854. ;
  42855. })(BABYLON || (BABYLON = {}));
  42856. //# sourceMappingURL=babylon.sceneLoader.js.map
  42857. var BABYLON;
  42858. (function (BABYLON) {
  42859. var Internals;
  42860. (function (Internals) {
  42861. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  42862. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  42863. var parsedMaterial = parsedData.materials[index];
  42864. if (parsedMaterial.id === id) {
  42865. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  42866. }
  42867. }
  42868. return null;
  42869. };
  42870. var isDescendantOf = function (mesh, names, hierarchyIds) {
  42871. names = (names instanceof Array) ? names : [names];
  42872. for (var i in names) {
  42873. if (mesh.name === names[i]) {
  42874. hierarchyIds.push(mesh.id);
  42875. return true;
  42876. }
  42877. }
  42878. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  42879. hierarchyIds.push(mesh.id);
  42880. return true;
  42881. }
  42882. return false;
  42883. };
  42884. var logOperation = function (operation, producer) {
  42885. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  42886. };
  42887. BABYLON.SceneLoader.RegisterPlugin({
  42888. extensions: ".babylon",
  42889. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  42890. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  42891. // when SceneLoader.debugLogging = true (default), or exception encountered.
  42892. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  42893. // and avoid problems with multiple concurrent .babylon loads.
  42894. var log = "importMesh has failed JSON parse";
  42895. try {
  42896. var parsedData = JSON.parse(data);
  42897. log = "";
  42898. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  42899. var loadedSkeletonsIds = [];
  42900. var loadedMaterialsIds = [];
  42901. var hierarchyIds = [];
  42902. var index;
  42903. var cache;
  42904. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  42905. var parsedMesh = parsedData.meshes[index];
  42906. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  42907. if (meshesNames instanceof Array) {
  42908. // Remove found mesh name from list.
  42909. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  42910. }
  42911. //Geometry?
  42912. if (parsedMesh.geometryId) {
  42913. //does the file contain geometries?
  42914. if (parsedData.geometries) {
  42915. //find the correct geometry and add it to the scene
  42916. var found = false;
  42917. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  42918. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  42919. return;
  42920. }
  42921. else {
  42922. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  42923. if (parsedGeometryData.id === parsedMesh.geometryId) {
  42924. switch (geometryType) {
  42925. case "boxes":
  42926. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  42927. break;
  42928. case "spheres":
  42929. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  42930. break;
  42931. case "cylinders":
  42932. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  42933. break;
  42934. case "toruses":
  42935. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  42936. break;
  42937. case "grounds":
  42938. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  42939. break;
  42940. case "planes":
  42941. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  42942. break;
  42943. case "torusKnots":
  42944. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  42945. break;
  42946. case "vertexData":
  42947. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  42948. break;
  42949. }
  42950. found = true;
  42951. }
  42952. });
  42953. }
  42954. });
  42955. if (!found) {
  42956. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  42957. }
  42958. }
  42959. }
  42960. // Material ?
  42961. if (parsedMesh.materialId) {
  42962. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  42963. if (!materialFound && parsedData.multiMaterials) {
  42964. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  42965. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  42966. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  42967. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  42968. var subMatId = parsedMultiMaterial.materials[matIndex];
  42969. loadedMaterialsIds.push(subMatId);
  42970. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  42971. log += "\n\tMaterial " + mat.toString(fullDetails);
  42972. }
  42973. loadedMaterialsIds.push(parsedMultiMaterial.id);
  42974. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  42975. materialFound = true;
  42976. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  42977. break;
  42978. }
  42979. }
  42980. }
  42981. if (!materialFound) {
  42982. loadedMaterialsIds.push(parsedMesh.materialId);
  42983. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  42984. if (!mat) {
  42985. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  42986. }
  42987. else {
  42988. log += "\n\tMaterial " + mat.toString(fullDetails);
  42989. }
  42990. }
  42991. }
  42992. // Skeleton ?
  42993. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  42994. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  42995. if (!skeletonAlreadyLoaded) {
  42996. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  42997. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  42998. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  42999. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  43000. skeletons.push(skeleton);
  43001. loadedSkeletonsIds.push(parsedSkeleton.id);
  43002. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  43003. }
  43004. }
  43005. }
  43006. }
  43007. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  43008. meshes.push(mesh);
  43009. log += "\n\tMesh " + mesh.toString(fullDetails);
  43010. }
  43011. }
  43012. // Connecting parents
  43013. var currentMesh;
  43014. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  43015. currentMesh = scene.meshes[index];
  43016. if (currentMesh._waitingParentId) {
  43017. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  43018. currentMesh._waitingParentId = undefined;
  43019. }
  43020. }
  43021. // freeze and compute world matrix application
  43022. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  43023. currentMesh = scene.meshes[index];
  43024. if (currentMesh._waitingFreezeWorldMatrix) {
  43025. currentMesh.freezeWorldMatrix();
  43026. currentMesh._waitingFreezeWorldMatrix = undefined;
  43027. }
  43028. else {
  43029. currentMesh.computeWorldMatrix(true);
  43030. }
  43031. }
  43032. // Particles
  43033. if (parsedData.particleSystems) {
  43034. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  43035. var parsedParticleSystem = parsedData.particleSystems[index];
  43036. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  43037. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  43038. }
  43039. }
  43040. }
  43041. return true;
  43042. }
  43043. catch (err) {
  43044. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  43045. log = null;
  43046. throw err;
  43047. }
  43048. finally {
  43049. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  43050. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  43051. }
  43052. }
  43053. },
  43054. load: function (scene, data, rootUrl) {
  43055. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  43056. // when SceneLoader.debugLogging = true (default), or exception encountered.
  43057. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  43058. // and avoid problems with multiple concurrent .babylon loads.
  43059. var log = "importScene has failed JSON parse";
  43060. try {
  43061. var parsedData = JSON.parse(data);
  43062. log = "";
  43063. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  43064. // Scene
  43065. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  43066. scene.autoClear = parsedData.autoClear;
  43067. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  43068. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  43069. if (parsedData.gravity) {
  43070. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  43071. }
  43072. // Fog
  43073. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  43074. scene.fogMode = parsedData.fogMode;
  43075. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  43076. scene.fogStart = parsedData.fogStart;
  43077. scene.fogEnd = parsedData.fogEnd;
  43078. scene.fogDensity = parsedData.fogDensity;
  43079. log += "\tFog mode for scene: ";
  43080. switch (scene.fogMode) {
  43081. // getters not compiling, so using hardcoded
  43082. case 1:
  43083. log += "exp\n";
  43084. break;
  43085. case 2:
  43086. log += "exp2\n";
  43087. break;
  43088. case 3:
  43089. log += "linear\n";
  43090. break;
  43091. }
  43092. }
  43093. //Physics
  43094. if (parsedData.physicsEnabled) {
  43095. var physicsPlugin;
  43096. if (parsedData.physicsEngine === "cannon") {
  43097. physicsPlugin = new BABYLON.CannonJSPlugin();
  43098. }
  43099. else if (parsedData.physicsEngine === "oimo") {
  43100. physicsPlugin = new BABYLON.OimoJSPlugin();
  43101. }
  43102. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  43103. //else - default engine, which is currently oimo
  43104. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  43105. scene.enablePhysics(physicsGravity, physicsPlugin);
  43106. }
  43107. // Metadata
  43108. if (parsedData.metadata !== undefined) {
  43109. scene.metadata = parsedData.metadata;
  43110. }
  43111. //collisions, if defined. otherwise, default is true
  43112. if (parsedData.collisionsEnabled != undefined) {
  43113. scene.collisionsEnabled = parsedData.collisionsEnabled;
  43114. }
  43115. scene.workerCollisions = !!parsedData.workerCollisions;
  43116. var index;
  43117. var cache;
  43118. // Lights
  43119. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  43120. var parsedLight = parsedData.lights[index];
  43121. var light = BABYLON.Light.Parse(parsedLight, scene);
  43122. log += (index === 0 ? "\n\tLights:" : "");
  43123. log += "\n\t\t" + light.toString(fullDetails);
  43124. }
  43125. // Animations
  43126. if (parsedData.animations) {
  43127. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  43128. var parsedAnimation = parsedData.animations[index];
  43129. var animation = BABYLON.Animation.Parse(parsedAnimation);
  43130. scene.animations.push(animation);
  43131. log += (index === 0 ? "\n\tAnimations:" : "");
  43132. log += "\n\t\t" + animation.toString(fullDetails);
  43133. }
  43134. }
  43135. if (parsedData.autoAnimate) {
  43136. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  43137. }
  43138. // Materials
  43139. if (parsedData.materials) {
  43140. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  43141. var parsedMaterial = parsedData.materials[index];
  43142. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  43143. log += (index === 0 ? "\n\tMaterials:" : "");
  43144. log += "\n\t\t" + mat.toString(fullDetails);
  43145. }
  43146. }
  43147. if (parsedData.multiMaterials) {
  43148. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  43149. var parsedMultiMaterial = parsedData.multiMaterials[index];
  43150. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  43151. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  43152. log += "\n\t\t" + mmat.toString(fullDetails);
  43153. }
  43154. }
  43155. // Morph targets
  43156. if (parsedData.morphTargetManagers) {
  43157. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  43158. var managerData = _a[_i];
  43159. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  43160. }
  43161. }
  43162. // Skeletons
  43163. if (parsedData.skeletons) {
  43164. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  43165. var parsedSkeleton = parsedData.skeletons[index];
  43166. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  43167. log += (index === 0 ? "\n\tSkeletons:" : "");
  43168. log += "\n\t\t" + skeleton.toString(fullDetails);
  43169. }
  43170. }
  43171. // Geometries
  43172. var geometries = parsedData.geometries;
  43173. if (geometries) {
  43174. // Boxes
  43175. var boxes = geometries.boxes;
  43176. if (boxes) {
  43177. for (index = 0, cache = boxes.length; index < cache; index++) {
  43178. var parsedBox = boxes[index];
  43179. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  43180. }
  43181. }
  43182. // Spheres
  43183. var spheres = geometries.spheres;
  43184. if (spheres) {
  43185. for (index = 0, cache = spheres.length; index < cache; index++) {
  43186. var parsedSphere = spheres[index];
  43187. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  43188. }
  43189. }
  43190. // Cylinders
  43191. var cylinders = geometries.cylinders;
  43192. if (cylinders) {
  43193. for (index = 0, cache = cylinders.length; index < cache; index++) {
  43194. var parsedCylinder = cylinders[index];
  43195. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  43196. }
  43197. }
  43198. // Toruses
  43199. var toruses = geometries.toruses;
  43200. if (toruses) {
  43201. for (index = 0, cache = toruses.length; index < cache; index++) {
  43202. var parsedTorus = toruses[index];
  43203. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  43204. }
  43205. }
  43206. // Grounds
  43207. var grounds = geometries.grounds;
  43208. if (grounds) {
  43209. for (index = 0, cache = grounds.length; index < cache; index++) {
  43210. var parsedGround = grounds[index];
  43211. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  43212. }
  43213. }
  43214. // Planes
  43215. var planes = geometries.planes;
  43216. if (planes) {
  43217. for (index = 0, cache = planes.length; index < cache; index++) {
  43218. var parsedPlane = planes[index];
  43219. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  43220. }
  43221. }
  43222. // TorusKnots
  43223. var torusKnots = geometries.torusKnots;
  43224. if (torusKnots) {
  43225. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  43226. var parsedTorusKnot = torusKnots[index];
  43227. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  43228. }
  43229. }
  43230. // VertexData
  43231. var vertexData = geometries.vertexData;
  43232. if (vertexData) {
  43233. for (index = 0, cache = vertexData.length; index < cache; index++) {
  43234. var parsedVertexData = vertexData[index];
  43235. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  43236. }
  43237. }
  43238. }
  43239. // Meshes
  43240. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  43241. var parsedMesh = parsedData.meshes[index];
  43242. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  43243. log += (index === 0 ? "\n\tMeshes:" : "");
  43244. log += "\n\t\t" + mesh.toString(fullDetails);
  43245. }
  43246. // Cameras
  43247. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  43248. var parsedCamera = parsedData.cameras[index];
  43249. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  43250. log += (index === 0 ? "\n\tCameras:" : "");
  43251. log += "\n\t\t" + camera.toString(fullDetails);
  43252. }
  43253. if (parsedData.activeCameraID) {
  43254. scene.setActiveCameraByID(parsedData.activeCameraID);
  43255. }
  43256. // Browsing all the graph to connect the dots
  43257. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  43258. var camera = scene.cameras[index];
  43259. if (camera._waitingParentId) {
  43260. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  43261. camera._waitingParentId = undefined;
  43262. }
  43263. }
  43264. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  43265. var light = scene.lights[index];
  43266. if (light._waitingParentId) {
  43267. light.parent = scene.getLastEntryByID(light._waitingParentId);
  43268. light._waitingParentId = undefined;
  43269. }
  43270. }
  43271. // Sounds
  43272. var loadedSounds = [];
  43273. var loadedSound;
  43274. if (BABYLON.AudioEngine && parsedData.sounds) {
  43275. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  43276. var parsedSound = parsedData.sounds[index];
  43277. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43278. if (!parsedSound.url)
  43279. parsedSound.url = parsedSound.name;
  43280. if (!loadedSounds[parsedSound.url]) {
  43281. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  43282. loadedSounds[parsedSound.url] = loadedSound;
  43283. }
  43284. else {
  43285. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  43286. }
  43287. }
  43288. else {
  43289. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  43290. }
  43291. }
  43292. }
  43293. loadedSounds = [];
  43294. // Connect parents & children and parse actions
  43295. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  43296. var mesh = scene.meshes[index];
  43297. if (mesh._waitingParentId) {
  43298. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  43299. mesh._waitingParentId = undefined;
  43300. }
  43301. if (mesh._waitingActions) {
  43302. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  43303. mesh._waitingActions = undefined;
  43304. }
  43305. }
  43306. // freeze world matrix application
  43307. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  43308. var currentMesh = scene.meshes[index];
  43309. if (currentMesh._waitingFreezeWorldMatrix) {
  43310. currentMesh.freezeWorldMatrix();
  43311. currentMesh._waitingFreezeWorldMatrix = undefined;
  43312. }
  43313. else {
  43314. currentMesh.computeWorldMatrix(true);
  43315. }
  43316. }
  43317. // Particles Systems
  43318. if (parsedData.particleSystems) {
  43319. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  43320. var parsedParticleSystem = parsedData.particleSystems[index];
  43321. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  43322. }
  43323. }
  43324. // Lens flares
  43325. if (parsedData.lensFlareSystems) {
  43326. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  43327. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  43328. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  43329. }
  43330. }
  43331. // Shadows
  43332. if (parsedData.shadowGenerators) {
  43333. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  43334. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  43335. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  43336. }
  43337. }
  43338. // Lights exclusions / inclusions
  43339. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  43340. var light = scene.lights[index];
  43341. // Excluded check
  43342. if (light._excludedMeshesIds.length > 0) {
  43343. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  43344. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  43345. if (excludedMesh) {
  43346. light.excludedMeshes.push(excludedMesh);
  43347. }
  43348. }
  43349. light._excludedMeshesIds = [];
  43350. }
  43351. // Included check
  43352. if (light._includedOnlyMeshesIds.length > 0) {
  43353. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  43354. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  43355. if (includedOnlyMesh) {
  43356. light.includedOnlyMeshes.push(includedOnlyMesh);
  43357. }
  43358. }
  43359. light._includedOnlyMeshesIds = [];
  43360. }
  43361. }
  43362. // Actions (scene)
  43363. if (parsedData.actions) {
  43364. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  43365. }
  43366. // Finish
  43367. return true;
  43368. }
  43369. catch (err) {
  43370. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  43371. log = null;
  43372. throw err;
  43373. }
  43374. finally {
  43375. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  43376. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  43377. }
  43378. }
  43379. }
  43380. });
  43381. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43382. })(BABYLON || (BABYLON = {}));
  43383. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  43384. var BABYLON;
  43385. (function (BABYLON) {
  43386. var FilesInput = (function () {
  43387. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  43388. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  43389. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  43390. this._engine = p_engine;
  43391. this._canvas = p_canvas;
  43392. this._currentScene = p_scene;
  43393. this._sceneLoadedCallback = p_sceneLoadedCallback;
  43394. this._progressCallback = p_progressCallback;
  43395. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  43396. this._textureLoadingCallback = p_textureLoadingCallback;
  43397. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  43398. }
  43399. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  43400. var _this = this;
  43401. if (p_elementToMonitor) {
  43402. this._elementToMonitor = p_elementToMonitor;
  43403. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  43404. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  43405. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  43406. }
  43407. };
  43408. FilesInput.prototype.renderFunction = function () {
  43409. if (this._additionnalRenderLoopLogicCallback) {
  43410. this._additionnalRenderLoopLogicCallback();
  43411. }
  43412. if (this._currentScene) {
  43413. if (this._textureLoadingCallback) {
  43414. var remaining = this._currentScene.getWaitingItemsCount();
  43415. if (remaining > 0) {
  43416. this._textureLoadingCallback(remaining);
  43417. }
  43418. }
  43419. this._currentScene.render();
  43420. }
  43421. };
  43422. FilesInput.prototype.drag = function (e) {
  43423. e.stopPropagation();
  43424. e.preventDefault();
  43425. };
  43426. FilesInput.prototype.drop = function (eventDrop) {
  43427. eventDrop.stopPropagation();
  43428. eventDrop.preventDefault();
  43429. this.loadFiles(eventDrop);
  43430. };
  43431. FilesInput.prototype.loadFiles = function (event) {
  43432. if (this._startingProcessingFilesCallback)
  43433. this._startingProcessingFilesCallback();
  43434. // Handling data transfer via drag'n'drop
  43435. if (event && event.dataTransfer && event.dataTransfer.files) {
  43436. this._filesToLoad = event.dataTransfer.files;
  43437. }
  43438. // Handling files from input files
  43439. if (event && event.target && event.target.files) {
  43440. this._filesToLoad = event.target.files;
  43441. }
  43442. if (this._filesToLoad && this._filesToLoad.length > 0) {
  43443. for (var i = 0; i < this._filesToLoad.length; i++) {
  43444. var name_1 = this._filesToLoad[i].name.toLowerCase();
  43445. var extension = name_1.split('.').pop();
  43446. var type = this._filesToLoad[i].type;
  43447. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  43448. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  43449. this._sceneFileToLoad = this._filesToLoad[i];
  43450. }
  43451. else {
  43452. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  43453. }
  43454. }
  43455. this.reload();
  43456. }
  43457. };
  43458. FilesInput.prototype.reload = function () {
  43459. var _this = this;
  43460. var that = this;
  43461. // If a ".babylon" file has been provided
  43462. if (this._sceneFileToLoad) {
  43463. if (this._currentScene) {
  43464. if (BABYLON.Tools.errorsCount > 0) {
  43465. BABYLON.Tools.ClearLogCache();
  43466. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  43467. }
  43468. this._engine.stopRenderLoop();
  43469. this._currentScene.dispose();
  43470. }
  43471. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  43472. that._currentScene = newScene;
  43473. // Wait for textures and shaders to be ready
  43474. that._currentScene.executeWhenReady(function () {
  43475. if (that._sceneLoadedCallback) {
  43476. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  43477. }
  43478. that._engine.runRenderLoop(function () { that.renderFunction(); });
  43479. });
  43480. }, function (progress) {
  43481. if (_this._progressCallback) {
  43482. _this._progressCallback(progress);
  43483. }
  43484. });
  43485. }
  43486. else {
  43487. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  43488. }
  43489. };
  43490. return FilesInput;
  43491. }());
  43492. FilesInput.FilesToLoad = new Array();
  43493. BABYLON.FilesInput = FilesInput;
  43494. })(BABYLON || (BABYLON = {}));
  43495. //# sourceMappingURL=babylon.filesInput.js.map
  43496. var BABYLON;
  43497. (function (BABYLON) {
  43498. /**
  43499. * This class implement a typical dictionary using a string as key and the generic type T as value.
  43500. * The underlying implementation relies on an associative array to ensure the best performances.
  43501. * The value can be anything including 'null' but except 'undefined'
  43502. */
  43503. var StringDictionary = (function () {
  43504. function StringDictionary() {
  43505. this._count = 0;
  43506. this._data = {};
  43507. }
  43508. /**
  43509. * This will clear this dictionary and copy the content from the 'source' one.
  43510. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  43511. * @param source the dictionary to take the content from and copy to this dictionary
  43512. */
  43513. StringDictionary.prototype.copyFrom = function (source) {
  43514. var _this = this;
  43515. this.clear();
  43516. source.forEach(function (t, v) { return _this.add(t, v); });
  43517. };
  43518. /**
  43519. * Get a value based from its key
  43520. * @param key the given key to get the matching value from
  43521. * @return the value if found, otherwise undefined is returned
  43522. */
  43523. StringDictionary.prototype.get = function (key) {
  43524. var val = this._data[key];
  43525. if (val !== undefined) {
  43526. return val;
  43527. }
  43528. return undefined;
  43529. };
  43530. /**
  43531. * Get a value from its key or add it if it doesn't exist.
  43532. * This method will ensure you that a given key/data will be present in the dictionary.
  43533. * @param key the given key to get the matching value from
  43534. * @param factory the factory that will create the value if the key is not present in the dictionary.
  43535. * The factory will only be invoked if there's no data for the given key.
  43536. * @return the value corresponding to the key.
  43537. */
  43538. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  43539. var val = this.get(key);
  43540. if (val !== undefined) {
  43541. return val;
  43542. }
  43543. val = factory(key);
  43544. if (val) {
  43545. this.add(key, val);
  43546. }
  43547. return val;
  43548. };
  43549. /**
  43550. * Get a value from its key if present in the dictionary otherwise add it
  43551. * @param key the key to get the value from
  43552. * @param val if there's no such key/value pair in the dictionary add it with this value
  43553. * @return the value corresponding to the key
  43554. */
  43555. StringDictionary.prototype.getOrAdd = function (key, val) {
  43556. var curVal = this.get(key);
  43557. if (curVal !== undefined) {
  43558. return curVal;
  43559. }
  43560. this.add(key, val);
  43561. return val;
  43562. };
  43563. /**
  43564. * Check if there's a given key in the dictionary
  43565. * @param key the key to check for
  43566. * @return true if the key is present, false otherwise
  43567. */
  43568. StringDictionary.prototype.contains = function (key) {
  43569. return this._data[key] !== undefined;
  43570. };
  43571. /**
  43572. * Add a new key and its corresponding value
  43573. * @param key the key to add
  43574. * @param value the value corresponding to the key
  43575. * @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
  43576. */
  43577. StringDictionary.prototype.add = function (key, value) {
  43578. if (this._data[key] !== undefined) {
  43579. return false;
  43580. }
  43581. this._data[key] = value;
  43582. ++this._count;
  43583. return true;
  43584. };
  43585. StringDictionary.prototype.set = function (key, value) {
  43586. if (this._data[key] === undefined) {
  43587. return false;
  43588. }
  43589. this._data[key] = value;
  43590. return true;
  43591. };
  43592. /**
  43593. * Get the element of the given key and remove it from the dictionary
  43594. * @param key
  43595. */
  43596. StringDictionary.prototype.getAndRemove = function (key) {
  43597. var val = this.get(key);
  43598. if (val !== undefined) {
  43599. delete this._data[key];
  43600. --this._count;
  43601. return val;
  43602. }
  43603. return null;
  43604. };
  43605. /**
  43606. * Remove a key/value from the dictionary.
  43607. * @param key the key to remove
  43608. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  43609. */
  43610. StringDictionary.prototype.remove = function (key) {
  43611. if (this.contains(key)) {
  43612. delete this._data[key];
  43613. --this._count;
  43614. return true;
  43615. }
  43616. return false;
  43617. };
  43618. /**
  43619. * Clear the whole content of the dictionary
  43620. */
  43621. StringDictionary.prototype.clear = function () {
  43622. this._data = {};
  43623. this._count = 0;
  43624. };
  43625. Object.defineProperty(StringDictionary.prototype, "count", {
  43626. get: function () {
  43627. return this._count;
  43628. },
  43629. enumerable: true,
  43630. configurable: true
  43631. });
  43632. /**
  43633. * Execute a callback on each key/val of the dictionary.
  43634. * Note that you can remove any element in this dictionary in the callback implementation
  43635. * @param callback the callback to execute on a given key/value pair
  43636. */
  43637. StringDictionary.prototype.forEach = function (callback) {
  43638. for (var cur in this._data) {
  43639. var val = this._data[cur];
  43640. callback(cur, val);
  43641. }
  43642. };
  43643. /**
  43644. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  43645. * If the callback returns null or undefined the method will iterate to the next key/value pair
  43646. * Note that you can remove any element in this dictionary in the callback implementation
  43647. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  43648. */
  43649. StringDictionary.prototype.first = function (callback) {
  43650. for (var cur in this._data) {
  43651. var val = this._data[cur];
  43652. var res = callback(cur, val);
  43653. if (res) {
  43654. return res;
  43655. }
  43656. }
  43657. return null;
  43658. };
  43659. return StringDictionary;
  43660. }());
  43661. BABYLON.StringDictionary = StringDictionary;
  43662. })(BABYLON || (BABYLON = {}));
  43663. //# sourceMappingURL=babylon.stringDictionary.js.map
  43664. var BABYLON;
  43665. (function (BABYLON) {
  43666. var Tags = (function () {
  43667. function Tags() {
  43668. }
  43669. Tags.EnableFor = function (obj) {
  43670. obj._tags = obj._tags || {};
  43671. obj.hasTags = function () {
  43672. return Tags.HasTags(obj);
  43673. };
  43674. obj.addTags = function (tagsString) {
  43675. return Tags.AddTagsTo(obj, tagsString);
  43676. };
  43677. obj.removeTags = function (tagsString) {
  43678. return Tags.RemoveTagsFrom(obj, tagsString);
  43679. };
  43680. obj.matchesTagsQuery = function (tagsQuery) {
  43681. return Tags.MatchesQuery(obj, tagsQuery);
  43682. };
  43683. };
  43684. Tags.DisableFor = function (obj) {
  43685. delete obj._tags;
  43686. delete obj.hasTags;
  43687. delete obj.addTags;
  43688. delete obj.removeTags;
  43689. delete obj.matchesTagsQuery;
  43690. };
  43691. Tags.HasTags = function (obj) {
  43692. if (!obj._tags) {
  43693. return false;
  43694. }
  43695. return !BABYLON.Tools.IsEmpty(obj._tags);
  43696. };
  43697. Tags.GetTags = function (obj, asString) {
  43698. if (asString === void 0) { asString = true; }
  43699. if (!obj._tags) {
  43700. return null;
  43701. }
  43702. if (asString) {
  43703. var tagsArray = [];
  43704. for (var tag in obj._tags) {
  43705. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  43706. tagsArray.push(tag);
  43707. }
  43708. }
  43709. return tagsArray.join(" ");
  43710. }
  43711. else {
  43712. return obj._tags;
  43713. }
  43714. };
  43715. // the tags 'true' and 'false' are reserved and cannot be used as tags
  43716. // a tag cannot start with '||', '&&', and '!'
  43717. // it cannot contain whitespaces
  43718. Tags.AddTagsTo = function (obj, tagsString) {
  43719. if (!tagsString) {
  43720. return;
  43721. }
  43722. if (typeof tagsString !== "string") {
  43723. return;
  43724. }
  43725. var tags = tagsString.split(" ");
  43726. tags.forEach(function (tag, index, array) {
  43727. Tags._AddTagTo(obj, tag);
  43728. });
  43729. };
  43730. Tags._AddTagTo = function (obj, tag) {
  43731. tag = tag.trim();
  43732. if (tag === "" || tag === "true" || tag === "false") {
  43733. return;
  43734. }
  43735. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  43736. return;
  43737. }
  43738. Tags.EnableFor(obj);
  43739. obj._tags[tag] = true;
  43740. };
  43741. Tags.RemoveTagsFrom = function (obj, tagsString) {
  43742. if (!Tags.HasTags(obj)) {
  43743. return;
  43744. }
  43745. var tags = tagsString.split(" ");
  43746. for (var t in tags) {
  43747. Tags._RemoveTagFrom(obj, tags[t]);
  43748. }
  43749. };
  43750. Tags._RemoveTagFrom = function (obj, tag) {
  43751. delete obj._tags[tag];
  43752. };
  43753. Tags.MatchesQuery = function (obj, tagsQuery) {
  43754. if (tagsQuery === undefined) {
  43755. return true;
  43756. }
  43757. if (tagsQuery === "") {
  43758. return Tags.HasTags(obj);
  43759. }
  43760. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  43761. };
  43762. return Tags;
  43763. }());
  43764. BABYLON.Tags = Tags;
  43765. })(BABYLON || (BABYLON = {}));
  43766. //# sourceMappingURL=babylon.tags.js.map
  43767. var BABYLON;
  43768. (function (BABYLON) {
  43769. var Internals;
  43770. (function (Internals) {
  43771. var AndOrNotEvaluator = (function () {
  43772. function AndOrNotEvaluator() {
  43773. }
  43774. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  43775. if (!query.match(/\([^\(\)]*\)/g)) {
  43776. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  43777. }
  43778. else {
  43779. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  43780. // remove parenthesis
  43781. r = r.slice(1, r.length - 1);
  43782. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  43783. });
  43784. }
  43785. if (query === "true") {
  43786. return true;
  43787. }
  43788. if (query === "false") {
  43789. return false;
  43790. }
  43791. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  43792. };
  43793. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  43794. evaluateCallback = evaluateCallback || (function (r) {
  43795. return r === "true" ? true : false;
  43796. });
  43797. var result;
  43798. var or = parenthesisContent.split("||");
  43799. for (var i in or) {
  43800. if (or.hasOwnProperty(i)) {
  43801. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  43802. var and = ori.split("&&");
  43803. if (and.length > 1) {
  43804. for (var j = 0; j < and.length; ++j) {
  43805. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  43806. if (andj !== "true" && andj !== "false") {
  43807. if (andj[0] === "!") {
  43808. result = !evaluateCallback(andj.substring(1));
  43809. }
  43810. else {
  43811. result = evaluateCallback(andj);
  43812. }
  43813. }
  43814. else {
  43815. result = andj === "true" ? true : false;
  43816. }
  43817. if (!result) {
  43818. ori = "false";
  43819. break;
  43820. }
  43821. }
  43822. }
  43823. if (result || ori === "true") {
  43824. result = true;
  43825. break;
  43826. }
  43827. // result equals false (or undefined)
  43828. if (ori !== "true" && ori !== "false") {
  43829. if (ori[0] === "!") {
  43830. result = !evaluateCallback(ori.substring(1));
  43831. }
  43832. else {
  43833. result = evaluateCallback(ori);
  43834. }
  43835. }
  43836. else {
  43837. result = ori === "true" ? true : false;
  43838. }
  43839. }
  43840. }
  43841. // the whole parenthesis scope is replaced by 'true' or 'false'
  43842. return result ? "true" : "false";
  43843. };
  43844. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  43845. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  43846. // remove whitespaces
  43847. r = r.replace(/[\s]/g, function () { return ""; });
  43848. return r.length % 2 ? "!" : "";
  43849. });
  43850. booleanString = booleanString.trim();
  43851. if (booleanString === "!true") {
  43852. booleanString = "false";
  43853. }
  43854. else if (booleanString === "!false") {
  43855. booleanString = "true";
  43856. }
  43857. return booleanString;
  43858. };
  43859. return AndOrNotEvaluator;
  43860. }());
  43861. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  43862. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43863. })(BABYLON || (BABYLON = {}));
  43864. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  43865. var BABYLON;
  43866. (function (BABYLON) {
  43867. var Database = (function () {
  43868. function Database(urlToScene, callbackManifestChecked) {
  43869. // Handling various flavors of prefixed version of IndexedDB
  43870. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  43871. this.callbackManifestChecked = callbackManifestChecked;
  43872. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  43873. this.db = null;
  43874. this.enableSceneOffline = false;
  43875. this.enableTexturesOffline = false;
  43876. this.manifestVersionFound = 0;
  43877. this.mustUpdateRessources = false;
  43878. this.hasReachedQuota = false;
  43879. if (!Database.IDBStorageEnabled) {
  43880. this.callbackManifestChecked(true);
  43881. }
  43882. else {
  43883. this.checkManifestFile();
  43884. }
  43885. }
  43886. Database.prototype.checkManifestFile = function () {
  43887. var _this = this;
  43888. function noManifestFile() {
  43889. that.enableSceneOffline = false;
  43890. that.enableTexturesOffline = false;
  43891. that.callbackManifestChecked(false);
  43892. }
  43893. var that = this;
  43894. var timeStampUsed = false;
  43895. var manifestURL = this.currentSceneUrl + ".manifest";
  43896. var xhr = new XMLHttpRequest();
  43897. if (navigator.onLine) {
  43898. // Adding a timestamp to by-pass browsers' cache
  43899. timeStampUsed = true;
  43900. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  43901. }
  43902. xhr.open("GET", manifestURL, true);
  43903. xhr.addEventListener("load", function () {
  43904. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  43905. try {
  43906. var manifestFile = JSON.parse(xhr.response);
  43907. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  43908. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  43909. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  43910. _this.manifestVersionFound = manifestFile.version;
  43911. }
  43912. if (_this.callbackManifestChecked) {
  43913. _this.callbackManifestChecked(true);
  43914. }
  43915. }
  43916. catch (ex) {
  43917. noManifestFile();
  43918. }
  43919. }
  43920. else {
  43921. noManifestFile();
  43922. }
  43923. }, false);
  43924. xhr.addEventListener("error", function (event) {
  43925. if (timeStampUsed) {
  43926. timeStampUsed = false;
  43927. // Let's retry without the timeStamp
  43928. // It could fail when coupled with HTML5 Offline API
  43929. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  43930. xhr.open("GET", retryManifestURL, true);
  43931. xhr.send();
  43932. }
  43933. else {
  43934. noManifestFile();
  43935. }
  43936. }, false);
  43937. try {
  43938. xhr.send();
  43939. }
  43940. catch (ex) {
  43941. BABYLON.Tools.Error("Error on XHR send request.");
  43942. that.callbackManifestChecked(false);
  43943. }
  43944. };
  43945. Database.prototype.openAsync = function (successCallback, errorCallback) {
  43946. var _this = this;
  43947. function handleError() {
  43948. that.isSupported = false;
  43949. if (errorCallback)
  43950. errorCallback();
  43951. }
  43952. var that = this;
  43953. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  43954. // Your browser doesn't support IndexedDB
  43955. this.isSupported = false;
  43956. if (errorCallback)
  43957. errorCallback();
  43958. }
  43959. else {
  43960. // If the DB hasn't been opened or created yet
  43961. if (!this.db) {
  43962. this.hasReachedQuota = false;
  43963. this.isSupported = true;
  43964. var request = this.idbFactory.open("babylonjs", 1);
  43965. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  43966. request.onerror = function (event) {
  43967. handleError();
  43968. };
  43969. // executes when a version change transaction cannot complete due to other active transactions
  43970. request.onblocked = function (event) {
  43971. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  43972. handleError();
  43973. };
  43974. // DB has been opened successfully
  43975. request.onsuccess = function (event) {
  43976. _this.db = request.result;
  43977. successCallback();
  43978. };
  43979. // Initialization of the DB. Creating Scenes & Textures stores
  43980. request.onupgradeneeded = function (event) {
  43981. _this.db = (event.target).result;
  43982. try {
  43983. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  43984. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  43985. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  43986. }
  43987. catch (ex) {
  43988. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  43989. handleError();
  43990. }
  43991. };
  43992. }
  43993. else {
  43994. if (successCallback)
  43995. successCallback();
  43996. }
  43997. }
  43998. };
  43999. Database.prototype.loadImageFromDB = function (url, image) {
  44000. var _this = this;
  44001. var completeURL = Database.ReturnFullUrlLocation(url);
  44002. var saveAndLoadImage = function () {
  44003. if (!_this.hasReachedQuota && _this.db !== null) {
  44004. // the texture is not yet in the DB, let's try to save it
  44005. _this._saveImageIntoDBAsync(completeURL, image);
  44006. }
  44007. else {
  44008. image.src = url;
  44009. }
  44010. };
  44011. if (!this.mustUpdateRessources) {
  44012. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  44013. }
  44014. else {
  44015. saveAndLoadImage();
  44016. }
  44017. };
  44018. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  44019. if (this.isSupported && this.db !== null) {
  44020. var texture;
  44021. var transaction = this.db.transaction(["textures"]);
  44022. transaction.onabort = function (event) {
  44023. image.src = url;
  44024. };
  44025. transaction.oncomplete = function (event) {
  44026. var blobTextureURL;
  44027. if (texture) {
  44028. var URL = window.URL || window.webkitURL;
  44029. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  44030. image.onerror = function () {
  44031. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  44032. image.src = url;
  44033. };
  44034. image.src = blobTextureURL;
  44035. }
  44036. else {
  44037. notInDBCallback();
  44038. }
  44039. };
  44040. var getRequest = transaction.objectStore("textures").get(url);
  44041. getRequest.onsuccess = function (event) {
  44042. texture = (event.target).result;
  44043. };
  44044. getRequest.onerror = function (event) {
  44045. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  44046. image.src = url;
  44047. };
  44048. }
  44049. else {
  44050. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44051. image.src = url;
  44052. }
  44053. };
  44054. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  44055. var _this = this;
  44056. if (this.isSupported) {
  44057. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  44058. var generateBlobUrl = function () {
  44059. var blobTextureURL;
  44060. if (blob) {
  44061. var URL = window.URL || window.webkitURL;
  44062. try {
  44063. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  44064. }
  44065. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  44066. catch (ex) {
  44067. blobTextureURL = URL.createObjectURL(blob);
  44068. }
  44069. }
  44070. image.src = blobTextureURL;
  44071. };
  44072. if (Database.IsUASupportingBlobStorage) {
  44073. var xhr = new XMLHttpRequest(), blob;
  44074. xhr.open("GET", url, true);
  44075. xhr.responseType = "blob";
  44076. xhr.addEventListener("load", function () {
  44077. if (xhr.status === 200) {
  44078. // Blob as response (XHR2)
  44079. blob = xhr.response;
  44080. var transaction = _this.db.transaction(["textures"], "readwrite");
  44081. // the transaction could abort because of a QuotaExceededError error
  44082. transaction.onabort = function (event) {
  44083. try {
  44084. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  44085. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  44086. _this.hasReachedQuota = true;
  44087. }
  44088. }
  44089. catch (ex) { }
  44090. generateBlobUrl();
  44091. };
  44092. transaction.oncomplete = function (event) {
  44093. generateBlobUrl();
  44094. };
  44095. var newTexture = { textureUrl: url, data: blob };
  44096. try {
  44097. // Put the blob into the dabase
  44098. var addRequest = transaction.objectStore("textures").put(newTexture);
  44099. addRequest.onsuccess = function (event) {
  44100. };
  44101. addRequest.onerror = function (event) {
  44102. generateBlobUrl();
  44103. };
  44104. }
  44105. catch (ex) {
  44106. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  44107. if (ex.code === 25) {
  44108. Database.IsUASupportingBlobStorage = false;
  44109. }
  44110. image.src = url;
  44111. }
  44112. }
  44113. else {
  44114. image.src = url;
  44115. }
  44116. }, false);
  44117. xhr.addEventListener("error", function (event) {
  44118. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  44119. image.src = url;
  44120. }, false);
  44121. xhr.send();
  44122. }
  44123. else {
  44124. image.src = url;
  44125. }
  44126. }
  44127. else {
  44128. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44129. image.src = url;
  44130. }
  44131. };
  44132. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  44133. var _this = this;
  44134. var updateVersion = function (event) {
  44135. // the version is not yet in the DB or we need to update it
  44136. _this._saveVersionIntoDBAsync(url, versionLoaded);
  44137. };
  44138. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  44139. };
  44140. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  44141. var _this = this;
  44142. if (this.isSupported) {
  44143. var version;
  44144. try {
  44145. var transaction = this.db.transaction(["versions"]);
  44146. transaction.oncomplete = function (event) {
  44147. if (version) {
  44148. // If the version in the JSON file is > than the version in DB
  44149. if (_this.manifestVersionFound > version.data) {
  44150. _this.mustUpdateRessources = true;
  44151. updateInDBCallback();
  44152. }
  44153. else {
  44154. callback(version.data);
  44155. }
  44156. }
  44157. else {
  44158. _this.mustUpdateRessources = true;
  44159. updateInDBCallback();
  44160. }
  44161. };
  44162. transaction.onabort = function (event) {
  44163. callback(-1);
  44164. };
  44165. var getRequest = transaction.objectStore("versions").get(url);
  44166. getRequest.onsuccess = function (event) {
  44167. version = (event.target).result;
  44168. };
  44169. getRequest.onerror = function (event) {
  44170. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  44171. callback(-1);
  44172. };
  44173. }
  44174. catch (ex) {
  44175. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  44176. callback(-1);
  44177. }
  44178. }
  44179. else {
  44180. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44181. callback(-1);
  44182. }
  44183. };
  44184. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  44185. var _this = this;
  44186. if (this.isSupported && !this.hasReachedQuota) {
  44187. try {
  44188. // Open a transaction to the database
  44189. var transaction = this.db.transaction(["versions"], "readwrite");
  44190. // the transaction could abort because of a QuotaExceededError error
  44191. transaction.onabort = function (event) {
  44192. try {
  44193. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  44194. _this.hasReachedQuota = true;
  44195. }
  44196. }
  44197. catch (ex) { }
  44198. callback(-1);
  44199. };
  44200. transaction.oncomplete = function (event) {
  44201. callback(_this.manifestVersionFound);
  44202. };
  44203. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  44204. // Put the scene into the database
  44205. var addRequest = transaction.objectStore("versions").put(newVersion);
  44206. addRequest.onsuccess = function (event) {
  44207. };
  44208. addRequest.onerror = function (event) {
  44209. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  44210. };
  44211. }
  44212. catch (ex) {
  44213. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  44214. callback(-1);
  44215. }
  44216. }
  44217. else {
  44218. callback(-1);
  44219. }
  44220. };
  44221. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  44222. var _this = this;
  44223. var completeUrl = Database.ReturnFullUrlLocation(url);
  44224. var saveAndLoadFile = function (event) {
  44225. // the scene is not yet in the DB, let's try to save it
  44226. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  44227. };
  44228. this._checkVersionFromDB(completeUrl, function (version) {
  44229. if (version !== -1) {
  44230. if (!_this.mustUpdateRessources) {
  44231. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  44232. }
  44233. else {
  44234. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  44235. }
  44236. }
  44237. else {
  44238. errorCallback();
  44239. }
  44240. });
  44241. };
  44242. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  44243. if (this.isSupported) {
  44244. var targetStore;
  44245. if (url.indexOf(".babylon") !== -1) {
  44246. targetStore = "scenes";
  44247. }
  44248. else {
  44249. targetStore = "textures";
  44250. }
  44251. var file;
  44252. var transaction = this.db.transaction([targetStore]);
  44253. transaction.oncomplete = function (event) {
  44254. if (file) {
  44255. callback(file.data);
  44256. }
  44257. else {
  44258. notInDBCallback();
  44259. }
  44260. };
  44261. transaction.onabort = function (event) {
  44262. notInDBCallback();
  44263. };
  44264. var getRequest = transaction.objectStore(targetStore).get(url);
  44265. getRequest.onsuccess = function (event) {
  44266. file = (event.target).result;
  44267. };
  44268. getRequest.onerror = function (event) {
  44269. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  44270. notInDBCallback();
  44271. };
  44272. }
  44273. else {
  44274. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44275. callback();
  44276. }
  44277. };
  44278. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  44279. var _this = this;
  44280. if (this.isSupported) {
  44281. var targetStore;
  44282. if (url.indexOf(".babylon") !== -1) {
  44283. targetStore = "scenes";
  44284. }
  44285. else {
  44286. targetStore = "textures";
  44287. }
  44288. // Create XHR
  44289. var xhr = new XMLHttpRequest(), fileData;
  44290. xhr.open("GET", url, true);
  44291. if (useArrayBuffer) {
  44292. xhr.responseType = "arraybuffer";
  44293. }
  44294. xhr.onprogress = progressCallback;
  44295. xhr.addEventListener("load", function () {
  44296. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  44297. // Blob as response (XHR2)
  44298. //fileData = xhr.responseText;
  44299. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  44300. if (!_this.hasReachedQuota) {
  44301. // Open a transaction to the database
  44302. var transaction = _this.db.transaction([targetStore], "readwrite");
  44303. // the transaction could abort because of a QuotaExceededError error
  44304. transaction.onabort = function (event) {
  44305. try {
  44306. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  44307. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  44308. _this.hasReachedQuota = true;
  44309. }
  44310. }
  44311. catch (ex) { }
  44312. callback(fileData);
  44313. };
  44314. transaction.oncomplete = function (event) {
  44315. callback(fileData);
  44316. };
  44317. var newFile;
  44318. if (targetStore === "scenes") {
  44319. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  44320. }
  44321. else {
  44322. newFile = { textureUrl: url, data: fileData };
  44323. }
  44324. try {
  44325. // Put the scene into the database
  44326. var addRequest = transaction.objectStore(targetStore).put(newFile);
  44327. addRequest.onsuccess = function (event) {
  44328. };
  44329. addRequest.onerror = function (event) {
  44330. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  44331. };
  44332. }
  44333. catch (ex) {
  44334. callback(fileData);
  44335. }
  44336. }
  44337. else {
  44338. callback(fileData);
  44339. }
  44340. }
  44341. else {
  44342. callback();
  44343. }
  44344. }, false);
  44345. xhr.addEventListener("error", function (event) {
  44346. BABYLON.Tools.Error("error on XHR request.");
  44347. callback();
  44348. }, false);
  44349. xhr.send();
  44350. }
  44351. else {
  44352. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44353. callback();
  44354. }
  44355. };
  44356. return Database;
  44357. }());
  44358. Database.IsUASupportingBlobStorage = true;
  44359. Database.IDBStorageEnabled = true;
  44360. Database.parseURL = function (url) {
  44361. var a = document.createElement('a');
  44362. a.href = url;
  44363. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  44364. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  44365. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  44366. return absLocation;
  44367. };
  44368. Database.ReturnFullUrlLocation = function (url) {
  44369. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  44370. return (Database.parseURL(window.location.href) + url);
  44371. }
  44372. else {
  44373. return url;
  44374. }
  44375. };
  44376. BABYLON.Database = Database;
  44377. })(BABYLON || (BABYLON = {}));
  44378. //# sourceMappingURL=babylon.database.js.map
  44379. var BABYLON;
  44380. (function (BABYLON) {
  44381. var FresnelParameters = (function () {
  44382. function FresnelParameters() {
  44383. this._isEnabled = true;
  44384. this.leftColor = BABYLON.Color3.White();
  44385. this.rightColor = BABYLON.Color3.Black();
  44386. this.bias = 0;
  44387. this.power = 1;
  44388. }
  44389. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  44390. get: function () {
  44391. return this._isEnabled;
  44392. },
  44393. set: function (value) {
  44394. if (this._isEnabled === value) {
  44395. return;
  44396. }
  44397. this._isEnabled = value;
  44398. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44399. },
  44400. enumerable: true,
  44401. configurable: true
  44402. });
  44403. FresnelParameters.prototype.clone = function () {
  44404. var newFresnelParameters = new FresnelParameters();
  44405. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  44406. return newFresnelParameters;
  44407. };
  44408. FresnelParameters.prototype.serialize = function () {
  44409. var serializationObject = {};
  44410. serializationObject.isEnabled = this.isEnabled;
  44411. serializationObject.leftColor = this.leftColor;
  44412. serializationObject.rightColor = this.rightColor;
  44413. serializationObject.bias = this.bias;
  44414. serializationObject.power = this.power;
  44415. return serializationObject;
  44416. };
  44417. FresnelParameters.Parse = function (parsedFresnelParameters) {
  44418. var fresnelParameters = new FresnelParameters();
  44419. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  44420. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  44421. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  44422. fresnelParameters.bias = parsedFresnelParameters.bias;
  44423. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  44424. return fresnelParameters;
  44425. };
  44426. return FresnelParameters;
  44427. }());
  44428. BABYLON.FresnelParameters = FresnelParameters;
  44429. })(BABYLON || (BABYLON = {}));
  44430. //# sourceMappingURL=babylon.fresnelParameters.js.map
  44431. var BABYLON;
  44432. (function (BABYLON) {
  44433. var MultiMaterial = (function (_super) {
  44434. __extends(MultiMaterial, _super);
  44435. function MultiMaterial(name, scene) {
  44436. var _this = _super.call(this, name, scene, true) || this;
  44437. _this.subMaterials = new Array();
  44438. scene.multiMaterials.push(_this);
  44439. return _this;
  44440. }
  44441. // Properties
  44442. MultiMaterial.prototype.getSubMaterial = function (index) {
  44443. if (index < 0 || index >= this.subMaterials.length) {
  44444. return this.getScene().defaultMaterial;
  44445. }
  44446. return this.subMaterials[index];
  44447. };
  44448. // Methods
  44449. MultiMaterial.prototype.getClassName = function () {
  44450. return "MultiMaterial";
  44451. };
  44452. MultiMaterial.prototype.isReady = function (mesh) {
  44453. for (var index = 0; index < this.subMaterials.length; index++) {
  44454. var subMaterial = this.subMaterials[index];
  44455. if (subMaterial) {
  44456. if (!this.subMaterials[index].isReady(mesh)) {
  44457. return false;
  44458. }
  44459. }
  44460. }
  44461. return true;
  44462. };
  44463. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  44464. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  44465. for (var index = 0; index < this.subMaterials.length; index++) {
  44466. var subMaterial = null;
  44467. if (cloneChildren) {
  44468. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  44469. }
  44470. else {
  44471. subMaterial = this.subMaterials[index];
  44472. }
  44473. newMultiMaterial.subMaterials.push(subMaterial);
  44474. }
  44475. return newMultiMaterial;
  44476. };
  44477. MultiMaterial.prototype.serialize = function () {
  44478. var serializationObject = {};
  44479. serializationObject.name = this.name;
  44480. serializationObject.id = this.id;
  44481. serializationObject.tags = BABYLON.Tags.GetTags(this);
  44482. serializationObject.materials = [];
  44483. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  44484. var subMat = this.subMaterials[matIndex];
  44485. if (subMat) {
  44486. serializationObject.materials.push(subMat.id);
  44487. }
  44488. else {
  44489. serializationObject.materials.push(null);
  44490. }
  44491. }
  44492. return serializationObject;
  44493. };
  44494. return MultiMaterial;
  44495. }(BABYLON.Material));
  44496. BABYLON.MultiMaterial = MultiMaterial;
  44497. })(BABYLON || (BABYLON = {}));
  44498. //# sourceMappingURL=babylon.multiMaterial.js.map
  44499. var BABYLON;
  44500. (function (BABYLON) {
  44501. var FreeCameraTouchInput = (function () {
  44502. function FreeCameraTouchInput() {
  44503. this._offsetX = null;
  44504. this._offsetY = null;
  44505. this._pointerCount = 0;
  44506. this._pointerPressed = [];
  44507. this.touchAngularSensibility = 200000.0;
  44508. this.touchMoveSensibility = 250.0;
  44509. }
  44510. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  44511. var _this = this;
  44512. var previousPosition;
  44513. if (this._pointerInput === undefined) {
  44514. this._onLostFocus = function (evt) {
  44515. _this._offsetX = null;
  44516. _this._offsetY = null;
  44517. };
  44518. this._pointerInput = function (p, s) {
  44519. var evt = p.event;
  44520. if (evt.pointerType === "mouse") {
  44521. return;
  44522. }
  44523. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  44524. if (!noPreventDefault) {
  44525. evt.preventDefault();
  44526. }
  44527. _this._pointerPressed.push(evt.pointerId);
  44528. if (_this._pointerPressed.length !== 1) {
  44529. return;
  44530. }
  44531. previousPosition = {
  44532. x: evt.clientX,
  44533. y: evt.clientY
  44534. };
  44535. }
  44536. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  44537. if (!noPreventDefault) {
  44538. evt.preventDefault();
  44539. }
  44540. var index = _this._pointerPressed.indexOf(evt.pointerId);
  44541. if (index === -1) {
  44542. return;
  44543. }
  44544. _this._pointerPressed.splice(index, 1);
  44545. if (index != 0) {
  44546. return;
  44547. }
  44548. previousPosition = null;
  44549. _this._offsetX = null;
  44550. _this._offsetY = null;
  44551. }
  44552. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44553. if (!noPreventDefault) {
  44554. evt.preventDefault();
  44555. }
  44556. if (!previousPosition) {
  44557. return;
  44558. }
  44559. var index = _this._pointerPressed.indexOf(evt.pointerId);
  44560. if (index != 0) {
  44561. return;
  44562. }
  44563. _this._offsetX = evt.clientX - previousPosition.x;
  44564. _this._offsetY = -(evt.clientY - previousPosition.y);
  44565. }
  44566. };
  44567. }
  44568. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44569. element.addEventListener("blur", this._onLostFocus);
  44570. };
  44571. FreeCameraTouchInput.prototype.detachControl = function (element) {
  44572. if (this._pointerInput && element) {
  44573. this.camera.getScene().onPointerObservable.remove(this._observer);
  44574. this._observer = null;
  44575. element.removeEventListener("blur", this._onLostFocus);
  44576. this._onLostFocus = null;
  44577. this._pointerPressed = [];
  44578. this._offsetX = null;
  44579. this._offsetY = null;
  44580. this._pointerCount = 0;
  44581. }
  44582. };
  44583. FreeCameraTouchInput.prototype.checkInputs = function () {
  44584. if (this._offsetX) {
  44585. var camera = this.camera;
  44586. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  44587. if (this._pointerPressed.length > 1) {
  44588. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  44589. }
  44590. else {
  44591. var speed = camera._computeLocalCameraSpeed();
  44592. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  44593. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  44594. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  44595. }
  44596. }
  44597. };
  44598. FreeCameraTouchInput.prototype.getTypeName = function () {
  44599. return "FreeCameraTouchInput";
  44600. };
  44601. FreeCameraTouchInput.prototype.getSimpleName = function () {
  44602. return "touch";
  44603. };
  44604. return FreeCameraTouchInput;
  44605. }());
  44606. __decorate([
  44607. BABYLON.serialize()
  44608. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  44609. __decorate([
  44610. BABYLON.serialize()
  44611. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  44612. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  44613. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  44614. })(BABYLON || (BABYLON = {}));
  44615. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  44616. /// <reference path="babylon.freeCamera.ts" />
  44617. var BABYLON;
  44618. (function (BABYLON) {
  44619. // We're mainly based on the logic defined into the FreeCamera code
  44620. var TouchCamera = (function (_super) {
  44621. __extends(TouchCamera, _super);
  44622. //-- end properties for backward compatibility for inputs
  44623. function TouchCamera(name, position, scene) {
  44624. var _this = _super.call(this, name, position, scene) || this;
  44625. _this.inputs.addTouch();
  44626. _this._setupInputs();
  44627. return _this;
  44628. }
  44629. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  44630. //-- Begin properties for backward compatibility for inputs
  44631. get: function () {
  44632. var touch = this.inputs.attached["touch"];
  44633. if (touch)
  44634. return touch.touchAngularSensibility;
  44635. },
  44636. set: function (value) {
  44637. var touch = this.inputs.attached["touch"];
  44638. if (touch)
  44639. touch.touchAngularSensibility = value;
  44640. },
  44641. enumerable: true,
  44642. configurable: true
  44643. });
  44644. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  44645. get: function () {
  44646. var touch = this.inputs.attached["touch"];
  44647. if (touch)
  44648. return touch.touchMoveSensibility;
  44649. },
  44650. set: function (value) {
  44651. var touch = this.inputs.attached["touch"];
  44652. if (touch)
  44653. touch.touchMoveSensibility = value;
  44654. },
  44655. enumerable: true,
  44656. configurable: true
  44657. });
  44658. TouchCamera.prototype.getClassName = function () {
  44659. return "TouchCamera";
  44660. };
  44661. TouchCamera.prototype._setupInputs = function () {
  44662. var mouse = this.inputs.attached["mouse"];
  44663. if (mouse) {
  44664. mouse.touchEnabled = false;
  44665. }
  44666. };
  44667. return TouchCamera;
  44668. }(BABYLON.FreeCamera));
  44669. BABYLON.TouchCamera = TouchCamera;
  44670. })(BABYLON || (BABYLON = {}));
  44671. //# sourceMappingURL=babylon.touchCamera.js.map
  44672. var BABYLON;
  44673. (function (BABYLON) {
  44674. var ProceduralTexture = (function (_super) {
  44675. __extends(ProceduralTexture, _super);
  44676. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  44677. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44678. if (isCube === void 0) { isCube = false; }
  44679. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  44680. _this.isCube = isCube;
  44681. _this.isEnabled = true;
  44682. _this._currentRefreshId = -1;
  44683. _this._refreshRate = 1;
  44684. _this._vertexBuffers = {};
  44685. _this._uniforms = new Array();
  44686. _this._samplers = new Array();
  44687. _this._textures = new Array();
  44688. _this._floats = new Array();
  44689. _this._floatsArrays = {};
  44690. _this._colors3 = new Array();
  44691. _this._colors4 = new Array();
  44692. _this._vectors2 = new Array();
  44693. _this._vectors3 = new Array();
  44694. _this._matrices = new Array();
  44695. _this._fallbackTextureUsed = false;
  44696. scene._proceduralTextures.push(_this);
  44697. _this.name = name;
  44698. _this.isRenderTarget = true;
  44699. _this._size = size;
  44700. _this._generateMipMaps = generateMipMaps;
  44701. _this.setFragment(fragment);
  44702. _this._fallbackTexture = fallbackTexture;
  44703. var engine = scene.getEngine();
  44704. if (isCube) {
  44705. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  44706. _this.setFloat("face", 0);
  44707. }
  44708. else {
  44709. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  44710. }
  44711. // VBO
  44712. var vertices = [];
  44713. vertices.push(1, 1);
  44714. vertices.push(-1, 1);
  44715. vertices.push(-1, -1);
  44716. vertices.push(1, -1);
  44717. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  44718. // Indices
  44719. var indices = [];
  44720. indices.push(0);
  44721. indices.push(1);
  44722. indices.push(2);
  44723. indices.push(0);
  44724. indices.push(2);
  44725. indices.push(3);
  44726. _this._indexBuffer = engine.createIndexBuffer(indices);
  44727. return _this;
  44728. }
  44729. ProceduralTexture.prototype.reset = function () {
  44730. if (this._effect === undefined) {
  44731. return;
  44732. }
  44733. var engine = this.getScene().getEngine();
  44734. engine._releaseEffect(this._effect);
  44735. };
  44736. ProceduralTexture.prototype.isReady = function () {
  44737. var _this = this;
  44738. var engine = this.getScene().getEngine();
  44739. var shaders;
  44740. if (!this._fragment) {
  44741. return false;
  44742. }
  44743. if (this._fallbackTextureUsed) {
  44744. return true;
  44745. }
  44746. if (this._fragment.fragmentElement !== undefined) {
  44747. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  44748. }
  44749. else {
  44750. shaders = { vertex: "procedural", fragment: this._fragment };
  44751. }
  44752. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  44753. _this.releaseInternalTexture();
  44754. if (_this._fallbackTexture) {
  44755. _this._texture = _this._fallbackTexture._texture;
  44756. _this._texture.references++;
  44757. }
  44758. _this._fallbackTextureUsed = true;
  44759. });
  44760. return this._effect.isReady();
  44761. };
  44762. ProceduralTexture.prototype.resetRefreshCounter = function () {
  44763. this._currentRefreshId = -1;
  44764. };
  44765. ProceduralTexture.prototype.setFragment = function (fragment) {
  44766. this._fragment = fragment;
  44767. };
  44768. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  44769. get: function () {
  44770. return this._refreshRate;
  44771. },
  44772. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  44773. set: function (value) {
  44774. this._refreshRate = value;
  44775. this.resetRefreshCounter();
  44776. },
  44777. enumerable: true,
  44778. configurable: true
  44779. });
  44780. ProceduralTexture.prototype._shouldRender = function () {
  44781. if (!this.isEnabled || !this.isReady() || !this._texture) {
  44782. return false;
  44783. }
  44784. if (this._fallbackTextureUsed) {
  44785. return false;
  44786. }
  44787. if (this._currentRefreshId === -1) {
  44788. this._currentRefreshId = 1;
  44789. return true;
  44790. }
  44791. if (this.refreshRate === this._currentRefreshId) {
  44792. this._currentRefreshId = 1;
  44793. return true;
  44794. }
  44795. this._currentRefreshId++;
  44796. return false;
  44797. };
  44798. ProceduralTexture.prototype.getRenderSize = function () {
  44799. return this._size;
  44800. };
  44801. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  44802. if (this._fallbackTextureUsed) {
  44803. return;
  44804. }
  44805. this.releaseInternalTexture();
  44806. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  44807. };
  44808. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  44809. if (this._uniforms.indexOf(uniformName) === -1) {
  44810. this._uniforms.push(uniformName);
  44811. }
  44812. };
  44813. ProceduralTexture.prototype.setTexture = function (name, texture) {
  44814. if (this._samplers.indexOf(name) === -1) {
  44815. this._samplers.push(name);
  44816. }
  44817. this._textures[name] = texture;
  44818. return this;
  44819. };
  44820. ProceduralTexture.prototype.setFloat = function (name, value) {
  44821. this._checkUniform(name);
  44822. this._floats[name] = value;
  44823. return this;
  44824. };
  44825. ProceduralTexture.prototype.setFloats = function (name, value) {
  44826. this._checkUniform(name);
  44827. this._floatsArrays[name] = value;
  44828. return this;
  44829. };
  44830. ProceduralTexture.prototype.setColor3 = function (name, value) {
  44831. this._checkUniform(name);
  44832. this._colors3[name] = value;
  44833. return this;
  44834. };
  44835. ProceduralTexture.prototype.setColor4 = function (name, value) {
  44836. this._checkUniform(name);
  44837. this._colors4[name] = value;
  44838. return this;
  44839. };
  44840. ProceduralTexture.prototype.setVector2 = function (name, value) {
  44841. this._checkUniform(name);
  44842. this._vectors2[name] = value;
  44843. return this;
  44844. };
  44845. ProceduralTexture.prototype.setVector3 = function (name, value) {
  44846. this._checkUniform(name);
  44847. this._vectors3[name] = value;
  44848. return this;
  44849. };
  44850. ProceduralTexture.prototype.setMatrix = function (name, value) {
  44851. this._checkUniform(name);
  44852. this._matrices[name] = value;
  44853. return this;
  44854. };
  44855. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  44856. var scene = this.getScene();
  44857. var engine = scene.getEngine();
  44858. // Render
  44859. engine.enableEffect(this._effect);
  44860. engine.setState(false);
  44861. // Texture
  44862. for (var name in this._textures) {
  44863. this._effect.setTexture(name, this._textures[name]);
  44864. }
  44865. // Float
  44866. for (name in this._floats) {
  44867. this._effect.setFloat(name, this._floats[name]);
  44868. }
  44869. // Floats
  44870. for (name in this._floatsArrays) {
  44871. this._effect.setArray(name, this._floatsArrays[name]);
  44872. }
  44873. // Color3
  44874. for (name in this._colors3) {
  44875. this._effect.setColor3(name, this._colors3[name]);
  44876. }
  44877. // Color4
  44878. for (name in this._colors4) {
  44879. var color = this._colors4[name];
  44880. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  44881. }
  44882. // Vector2
  44883. for (name in this._vectors2) {
  44884. this._effect.setVector2(name, this._vectors2[name]);
  44885. }
  44886. // Vector3
  44887. for (name in this._vectors3) {
  44888. this._effect.setVector3(name, this._vectors3[name]);
  44889. }
  44890. // Matrix
  44891. for (name in this._matrices) {
  44892. this._effect.setMatrix(name, this._matrices[name]);
  44893. }
  44894. if (this.isCube) {
  44895. for (var face = 0; face < 6; face++) {
  44896. engine.bindFramebuffer(this._texture, face);
  44897. // VBOs
  44898. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  44899. this._effect.setFloat("face", face);
  44900. // Clear
  44901. engine.clear(scene.clearColor, true, true, true);
  44902. // Draw order
  44903. engine.draw(true, 0, 6);
  44904. // Mipmaps
  44905. if (face === 5) {
  44906. engine.generateMipMapsForCubemap(this._texture);
  44907. }
  44908. }
  44909. }
  44910. else {
  44911. engine.bindFramebuffer(this._texture);
  44912. // VBOs
  44913. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  44914. // Clear
  44915. engine.clear(scene.clearColor, true, true, true);
  44916. // Draw order
  44917. engine.draw(true, 0, 6);
  44918. }
  44919. // Unbind
  44920. engine.unBindFramebuffer(this._texture, this.isCube);
  44921. if (this.onGenerated) {
  44922. this.onGenerated();
  44923. }
  44924. };
  44925. ProceduralTexture.prototype.clone = function () {
  44926. var textureSize = this.getSize();
  44927. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  44928. // Base texture
  44929. newTexture.hasAlpha = this.hasAlpha;
  44930. newTexture.level = this.level;
  44931. // RenderTarget Texture
  44932. newTexture.coordinatesMode = this.coordinatesMode;
  44933. return newTexture;
  44934. };
  44935. ProceduralTexture.prototype.dispose = function () {
  44936. var index = this.getScene()._proceduralTextures.indexOf(this);
  44937. if (index >= 0) {
  44938. this.getScene()._proceduralTextures.splice(index, 1);
  44939. }
  44940. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  44941. if (vertexBuffer) {
  44942. vertexBuffer.dispose();
  44943. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  44944. }
  44945. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  44946. this._indexBuffer = null;
  44947. }
  44948. _super.prototype.dispose.call(this);
  44949. };
  44950. return ProceduralTexture;
  44951. }(BABYLON.Texture));
  44952. BABYLON.ProceduralTexture = ProceduralTexture;
  44953. })(BABYLON || (BABYLON = {}));
  44954. //# sourceMappingURL=babylon.proceduralTexture.js.map
  44955. /// <reference path="babylon.proceduralTexture.ts" />
  44956. var BABYLON;
  44957. (function (BABYLON) {
  44958. var CustomProceduralTexture = (function (_super) {
  44959. __extends(CustomProceduralTexture, _super);
  44960. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  44961. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  44962. _this._animate = true;
  44963. _this._time = 0;
  44964. _this._texturePath = texturePath;
  44965. //Try to load json
  44966. _this.loadJson(texturePath);
  44967. _this.refreshRate = 1;
  44968. return _this;
  44969. }
  44970. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  44971. var _this = this;
  44972. var that = this;
  44973. function noConfigFile() {
  44974. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  44975. try {
  44976. that.setFragment(that._texturePath);
  44977. }
  44978. catch (ex) {
  44979. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  44980. }
  44981. }
  44982. var configFileUrl = jsonUrl + "/config.json";
  44983. var xhr = new XMLHttpRequest();
  44984. xhr.open("GET", configFileUrl, true);
  44985. xhr.addEventListener("load", function () {
  44986. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  44987. try {
  44988. _this._config = JSON.parse(xhr.response);
  44989. _this.updateShaderUniforms();
  44990. _this.updateTextures();
  44991. _this.setFragment(_this._texturePath + "/custom");
  44992. _this._animate = _this._config.animate;
  44993. _this.refreshRate = _this._config.refreshrate;
  44994. }
  44995. catch (ex) {
  44996. noConfigFile();
  44997. }
  44998. }
  44999. else {
  45000. noConfigFile();
  45001. }
  45002. }, false);
  45003. xhr.addEventListener("error", function () {
  45004. noConfigFile();
  45005. }, false);
  45006. try {
  45007. xhr.send();
  45008. }
  45009. catch (ex) {
  45010. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  45011. }
  45012. };
  45013. CustomProceduralTexture.prototype.isReady = function () {
  45014. if (!_super.prototype.isReady.call(this)) {
  45015. return false;
  45016. }
  45017. for (var name in this._textures) {
  45018. var texture = this._textures[name];
  45019. if (!texture.isReady()) {
  45020. return false;
  45021. }
  45022. }
  45023. return true;
  45024. };
  45025. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  45026. if (this._animate) {
  45027. this._time += this.getScene().getAnimationRatio() * 0.03;
  45028. this.updateShaderUniforms();
  45029. }
  45030. _super.prototype.render.call(this, useCameraPostProcess);
  45031. };
  45032. CustomProceduralTexture.prototype.updateTextures = function () {
  45033. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  45034. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  45035. }
  45036. };
  45037. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  45038. if (this._config) {
  45039. for (var j = 0; j < this._config.uniforms.length; j++) {
  45040. var uniform = this._config.uniforms[j];
  45041. switch (uniform.type) {
  45042. case "float":
  45043. this.setFloat(uniform.name, uniform.value);
  45044. break;
  45045. case "color3":
  45046. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  45047. break;
  45048. case "color4":
  45049. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  45050. break;
  45051. case "vector2":
  45052. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  45053. break;
  45054. case "vector3":
  45055. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  45056. break;
  45057. }
  45058. }
  45059. }
  45060. this.setFloat("time", this._time);
  45061. };
  45062. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  45063. get: function () {
  45064. return this._animate;
  45065. },
  45066. set: function (value) {
  45067. this._animate = value;
  45068. },
  45069. enumerable: true,
  45070. configurable: true
  45071. });
  45072. return CustomProceduralTexture;
  45073. }(BABYLON.ProceduralTexture));
  45074. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  45075. })(BABYLON || (BABYLON = {}));
  45076. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  45077. var BABYLON;
  45078. (function (BABYLON) {
  45079. var FreeCameraGamepadInput = (function () {
  45080. function FreeCameraGamepadInput() {
  45081. this.gamepadAngularSensibility = 200;
  45082. this.gamepadMoveSensibility = 40;
  45083. // private members
  45084. this._cameraTransform = BABYLON.Matrix.Identity();
  45085. this._deltaTransform = BABYLON.Vector3.Zero();
  45086. this._vector3 = BABYLON.Vector3.Zero();
  45087. this._vector2 = BABYLON.Vector2.Zero();
  45088. }
  45089. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  45090. var _this = this;
  45091. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  45092. };
  45093. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  45094. if (this._gamepads) {
  45095. this._gamepads.dispose();
  45096. }
  45097. this.gamepad = null;
  45098. };
  45099. FreeCameraGamepadInput.prototype.checkInputs = function () {
  45100. if (this.gamepad && this.gamepad.leftStick) {
  45101. var camera = this.camera;
  45102. var LSValues = this.gamepad.leftStick;
  45103. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  45104. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  45105. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  45106. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  45107. var RSValues = this.gamepad.rightStick;
  45108. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  45109. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  45110. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  45111. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  45112. if (!camera.rotationQuaternion) {
  45113. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  45114. }
  45115. else {
  45116. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  45117. }
  45118. var speed = camera._computeLocalCameraSpeed() * 50.0;
  45119. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  45120. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  45121. camera.cameraDirection.addInPlace(this._deltaTransform);
  45122. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  45123. camera.cameraRotation.addInPlace(this._vector2);
  45124. }
  45125. };
  45126. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  45127. // Only the first gamepad found can control the camera
  45128. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  45129. // prioritize XBOX gamepads.
  45130. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  45131. this.gamepad = gamepad;
  45132. }
  45133. }
  45134. };
  45135. FreeCameraGamepadInput.prototype.getTypeName = function () {
  45136. return "FreeCameraGamepadInput";
  45137. };
  45138. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  45139. return "gamepad";
  45140. };
  45141. return FreeCameraGamepadInput;
  45142. }());
  45143. __decorate([
  45144. BABYLON.serialize()
  45145. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  45146. __decorate([
  45147. BABYLON.serialize()
  45148. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  45149. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  45150. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  45151. })(BABYLON || (BABYLON = {}));
  45152. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  45153. var BABYLON;
  45154. (function (BABYLON) {
  45155. var ArcRotateCameraGamepadInput = (function () {
  45156. function ArcRotateCameraGamepadInput() {
  45157. this.gamepadRotationSensibility = 80;
  45158. this.gamepadMoveSensibility = 40;
  45159. }
  45160. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  45161. var _this = this;
  45162. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  45163. };
  45164. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  45165. if (this._gamepads) {
  45166. this._gamepads.dispose();
  45167. }
  45168. this.gamepad = null;
  45169. };
  45170. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  45171. if (this.gamepad) {
  45172. var camera = this.camera;
  45173. var RSValues = this.gamepad.rightStick;
  45174. if (RSValues.x != 0) {
  45175. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  45176. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  45177. camera.inertialAlphaOffset += normalizedRX;
  45178. }
  45179. }
  45180. if (RSValues.y != 0) {
  45181. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  45182. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  45183. camera.inertialBetaOffset += normalizedRY;
  45184. }
  45185. }
  45186. var LSValues = this.gamepad.leftStick;
  45187. if (LSValues.y != 0) {
  45188. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  45189. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  45190. this.camera.inertialRadiusOffset -= normalizedLY;
  45191. }
  45192. }
  45193. }
  45194. };
  45195. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  45196. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  45197. // prioritize XBOX gamepads.
  45198. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  45199. this.gamepad = gamepad;
  45200. }
  45201. }
  45202. };
  45203. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  45204. return "ArcRotateCameraGamepadInput";
  45205. };
  45206. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  45207. return "gamepad";
  45208. };
  45209. return ArcRotateCameraGamepadInput;
  45210. }());
  45211. __decorate([
  45212. BABYLON.serialize()
  45213. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  45214. __decorate([
  45215. BABYLON.serialize()
  45216. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  45217. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  45218. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  45219. })(BABYLON || (BABYLON = {}));
  45220. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  45221. var BABYLON;
  45222. (function (BABYLON) {
  45223. var Gamepads = (function () {
  45224. function Gamepads(ongamedpadconnected) {
  45225. var _this = this;
  45226. this.babylonGamepads = [];
  45227. this.oneGamepadConnected = false;
  45228. this.isMonitoring = false;
  45229. this.gamepadEventSupported = 'GamepadEvent' in window;
  45230. this.gamepadSupport = (navigator.getGamepads ||
  45231. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  45232. this._callbackGamepadConnected = ongamedpadconnected;
  45233. if (this.gamepadSupport) {
  45234. //first add already-connected gamepads
  45235. this._updateGamepadObjects();
  45236. if (this.babylonGamepads.length) {
  45237. this._startMonitoringGamepads();
  45238. }
  45239. // Checking if the gamepad connected event is supported (like in Firefox)
  45240. if (this.gamepadEventSupported) {
  45241. this._onGamepadConnectedEvent = function (evt) {
  45242. _this._onGamepadConnected(evt.gamepad);
  45243. };
  45244. this._onGamepadDisonnectedEvent = function (evt) {
  45245. _this._onGamepadDisconnected(evt);
  45246. };
  45247. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45248. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45249. }
  45250. else {
  45251. this._startMonitoringGamepads();
  45252. }
  45253. }
  45254. }
  45255. Gamepads.prototype.dispose = function () {
  45256. if (Gamepads.gamepadDOMInfo) {
  45257. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45258. }
  45259. if (this._onGamepadConnectedEvent) {
  45260. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45261. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45262. this._onGamepadConnectedEvent = null;
  45263. this._onGamepadDisonnectedEvent = null;
  45264. }
  45265. };
  45266. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  45267. var newGamepad = this._addNewGamepad(gamepad);
  45268. if (this._callbackGamepadConnected)
  45269. this._callbackGamepadConnected(newGamepad);
  45270. this._startMonitoringGamepads();
  45271. };
  45272. Gamepads.prototype._addNewGamepad = function (gamepad) {
  45273. if (!this.oneGamepadConnected) {
  45274. this.oneGamepadConnected = true;
  45275. if (Gamepads.gamepadDOMInfo) {
  45276. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45277. Gamepads.gamepadDOMInfo = null;
  45278. }
  45279. }
  45280. var newGamepad;
  45281. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  45282. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  45283. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  45284. }
  45285. else if (gamepad.pose) {
  45286. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  45287. }
  45288. else {
  45289. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  45290. }
  45291. this.babylonGamepads.push(newGamepad);
  45292. return newGamepad;
  45293. };
  45294. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  45295. // Remove the gamepad from the list of gamepads to monitor.
  45296. for (var i in this.babylonGamepads) {
  45297. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  45298. this.babylonGamepads.splice(+i, 1);
  45299. break;
  45300. }
  45301. }
  45302. // If no gamepads are left, stop the polling loop.
  45303. if (this.babylonGamepads.length == 0) {
  45304. this._stopMonitoringGamepads();
  45305. }
  45306. };
  45307. Gamepads.prototype._startMonitoringGamepads = function () {
  45308. if (!this.isMonitoring) {
  45309. this.isMonitoring = true;
  45310. this._checkGamepadsStatus();
  45311. }
  45312. };
  45313. Gamepads.prototype._stopMonitoringGamepads = function () {
  45314. this.isMonitoring = false;
  45315. };
  45316. Gamepads.prototype._checkGamepadsStatus = function () {
  45317. var _this = this;
  45318. // updating gamepad objects
  45319. this._updateGamepadObjects();
  45320. for (var i in this.babylonGamepads) {
  45321. this.babylonGamepads[i].update();
  45322. }
  45323. if (this.isMonitoring) {
  45324. if (window.requestAnimationFrame) {
  45325. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45326. }
  45327. else if (window.mozRequestAnimationFrame) {
  45328. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45329. }
  45330. else if (window.webkitRequestAnimationFrame) {
  45331. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45332. }
  45333. }
  45334. };
  45335. // This function is called only on Chrome, which does not yet support
  45336. // connection/disconnection events, but requires you to monitor
  45337. // an array for changes.
  45338. Gamepads.prototype._updateGamepadObjects = function () {
  45339. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  45340. for (var i = 0; i < gamepads.length; i++) {
  45341. if (gamepads[i]) {
  45342. if (!(gamepads[i].index in this.babylonGamepads)) {
  45343. var newGamepad = this._addNewGamepad(gamepads[i]);
  45344. if (this._callbackGamepadConnected) {
  45345. this._callbackGamepadConnected(newGamepad);
  45346. }
  45347. }
  45348. else {
  45349. this.babylonGamepads[i].browserGamepad = gamepads[i];
  45350. }
  45351. }
  45352. }
  45353. };
  45354. return Gamepads;
  45355. }());
  45356. BABYLON.Gamepads = Gamepads;
  45357. var StickValues = (function () {
  45358. function StickValues(x, y) {
  45359. this.x = x;
  45360. this.y = y;
  45361. }
  45362. return StickValues;
  45363. }());
  45364. BABYLON.StickValues = StickValues;
  45365. var Gamepad = (function () {
  45366. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  45367. if (leftStickX === void 0) { leftStickX = 0; }
  45368. if (leftStickY === void 0) { leftStickY = 1; }
  45369. if (rightStickX === void 0) { rightStickX = 2; }
  45370. if (rightStickY === void 0) { rightStickY = 3; }
  45371. this.id = id;
  45372. this.index = index;
  45373. this.browserGamepad = browserGamepad;
  45374. this.type = Gamepad.GAMEPAD;
  45375. this._leftStickAxisX = leftStickX;
  45376. this._leftStickAxisY = leftStickY;
  45377. this._rightStickAxisX = rightStickX;
  45378. this._rightStickAxisY = rightStickY;
  45379. if (this.browserGamepad.axes.length >= 2) {
  45380. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  45381. }
  45382. if (this.browserGamepad.axes.length >= 4) {
  45383. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  45384. }
  45385. }
  45386. Gamepad.prototype.onleftstickchanged = function (callback) {
  45387. this._onleftstickchanged = callback;
  45388. };
  45389. Gamepad.prototype.onrightstickchanged = function (callback) {
  45390. this._onrightstickchanged = callback;
  45391. };
  45392. Object.defineProperty(Gamepad.prototype, "leftStick", {
  45393. get: function () {
  45394. return this._leftStick;
  45395. },
  45396. set: function (newValues) {
  45397. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  45398. this._onleftstickchanged(newValues);
  45399. }
  45400. this._leftStick = newValues;
  45401. },
  45402. enumerable: true,
  45403. configurable: true
  45404. });
  45405. Object.defineProperty(Gamepad.prototype, "rightStick", {
  45406. get: function () {
  45407. return this._rightStick;
  45408. },
  45409. set: function (newValues) {
  45410. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  45411. this._onrightstickchanged(newValues);
  45412. }
  45413. this._rightStick = newValues;
  45414. },
  45415. enumerable: true,
  45416. configurable: true
  45417. });
  45418. Gamepad.prototype.update = function () {
  45419. if (this._leftStick) {
  45420. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  45421. }
  45422. if (this._rightStick) {
  45423. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  45424. }
  45425. };
  45426. return Gamepad;
  45427. }());
  45428. Gamepad.GAMEPAD = 0;
  45429. Gamepad.GENERIC = 1;
  45430. Gamepad.XBOX = 2;
  45431. Gamepad.POSE_ENABLED = 3;
  45432. BABYLON.Gamepad = Gamepad;
  45433. var GenericPad = (function (_super) {
  45434. __extends(GenericPad, _super);
  45435. function GenericPad(id, index, gamepad) {
  45436. var _this = _super.call(this, id, index, gamepad) || this;
  45437. _this.id = id;
  45438. _this.index = index;
  45439. _this.gamepad = gamepad;
  45440. _this.type = Gamepad.GENERIC;
  45441. _this._buttons = new Array(gamepad.buttons.length);
  45442. return _this;
  45443. }
  45444. GenericPad.prototype.onbuttondown = function (callback) {
  45445. this._onbuttondown = callback;
  45446. };
  45447. GenericPad.prototype.onbuttonup = function (callback) {
  45448. this._onbuttonup = callback;
  45449. };
  45450. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  45451. if (newValue !== currentValue) {
  45452. if (this._onbuttondown && newValue === 1) {
  45453. this._onbuttondown(buttonIndex);
  45454. }
  45455. if (this._onbuttonup && newValue === 0) {
  45456. this._onbuttonup(buttonIndex);
  45457. }
  45458. }
  45459. return newValue;
  45460. };
  45461. GenericPad.prototype.update = function () {
  45462. _super.prototype.update.call(this);
  45463. for (var index = 0; index < this._buttons.length; index++) {
  45464. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  45465. }
  45466. };
  45467. return GenericPad;
  45468. }(Gamepad));
  45469. BABYLON.GenericPad = GenericPad;
  45470. var Xbox360Button;
  45471. (function (Xbox360Button) {
  45472. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  45473. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  45474. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  45475. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  45476. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  45477. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  45478. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  45479. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  45480. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  45481. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  45482. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  45483. var Xbox360Dpad;
  45484. (function (Xbox360Dpad) {
  45485. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  45486. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  45487. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  45488. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  45489. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  45490. var Xbox360Pad = (function (_super) {
  45491. __extends(Xbox360Pad, _super);
  45492. function Xbox360Pad(id, index, gamepad, xboxOne) {
  45493. if (xboxOne === void 0) { xboxOne = false; }
  45494. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  45495. _this._leftTrigger = 0;
  45496. _this._rightTrigger = 0;
  45497. _this._buttonA = 0;
  45498. _this._buttonB = 0;
  45499. _this._buttonX = 0;
  45500. _this._buttonY = 0;
  45501. _this._buttonBack = 0;
  45502. _this._buttonStart = 0;
  45503. _this._buttonLB = 0;
  45504. _this._buttonRB = 0;
  45505. _this._buttonLeftStick = 0;
  45506. _this._buttonRightStick = 0;
  45507. _this._dPadUp = 0;
  45508. _this._dPadDown = 0;
  45509. _this._dPadLeft = 0;
  45510. _this._dPadRight = 0;
  45511. _this._isXboxOnePad = false;
  45512. _this.type = Gamepad.XBOX;
  45513. _this._isXboxOnePad = xboxOne;
  45514. return _this;
  45515. }
  45516. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  45517. this._onlefttriggerchanged = callback;
  45518. };
  45519. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  45520. this._onrighttriggerchanged = callback;
  45521. };
  45522. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  45523. get: function () {
  45524. return this._leftTrigger;
  45525. },
  45526. set: function (newValue) {
  45527. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  45528. this._onlefttriggerchanged(newValue);
  45529. }
  45530. this._leftTrigger = newValue;
  45531. },
  45532. enumerable: true,
  45533. configurable: true
  45534. });
  45535. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  45536. get: function () {
  45537. return this._rightTrigger;
  45538. },
  45539. set: function (newValue) {
  45540. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  45541. this._onrighttriggerchanged(newValue);
  45542. }
  45543. this._rightTrigger = newValue;
  45544. },
  45545. enumerable: true,
  45546. configurable: true
  45547. });
  45548. Xbox360Pad.prototype.onbuttondown = function (callback) {
  45549. this._onbuttondown = callback;
  45550. };
  45551. Xbox360Pad.prototype.onbuttonup = function (callback) {
  45552. this._onbuttonup = callback;
  45553. };
  45554. Xbox360Pad.prototype.ondpaddown = function (callback) {
  45555. this._ondpaddown = callback;
  45556. };
  45557. Xbox360Pad.prototype.ondpadup = function (callback) {
  45558. this._ondpadup = callback;
  45559. };
  45560. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  45561. if (newValue !== currentValue) {
  45562. if (this._onbuttondown && newValue === 1) {
  45563. this._onbuttondown(buttonType);
  45564. }
  45565. if (this._onbuttonup && newValue === 0) {
  45566. this._onbuttonup(buttonType);
  45567. }
  45568. }
  45569. return newValue;
  45570. };
  45571. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  45572. if (newValue !== currentValue) {
  45573. if (this._ondpaddown && newValue === 1) {
  45574. this._ondpaddown(buttonType);
  45575. }
  45576. if (this._ondpadup && newValue === 0) {
  45577. this._ondpadup(buttonType);
  45578. }
  45579. }
  45580. return newValue;
  45581. };
  45582. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  45583. get: function () {
  45584. return this._buttonA;
  45585. },
  45586. set: function (value) {
  45587. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  45588. },
  45589. enumerable: true,
  45590. configurable: true
  45591. });
  45592. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  45593. get: function () {
  45594. return this._buttonB;
  45595. },
  45596. set: function (value) {
  45597. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  45598. },
  45599. enumerable: true,
  45600. configurable: true
  45601. });
  45602. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  45603. get: function () {
  45604. return this._buttonX;
  45605. },
  45606. set: function (value) {
  45607. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  45608. },
  45609. enumerable: true,
  45610. configurable: true
  45611. });
  45612. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  45613. get: function () {
  45614. return this._buttonY;
  45615. },
  45616. set: function (value) {
  45617. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  45618. },
  45619. enumerable: true,
  45620. configurable: true
  45621. });
  45622. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  45623. get: function () {
  45624. return this._buttonStart;
  45625. },
  45626. set: function (value) {
  45627. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  45628. },
  45629. enumerable: true,
  45630. configurable: true
  45631. });
  45632. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  45633. get: function () {
  45634. return this._buttonBack;
  45635. },
  45636. set: function (value) {
  45637. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  45638. },
  45639. enumerable: true,
  45640. configurable: true
  45641. });
  45642. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  45643. get: function () {
  45644. return this._buttonLB;
  45645. },
  45646. set: function (value) {
  45647. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  45648. },
  45649. enumerable: true,
  45650. configurable: true
  45651. });
  45652. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  45653. get: function () {
  45654. return this._buttonRB;
  45655. },
  45656. set: function (value) {
  45657. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  45658. },
  45659. enumerable: true,
  45660. configurable: true
  45661. });
  45662. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  45663. get: function () {
  45664. return this._buttonLeftStick;
  45665. },
  45666. set: function (value) {
  45667. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  45668. },
  45669. enumerable: true,
  45670. configurable: true
  45671. });
  45672. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  45673. get: function () {
  45674. return this._buttonRightStick;
  45675. },
  45676. set: function (value) {
  45677. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  45678. },
  45679. enumerable: true,
  45680. configurable: true
  45681. });
  45682. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  45683. get: function () {
  45684. return this._dPadUp;
  45685. },
  45686. set: function (value) {
  45687. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  45688. },
  45689. enumerable: true,
  45690. configurable: true
  45691. });
  45692. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  45693. get: function () {
  45694. return this._dPadDown;
  45695. },
  45696. set: function (value) {
  45697. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  45698. },
  45699. enumerable: true,
  45700. configurable: true
  45701. });
  45702. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  45703. get: function () {
  45704. return this._dPadLeft;
  45705. },
  45706. set: function (value) {
  45707. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  45708. },
  45709. enumerable: true,
  45710. configurable: true
  45711. });
  45712. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  45713. get: function () {
  45714. return this._dPadRight;
  45715. },
  45716. set: function (value) {
  45717. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  45718. },
  45719. enumerable: true,
  45720. configurable: true
  45721. });
  45722. Xbox360Pad.prototype.update = function () {
  45723. _super.prototype.update.call(this);
  45724. if (this._isXboxOnePad) {
  45725. this.buttonA = this.browserGamepad.buttons[0].value;
  45726. this.buttonB = this.browserGamepad.buttons[1].value;
  45727. this.buttonX = this.browserGamepad.buttons[2].value;
  45728. this.buttonY = this.browserGamepad.buttons[3].value;
  45729. this.buttonLB = this.browserGamepad.buttons[4].value;
  45730. this.buttonRB = this.browserGamepad.buttons[5].value;
  45731. this.leftTrigger = this.browserGamepad.axes[2];
  45732. this.rightTrigger = this.browserGamepad.axes[5];
  45733. this.buttonBack = this.browserGamepad.buttons[9].value;
  45734. this.buttonStart = this.browserGamepad.buttons[8].value;
  45735. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  45736. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  45737. this.dPadUp = this.browserGamepad.buttons[11].value;
  45738. this.dPadDown = this.browserGamepad.buttons[12].value;
  45739. this.dPadLeft = this.browserGamepad.buttons[13].value;
  45740. this.dPadRight = this.browserGamepad.buttons[14].value;
  45741. }
  45742. else {
  45743. this.buttonA = this.browserGamepad.buttons[0].value;
  45744. this.buttonB = this.browserGamepad.buttons[1].value;
  45745. this.buttonX = this.browserGamepad.buttons[2].value;
  45746. this.buttonY = this.browserGamepad.buttons[3].value;
  45747. this.buttonLB = this.browserGamepad.buttons[4].value;
  45748. this.buttonRB = this.browserGamepad.buttons[5].value;
  45749. this.leftTrigger = this.browserGamepad.buttons[6].value;
  45750. this.rightTrigger = this.browserGamepad.buttons[7].value;
  45751. this.buttonBack = this.browserGamepad.buttons[8].value;
  45752. this.buttonStart = this.browserGamepad.buttons[9].value;
  45753. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  45754. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  45755. this.dPadUp = this.browserGamepad.buttons[12].value;
  45756. this.dPadDown = this.browserGamepad.buttons[13].value;
  45757. this.dPadLeft = this.browserGamepad.buttons[14].value;
  45758. this.dPadRight = this.browserGamepad.buttons[15].value;
  45759. }
  45760. };
  45761. return Xbox360Pad;
  45762. }(Gamepad));
  45763. BABYLON.Xbox360Pad = Xbox360Pad;
  45764. })(BABYLON || (BABYLON = {}));
  45765. //# sourceMappingURL=babylon.gamepads.js.map
  45766. var BABYLON;
  45767. (function (BABYLON) {
  45768. var PoseEnabledControllerType;
  45769. (function (PoseEnabledControllerType) {
  45770. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  45771. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  45772. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  45773. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  45774. var PoseEnabledControllerHelper = (function () {
  45775. function PoseEnabledControllerHelper() {
  45776. }
  45777. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  45778. // for now, only Oculus and Vive are supported
  45779. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  45780. return new OculusTouchController(vrGamepad);
  45781. }
  45782. else {
  45783. return new ViveController(vrGamepad);
  45784. }
  45785. };
  45786. return PoseEnabledControllerHelper;
  45787. }());
  45788. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  45789. var PoseEnabledController = (function (_super) {
  45790. __extends(PoseEnabledController, _super);
  45791. function PoseEnabledController(vrGamepad) {
  45792. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  45793. _this.vrGamepad = vrGamepad;
  45794. _this.deviceScaleFactor = 1;
  45795. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  45796. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  45797. _this.controllerType = PoseEnabledControllerType.GENERIC;
  45798. _this.position = BABYLON.Vector3.Zero();
  45799. _this.rotationQuaternion = new BABYLON.Quaternion();
  45800. _this.devicePosition = BABYLON.Vector3.Zero();
  45801. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  45802. _this._calculatedPosition = BABYLON.Vector3.Zero();
  45803. _this._calculatedRotation = new BABYLON.Quaternion();
  45804. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  45805. return _this;
  45806. }
  45807. PoseEnabledController.prototype.update = function () {
  45808. _super.prototype.update.call(this);
  45809. var pose = this.vrGamepad.pose;
  45810. this.updateFromDevice(pose);
  45811. if (this._mesh) {
  45812. this._mesh.position.copyFrom(this._calculatedPosition);
  45813. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  45814. }
  45815. };
  45816. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  45817. if (poseData) {
  45818. this.rawPose = poseData;
  45819. if (poseData.position) {
  45820. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  45821. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  45822. this.devicePosition.z *= -1;
  45823. }
  45824. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  45825. this._calculatedPosition.addInPlace(this.position);
  45826. }
  45827. if (poseData.orientation) {
  45828. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  45829. if (this._mesh) {
  45830. if (this._mesh.getScene().useRightHandedSystem) {
  45831. this.deviceRotationQuaternion.z *= -1;
  45832. this.deviceRotationQuaternion.w *= -1;
  45833. }
  45834. else {
  45835. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  45836. }
  45837. }
  45838. // if the camera is set, rotate to the camera's rotation
  45839. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  45840. }
  45841. }
  45842. };
  45843. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  45844. if (this._mesh) {
  45845. this._mesh.parent = undefined;
  45846. }
  45847. this._mesh = mesh;
  45848. if (this._poseControlledCamera) {
  45849. this._mesh.parent = this._poseControlledCamera;
  45850. }
  45851. if (!this._mesh.rotationQuaternion) {
  45852. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  45853. }
  45854. };
  45855. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  45856. this._poseControlledCamera = camera;
  45857. if (this._mesh) {
  45858. this._mesh.parent = this._poseControlledCamera;
  45859. }
  45860. };
  45861. PoseEnabledController.prototype.detachMesh = function () {
  45862. this._mesh = undefined;
  45863. };
  45864. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  45865. get: function () {
  45866. return this._mesh;
  45867. },
  45868. enumerable: true,
  45869. configurable: true
  45870. });
  45871. PoseEnabledController.prototype.getForwardRay = function (length) {
  45872. if (length === void 0) { length = 100; }
  45873. if (!this.mesh) {
  45874. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  45875. }
  45876. var m = this.mesh.getWorldMatrix();
  45877. var origin = m.getTranslation();
  45878. var forward = new BABYLON.Vector3(0, 0, -1);
  45879. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  45880. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  45881. return new BABYLON.Ray(origin, direction, length);
  45882. };
  45883. return PoseEnabledController;
  45884. }(BABYLON.Gamepad));
  45885. BABYLON.PoseEnabledController = PoseEnabledController;
  45886. var WebVRController = (function (_super) {
  45887. __extends(WebVRController, _super);
  45888. function WebVRController(vrGamepad) {
  45889. var _this = _super.call(this, vrGamepad) || this;
  45890. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  45891. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  45892. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  45893. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  45894. _this.onPadStateChangedObservable = new BABYLON.Observable();
  45895. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  45896. _this.pad = { x: 0, y: 0 };
  45897. // avoid GC, store state in a tmp object
  45898. _this._changes = {
  45899. pressChanged: false,
  45900. touchChanged: false,
  45901. valueChanged: false,
  45902. changed: false
  45903. };
  45904. _this._buttons = new Array(vrGamepad.buttons.length);
  45905. _this.hand = vrGamepad.hand;
  45906. return _this;
  45907. }
  45908. WebVRController.prototype.onButtonStateChange = function (callback) {
  45909. this._onButtonStateChange = callback;
  45910. };
  45911. WebVRController.prototype.update = function () {
  45912. _super.prototype.update.call(this);
  45913. for (var index = 0; index < this._buttons.length; index++) {
  45914. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  45915. }
  45916. ;
  45917. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  45918. this.pad.x = this.leftStick.x;
  45919. this.pad.y = this.leftStick.y;
  45920. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  45921. }
  45922. };
  45923. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  45924. if (!currentState) {
  45925. this._buttons[buttonIndex] = {
  45926. pressed: newState.pressed,
  45927. touched: newState.touched,
  45928. value: newState.value
  45929. };
  45930. return;
  45931. }
  45932. this._checkChanges(newState, currentState);
  45933. if (this._changes.changed) {
  45934. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  45935. this.handleButtonChange(buttonIndex, newState, this._changes);
  45936. }
  45937. this._buttons[buttonIndex].pressed = newState.pressed;
  45938. this._buttons[buttonIndex].touched = newState.touched;
  45939. // oculus triggers are never 0, thou not touched.
  45940. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  45941. };
  45942. WebVRController.prototype._checkChanges = function (newState, currentState) {
  45943. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  45944. this._changes.touchChanged = newState.touched !== currentState.touched;
  45945. this._changes.valueChanged = newState.value !== currentState.value;
  45946. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  45947. return this._changes;
  45948. };
  45949. return WebVRController;
  45950. }(PoseEnabledController));
  45951. BABYLON.WebVRController = WebVRController;
  45952. var OculusTouchController = (function (_super) {
  45953. __extends(OculusTouchController, _super);
  45954. function OculusTouchController(vrGamepad) {
  45955. var _this = _super.call(this, vrGamepad) || this;
  45956. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  45957. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  45958. _this.controllerType = PoseEnabledControllerType.OCULUS;
  45959. return _this;
  45960. }
  45961. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  45962. var _this = this;
  45963. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  45964. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  45965. /*
  45966. Parent Mesh name: oculus_touch_left
  45967. - body
  45968. - trigger
  45969. - thumbstick
  45970. - grip
  45971. - button_y
  45972. - button_x
  45973. - button_enter
  45974. */
  45975. _this._defaultModel = newMeshes[1];
  45976. if (meshLoaded) {
  45977. meshLoaded(_this._defaultModel);
  45978. }
  45979. _this.attachToMesh(_this._defaultModel);
  45980. });
  45981. };
  45982. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  45983. // helper getters for left and right hand.
  45984. get: function () {
  45985. if (this.hand === 'right') {
  45986. return this.onMainButtonStateChangedObservable;
  45987. }
  45988. else {
  45989. throw new Error('No A button on left hand');
  45990. }
  45991. },
  45992. enumerable: true,
  45993. configurable: true
  45994. });
  45995. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  45996. get: function () {
  45997. if (this.hand === 'right') {
  45998. return this.onSecondaryButtonStateChangedObservable;
  45999. }
  46000. else {
  46001. throw new Error('No B button on left hand');
  46002. }
  46003. },
  46004. enumerable: true,
  46005. configurable: true
  46006. });
  46007. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  46008. get: function () {
  46009. if (this.hand === 'left') {
  46010. return this.onMainButtonStateChangedObservable;
  46011. }
  46012. else {
  46013. throw new Error('No X button on right hand');
  46014. }
  46015. },
  46016. enumerable: true,
  46017. configurable: true
  46018. });
  46019. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  46020. get: function () {
  46021. if (this.hand === 'left') {
  46022. return this.onSecondaryButtonStateChangedObservable;
  46023. }
  46024. else {
  46025. throw new Error('No Y button on right hand');
  46026. }
  46027. },
  46028. enumerable: true,
  46029. configurable: true
  46030. });
  46031. /*
  46032. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  46033. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  46034. 2) secondary trigger (same)
  46035. 3) A (right) X (left), touch, pressed = value
  46036. 4) B / Y
  46037. 5) thumb rest
  46038. */
  46039. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  46040. var notifyObject = state; //{ state: state, changes: changes };
  46041. var triggerDirection = this.hand === 'right' ? -1 : 1;
  46042. switch (buttonIdx) {
  46043. case 0:
  46044. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  46045. return;
  46046. case 1:
  46047. if (this._defaultModel) {
  46048. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  46049. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  46050. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  46051. }
  46052. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  46053. return;
  46054. case 2:
  46055. if (this._defaultModel) {
  46056. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  46057. }
  46058. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  46059. return;
  46060. case 3:
  46061. if (this._defaultModel) {
  46062. if (notifyObject.pressed) {
  46063. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  46064. }
  46065. else {
  46066. (this._defaultModel.getChildren()[1]).position.y = 0;
  46067. }
  46068. }
  46069. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  46070. return;
  46071. case 4:
  46072. if (this._defaultModel) {
  46073. if (notifyObject.pressed) {
  46074. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  46075. }
  46076. else {
  46077. (this._defaultModel.getChildren()[2]).position.y = 0;
  46078. }
  46079. }
  46080. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  46081. return;
  46082. case 5:
  46083. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  46084. return;
  46085. }
  46086. };
  46087. return OculusTouchController;
  46088. }(WebVRController));
  46089. BABYLON.OculusTouchController = OculusTouchController;
  46090. var ViveController = (function (_super) {
  46091. __extends(ViveController, _super);
  46092. function ViveController(vrGamepad) {
  46093. var _this = _super.call(this, vrGamepad) || this;
  46094. _this.controllerType = PoseEnabledControllerType.VIVE;
  46095. return _this;
  46096. }
  46097. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  46098. var _this = this;
  46099. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  46100. /*
  46101. Parent Mesh name: ViveWand
  46102. - body
  46103. - r_gripper
  46104. - l_gripper
  46105. - menu_button
  46106. - system_button
  46107. - trackpad
  46108. - trigger
  46109. - LED
  46110. */
  46111. _this._defaultModel = newMeshes[1];
  46112. if (meshLoaded) {
  46113. meshLoaded(_this._defaultModel);
  46114. }
  46115. _this.attachToMesh(_this._defaultModel);
  46116. });
  46117. };
  46118. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  46119. get: function () {
  46120. return this.onMainButtonStateChangedObservable;
  46121. },
  46122. enumerable: true,
  46123. configurable: true
  46124. });
  46125. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  46126. get: function () {
  46127. return this.onMainButtonStateChangedObservable;
  46128. },
  46129. enumerable: true,
  46130. configurable: true
  46131. });
  46132. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  46133. get: function () {
  46134. return this.onSecondaryButtonStateChangedObservable;
  46135. },
  46136. enumerable: true,
  46137. configurable: true
  46138. });
  46139. /**
  46140. * Vive mapping:
  46141. * 0: touchpad
  46142. * 1: trigger
  46143. * 2: left AND right buttons
  46144. * 3: menu button
  46145. */
  46146. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  46147. var notifyObject = state; //{ state: state, changes: changes };
  46148. switch (buttonIdx) {
  46149. case 0:
  46150. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  46151. return;
  46152. case 1:
  46153. if (this._defaultModel) {
  46154. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  46155. }
  46156. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  46157. return;
  46158. case 2:
  46159. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  46160. return;
  46161. case 3:
  46162. if (this._defaultModel) {
  46163. if (notifyObject.pressed) {
  46164. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  46165. }
  46166. else {
  46167. (this._defaultModel.getChildren()[2]).position.y = 0;
  46168. }
  46169. }
  46170. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  46171. return;
  46172. }
  46173. };
  46174. return ViveController;
  46175. }(WebVRController));
  46176. BABYLON.ViveController = ViveController;
  46177. })(BABYLON || (BABYLON = {}));
  46178. //# sourceMappingURL=babylon.extendedGamepad.js.map
  46179. /// <reference path="babylon.targetCamera.ts" />
  46180. var BABYLON;
  46181. (function (BABYLON) {
  46182. var FollowCamera = (function (_super) {
  46183. __extends(FollowCamera, _super);
  46184. function FollowCamera(name, position, scene, lockedTarget) {
  46185. var _this = _super.call(this, name, position, scene) || this;
  46186. _this.radius = 12;
  46187. _this.rotationOffset = 0;
  46188. _this.heightOffset = 4;
  46189. _this.cameraAcceleration = 0.05;
  46190. _this.maxCameraSpeed = 20;
  46191. _this.lockedTarget = lockedTarget;
  46192. return _this;
  46193. }
  46194. FollowCamera.prototype.getRadians = function (degrees) {
  46195. return degrees * Math.PI / 180;
  46196. };
  46197. FollowCamera.prototype.follow = function (cameraTarget) {
  46198. if (!cameraTarget)
  46199. return;
  46200. var yRotation;
  46201. if (cameraTarget.rotationQuaternion) {
  46202. var rotMatrix = new BABYLON.Matrix();
  46203. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  46204. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  46205. }
  46206. else {
  46207. yRotation = cameraTarget.rotation.y;
  46208. }
  46209. var radians = this.getRadians(this.rotationOffset) + yRotation;
  46210. var targetPosition = cameraTarget.getAbsolutePosition();
  46211. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  46212. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  46213. var dx = targetX - this.position.x;
  46214. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  46215. var dz = (targetZ) - this.position.z;
  46216. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  46217. var vy = dy * this.cameraAcceleration;
  46218. var vz = dz * this.cameraAcceleration * 2;
  46219. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  46220. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  46221. }
  46222. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  46223. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  46224. }
  46225. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  46226. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  46227. }
  46228. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  46229. this.setTarget(targetPosition);
  46230. };
  46231. FollowCamera.prototype._checkInputs = function () {
  46232. _super.prototype._checkInputs.call(this);
  46233. this.follow(this.lockedTarget);
  46234. };
  46235. FollowCamera.prototype.getClassName = function () {
  46236. return "FollowCamera";
  46237. };
  46238. return FollowCamera;
  46239. }(BABYLON.TargetCamera));
  46240. __decorate([
  46241. BABYLON.serialize()
  46242. ], FollowCamera.prototype, "radius", void 0);
  46243. __decorate([
  46244. BABYLON.serialize()
  46245. ], FollowCamera.prototype, "rotationOffset", void 0);
  46246. __decorate([
  46247. BABYLON.serialize()
  46248. ], FollowCamera.prototype, "heightOffset", void 0);
  46249. __decorate([
  46250. BABYLON.serialize()
  46251. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  46252. __decorate([
  46253. BABYLON.serialize()
  46254. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  46255. __decorate([
  46256. BABYLON.serializeAsMeshReference("lockedTargetId")
  46257. ], FollowCamera.prototype, "lockedTarget", void 0);
  46258. BABYLON.FollowCamera = FollowCamera;
  46259. var ArcFollowCamera = (function (_super) {
  46260. __extends(ArcFollowCamera, _super);
  46261. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  46262. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  46263. _this.alpha = alpha;
  46264. _this.beta = beta;
  46265. _this.radius = radius;
  46266. _this.target = target;
  46267. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  46268. _this.follow();
  46269. return _this;
  46270. }
  46271. ArcFollowCamera.prototype.follow = function () {
  46272. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  46273. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  46274. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  46275. var targetPosition = this.target.getAbsolutePosition();
  46276. this.position = targetPosition.add(this._cartesianCoordinates);
  46277. this.setTarget(targetPosition);
  46278. };
  46279. ArcFollowCamera.prototype._checkInputs = function () {
  46280. _super.prototype._checkInputs.call(this);
  46281. this.follow();
  46282. };
  46283. ArcFollowCamera.prototype.getClassName = function () {
  46284. return "ArcFollowCamera";
  46285. };
  46286. return ArcFollowCamera;
  46287. }(BABYLON.TargetCamera));
  46288. BABYLON.ArcFollowCamera = ArcFollowCamera;
  46289. })(BABYLON || (BABYLON = {}));
  46290. //# sourceMappingURL=babylon.followCamera.js.map
  46291. /// <reference path="babylon.touchCamera.ts" />
  46292. var BABYLON;
  46293. (function (BABYLON) {
  46294. // We're mainly based on the logic defined into the FreeCamera code
  46295. var UniversalCamera = (function (_super) {
  46296. __extends(UniversalCamera, _super);
  46297. //-- end properties for backward compatibility for inputs
  46298. function UniversalCamera(name, position, scene) {
  46299. var _this = _super.call(this, name, position, scene) || this;
  46300. _this.inputs.addGamepad();
  46301. return _this;
  46302. }
  46303. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  46304. //-- Begin properties for backward compatibility for inputs
  46305. get: function () {
  46306. var gamepad = this.inputs.attached["gamepad"];
  46307. if (gamepad)
  46308. return gamepad.gamepadAngularSensibility;
  46309. },
  46310. set: function (value) {
  46311. var gamepad = this.inputs.attached["gamepad"];
  46312. if (gamepad)
  46313. gamepad.gamepadAngularSensibility = value;
  46314. },
  46315. enumerable: true,
  46316. configurable: true
  46317. });
  46318. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  46319. get: function () {
  46320. var gamepad = this.inputs.attached["gamepad"];
  46321. if (gamepad)
  46322. return gamepad.gamepadMoveSensibility;
  46323. },
  46324. set: function (value) {
  46325. var gamepad = this.inputs.attached["gamepad"];
  46326. if (gamepad)
  46327. gamepad.gamepadMoveSensibility = value;
  46328. },
  46329. enumerable: true,
  46330. configurable: true
  46331. });
  46332. UniversalCamera.prototype.getClassName = function () {
  46333. return "UniversalCamera";
  46334. };
  46335. return UniversalCamera;
  46336. }(BABYLON.TouchCamera));
  46337. BABYLON.UniversalCamera = UniversalCamera;
  46338. })(BABYLON || (BABYLON = {}));
  46339. //# sourceMappingURL=babylon.universalCamera.js.map
  46340. /// <reference path="babylon.universalCamera.ts" />
  46341. var BABYLON;
  46342. (function (BABYLON) {
  46343. // We're mainly based on the logic defined into the FreeCamera code
  46344. var GamepadCamera = (function (_super) {
  46345. __extends(GamepadCamera, _super);
  46346. //-- end properties for backward compatibility for inputs
  46347. function GamepadCamera(name, position, scene) {
  46348. return _super.call(this, name, position, scene) || this;
  46349. }
  46350. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  46351. //-- Begin properties for backward compatibility for inputs
  46352. get: function () {
  46353. var gamepad = this.inputs.attached["gamepad"];
  46354. if (gamepad)
  46355. return gamepad.gamepadAngularSensibility;
  46356. },
  46357. set: function (value) {
  46358. var gamepad = this.inputs.attached["gamepad"];
  46359. if (gamepad)
  46360. gamepad.gamepadAngularSensibility = value;
  46361. },
  46362. enumerable: true,
  46363. configurable: true
  46364. });
  46365. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  46366. get: function () {
  46367. var gamepad = this.inputs.attached["gamepad"];
  46368. if (gamepad)
  46369. return gamepad.gamepadMoveSensibility;
  46370. },
  46371. set: function (value) {
  46372. var gamepad = this.inputs.attached["gamepad"];
  46373. if (gamepad)
  46374. gamepad.gamepadMoveSensibility = value;
  46375. },
  46376. enumerable: true,
  46377. configurable: true
  46378. });
  46379. GamepadCamera.prototype.getClassName = function () {
  46380. return "GamepadCamera";
  46381. };
  46382. return GamepadCamera;
  46383. }(BABYLON.UniversalCamera));
  46384. BABYLON.GamepadCamera = GamepadCamera;
  46385. })(BABYLON || (BABYLON = {}));
  46386. //# sourceMappingURL=babylon.gamepadCamera.js.map
  46387. var BABYLON;
  46388. (function (BABYLON) {
  46389. var PostProcessRenderPipelineManager = (function () {
  46390. function PostProcessRenderPipelineManager() {
  46391. this._renderPipelines = {};
  46392. }
  46393. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  46394. this._renderPipelines[renderPipeline._name] = renderPipeline;
  46395. };
  46396. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  46397. var renderPipeline = this._renderPipelines[renderPipelineName];
  46398. if (!renderPipeline) {
  46399. return;
  46400. }
  46401. renderPipeline._attachCameras(cameras, unique);
  46402. };
  46403. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  46404. var renderPipeline = this._renderPipelines[renderPipelineName];
  46405. if (!renderPipeline) {
  46406. return;
  46407. }
  46408. renderPipeline._detachCameras(cameras);
  46409. };
  46410. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  46411. var renderPipeline = this._renderPipelines[renderPipelineName];
  46412. if (!renderPipeline) {
  46413. return;
  46414. }
  46415. renderPipeline._enableEffect(renderEffectName, cameras);
  46416. };
  46417. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  46418. var renderPipeline = this._renderPipelines[renderPipelineName];
  46419. if (!renderPipeline) {
  46420. return;
  46421. }
  46422. renderPipeline._disableEffect(renderEffectName, cameras);
  46423. };
  46424. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  46425. var renderPipeline = this._renderPipelines[renderPipelineName];
  46426. if (!renderPipeline) {
  46427. return;
  46428. }
  46429. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  46430. };
  46431. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  46432. var renderPipeline = this._renderPipelines[renderPipelineName];
  46433. if (!renderPipeline) {
  46434. return;
  46435. }
  46436. renderPipeline._disableDisplayOnlyPass(cameras);
  46437. };
  46438. PostProcessRenderPipelineManager.prototype.update = function () {
  46439. for (var renderPipelineName in this._renderPipelines) {
  46440. var pipeline = this._renderPipelines[renderPipelineName];
  46441. if (!pipeline.isSupported) {
  46442. pipeline.dispose();
  46443. delete this._renderPipelines[renderPipelineName];
  46444. }
  46445. else {
  46446. pipeline._update();
  46447. }
  46448. }
  46449. };
  46450. return PostProcessRenderPipelineManager;
  46451. }());
  46452. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  46453. })(BABYLON || (BABYLON = {}));
  46454. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  46455. var BABYLON;
  46456. (function (BABYLON) {
  46457. var PostProcessRenderPass = (function () {
  46458. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  46459. this._enabled = true;
  46460. this._refCount = 0;
  46461. this._name = name;
  46462. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  46463. this.setRenderList(renderList);
  46464. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  46465. this._renderTexture.onAfterRenderObservable.add(afterRender);
  46466. this._scene = scene;
  46467. this._renderList = renderList;
  46468. }
  46469. // private
  46470. PostProcessRenderPass.prototype._incRefCount = function () {
  46471. if (this._refCount === 0) {
  46472. this._scene.customRenderTargets.push(this._renderTexture);
  46473. }
  46474. return ++this._refCount;
  46475. };
  46476. PostProcessRenderPass.prototype._decRefCount = function () {
  46477. this._refCount--;
  46478. if (this._refCount <= 0) {
  46479. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  46480. }
  46481. return this._refCount;
  46482. };
  46483. PostProcessRenderPass.prototype._update = function () {
  46484. this.setRenderList(this._renderList);
  46485. };
  46486. // public
  46487. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  46488. this._renderTexture.renderList = renderList;
  46489. };
  46490. PostProcessRenderPass.prototype.getRenderTexture = function () {
  46491. return this._renderTexture;
  46492. };
  46493. return PostProcessRenderPass;
  46494. }());
  46495. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  46496. })(BABYLON || (BABYLON = {}));
  46497. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  46498. var BABYLON;
  46499. (function (BABYLON) {
  46500. var PostProcessRenderEffect = (function () {
  46501. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  46502. this._engine = engine;
  46503. this._name = name;
  46504. this._singleInstance = singleInstance || true;
  46505. this._getPostProcess = getPostProcess;
  46506. this._cameras = [];
  46507. this._indicesForCamera = [];
  46508. this._postProcesses = {};
  46509. this._renderPasses = {};
  46510. this._renderEffectAsPasses = {};
  46511. }
  46512. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  46513. get: function () {
  46514. for (var index in this._postProcesses) {
  46515. if (!this._postProcesses[index].isSupported) {
  46516. return false;
  46517. }
  46518. }
  46519. return true;
  46520. },
  46521. enumerable: true,
  46522. configurable: true
  46523. });
  46524. PostProcessRenderEffect.prototype._update = function () {
  46525. for (var renderPassName in this._renderPasses) {
  46526. this._renderPasses[renderPassName]._update();
  46527. }
  46528. };
  46529. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  46530. this._renderPasses[renderPass._name] = renderPass;
  46531. this._linkParameters();
  46532. };
  46533. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  46534. delete this._renderPasses[renderPass._name];
  46535. this._linkParameters();
  46536. };
  46537. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  46538. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  46539. this._linkParameters();
  46540. };
  46541. PostProcessRenderEffect.prototype.getPass = function (passName) {
  46542. for (var renderPassName in this._renderPasses) {
  46543. if (renderPassName === passName) {
  46544. return this._renderPasses[passName];
  46545. }
  46546. }
  46547. };
  46548. PostProcessRenderEffect.prototype.emptyPasses = function () {
  46549. this._renderPasses = {};
  46550. this._linkParameters();
  46551. };
  46552. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  46553. var cameraKey;
  46554. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46555. for (var i = 0; i < _cam.length; i++) {
  46556. var camera = _cam[i];
  46557. var cameraName = camera.name;
  46558. if (this._singleInstance) {
  46559. cameraKey = 0;
  46560. }
  46561. else {
  46562. cameraKey = cameraName;
  46563. }
  46564. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  46565. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  46566. if (!this._indicesForCamera[cameraName]) {
  46567. this._indicesForCamera[cameraName] = [];
  46568. }
  46569. this._indicesForCamera[cameraName].push(index);
  46570. if (this._cameras.indexOf(camera) === -1) {
  46571. this._cameras[cameraName] = camera;
  46572. }
  46573. for (var passName in this._renderPasses) {
  46574. this._renderPasses[passName]._incRefCount();
  46575. }
  46576. }
  46577. this._linkParameters();
  46578. };
  46579. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  46580. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46581. for (var i = 0; i < _cam.length; i++) {
  46582. var camera = _cam[i];
  46583. var cameraName = camera.name;
  46584. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  46585. var index = this._cameras.indexOf(cameraName);
  46586. this._indicesForCamera.splice(index, 1);
  46587. this._cameras.splice(index, 1);
  46588. for (var passName in this._renderPasses) {
  46589. this._renderPasses[passName]._decRefCount();
  46590. }
  46591. }
  46592. };
  46593. PostProcessRenderEffect.prototype._enable = function (cameras) {
  46594. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46595. for (var i = 0; i < _cam.length; i++) {
  46596. var camera = _cam[i];
  46597. var cameraName = camera.name;
  46598. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  46599. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  46600. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  46601. }
  46602. }
  46603. for (var passName in this._renderPasses) {
  46604. this._renderPasses[passName]._incRefCount();
  46605. }
  46606. }
  46607. };
  46608. PostProcessRenderEffect.prototype._disable = function (cameras) {
  46609. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46610. for (var i = 0; i < _cam.length; i++) {
  46611. var camera = _cam[i];
  46612. var cameraName = camera.Name;
  46613. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  46614. for (var passName in this._renderPasses) {
  46615. this._renderPasses[passName]._decRefCount();
  46616. }
  46617. }
  46618. };
  46619. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  46620. if (this._singleInstance) {
  46621. return this._postProcesses[0];
  46622. }
  46623. else {
  46624. return this._postProcesses[camera.name];
  46625. }
  46626. };
  46627. PostProcessRenderEffect.prototype._linkParameters = function () {
  46628. var _this = this;
  46629. for (var index in this._postProcesses) {
  46630. if (this.applyParameters) {
  46631. this.applyParameters(this._postProcesses[index]);
  46632. }
  46633. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  46634. _this._linkTextures(effect);
  46635. });
  46636. }
  46637. };
  46638. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  46639. for (var renderPassName in this._renderPasses) {
  46640. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  46641. }
  46642. for (var renderEffectName in this._renderEffectAsPasses) {
  46643. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  46644. }
  46645. };
  46646. return PostProcessRenderEffect;
  46647. }());
  46648. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  46649. })(BABYLON || (BABYLON = {}));
  46650. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  46651. var BABYLON;
  46652. (function (BABYLON) {
  46653. var PostProcessRenderPipeline = (function () {
  46654. function PostProcessRenderPipeline(engine, name) {
  46655. this._engine = engine;
  46656. this._name = name;
  46657. this._renderEffects = {};
  46658. this._renderEffectsForIsolatedPass = {};
  46659. this._cameras = [];
  46660. }
  46661. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  46662. get: function () {
  46663. for (var renderEffectName in this._renderEffects) {
  46664. if (!this._renderEffects[renderEffectName].isSupported) {
  46665. return false;
  46666. }
  46667. }
  46668. return true;
  46669. },
  46670. enumerable: true,
  46671. configurable: true
  46672. });
  46673. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  46674. this._renderEffects[renderEffect._name] = renderEffect;
  46675. };
  46676. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  46677. var renderEffects = this._renderEffects[renderEffectName];
  46678. if (!renderEffects) {
  46679. return;
  46680. }
  46681. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  46682. };
  46683. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  46684. var renderEffects = this._renderEffects[renderEffectName];
  46685. if (!renderEffects) {
  46686. return;
  46687. }
  46688. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  46689. };
  46690. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  46691. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46692. var indicesToDelete = [];
  46693. var i;
  46694. for (i = 0; i < _cam.length; i++) {
  46695. var camera = _cam[i];
  46696. var cameraName = camera.name;
  46697. if (this._cameras.indexOf(camera) === -1) {
  46698. this._cameras[cameraName] = camera;
  46699. }
  46700. else if (unique) {
  46701. indicesToDelete.push(i);
  46702. }
  46703. }
  46704. for (i = 0; i < indicesToDelete.length; i++) {
  46705. cameras.splice(indicesToDelete[i], 1);
  46706. }
  46707. for (var renderEffectName in this._renderEffects) {
  46708. this._renderEffects[renderEffectName]._attachCameras(_cam);
  46709. }
  46710. };
  46711. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  46712. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46713. for (var renderEffectName in this._renderEffects) {
  46714. this._renderEffects[renderEffectName]._detachCameras(_cam);
  46715. }
  46716. for (var i = 0; i < _cam.length; i++) {
  46717. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  46718. }
  46719. };
  46720. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  46721. var _this = this;
  46722. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46723. var pass = null;
  46724. var renderEffectName;
  46725. for (renderEffectName in this._renderEffects) {
  46726. pass = this._renderEffects[renderEffectName].getPass(passName);
  46727. if (pass != null) {
  46728. break;
  46729. }
  46730. }
  46731. if (pass === null) {
  46732. return;
  46733. }
  46734. for (renderEffectName in this._renderEffects) {
  46735. this._renderEffects[renderEffectName]._disable(_cam);
  46736. }
  46737. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  46738. for (var i = 0; i < _cam.length; i++) {
  46739. var camera = _cam[i];
  46740. var cameraName = camera.name;
  46741. 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); });
  46742. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  46743. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  46744. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  46745. }
  46746. };
  46747. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  46748. var _this = this;
  46749. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46750. for (var i = 0; i < _cam.length; i++) {
  46751. var camera = _cam[i];
  46752. var cameraName = camera.name;
  46753. 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); });
  46754. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  46755. }
  46756. for (var renderEffectName in this._renderEffects) {
  46757. this._renderEffects[renderEffectName]._enable(_cam);
  46758. }
  46759. };
  46760. PostProcessRenderPipeline.prototype._update = function () {
  46761. for (var renderEffectName in this._renderEffects) {
  46762. this._renderEffects[renderEffectName]._update();
  46763. }
  46764. for (var i = 0; i < this._cameras.length; i++) {
  46765. var cameraName = this._cameras[i].name;
  46766. if (this._renderEffectsForIsolatedPass[cameraName]) {
  46767. this._renderEffectsForIsolatedPass[cameraName]._update();
  46768. }
  46769. }
  46770. };
  46771. PostProcessRenderPipeline.prototype.dispose = function () {
  46772. // Must be implemented by children
  46773. };
  46774. return PostProcessRenderPipeline;
  46775. }());
  46776. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  46777. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  46778. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  46779. })(BABYLON || (BABYLON = {}));
  46780. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  46781. var BABYLON;
  46782. (function (BABYLON) {
  46783. var DepthRenderer = (function () {
  46784. function DepthRenderer(scene, type) {
  46785. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  46786. var _this = this;
  46787. this._viewMatrix = BABYLON.Matrix.Zero();
  46788. this._projectionMatrix = BABYLON.Matrix.Zero();
  46789. this._transformMatrix = BABYLON.Matrix.Zero();
  46790. this._worldViewProjection = BABYLON.Matrix.Zero();
  46791. this._scene = scene;
  46792. var engine = scene.getEngine();
  46793. // Render target
  46794. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  46795. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46796. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46797. this._depthMap.refreshRate = 1;
  46798. this._depthMap.renderParticles = false;
  46799. this._depthMap.renderList = null;
  46800. // set default depth value to 1.0 (far away)
  46801. this._depthMap.onClearObservable.add(function (engine) {
  46802. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  46803. });
  46804. // Custom render function
  46805. var renderSubMesh = function (subMesh) {
  46806. var mesh = subMesh.getRenderingMesh();
  46807. var scene = _this._scene;
  46808. var engine = scene.getEngine();
  46809. // Culling
  46810. engine.setState(subMesh.getMaterial().backFaceCulling);
  46811. // Managing instances
  46812. var batch = mesh._getInstancesRenderList(subMesh._id);
  46813. if (batch.mustReturn) {
  46814. return;
  46815. }
  46816. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  46817. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  46818. engine.enableEffect(_this._effect);
  46819. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  46820. var material = subMesh.getMaterial();
  46821. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  46822. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  46823. // Alpha test
  46824. if (material && material.needAlphaTesting()) {
  46825. var alphaTexture = material.getAlphaTestTexture();
  46826. _this._effect.setTexture("diffuseSampler", alphaTexture);
  46827. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  46828. }
  46829. // Bones
  46830. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46831. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46832. }
  46833. // Draw
  46834. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  46835. }
  46836. };
  46837. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  46838. var index;
  46839. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46840. renderSubMesh(opaqueSubMeshes.data[index]);
  46841. }
  46842. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  46843. renderSubMesh(alphaTestSubMeshes.data[index]);
  46844. }
  46845. };
  46846. }
  46847. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  46848. var material = subMesh.getMaterial();
  46849. if (material.disableDepthWrite) {
  46850. return false;
  46851. }
  46852. var defines = [];
  46853. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46854. var mesh = subMesh.getMesh();
  46855. var scene = mesh.getScene();
  46856. // Alpha test
  46857. if (material && material.needAlphaTesting()) {
  46858. defines.push("#define ALPHATEST");
  46859. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46860. attribs.push(BABYLON.VertexBuffer.UVKind);
  46861. defines.push("#define UV1");
  46862. }
  46863. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  46864. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46865. defines.push("#define UV2");
  46866. }
  46867. }
  46868. // Bones
  46869. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46870. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46871. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46872. if (mesh.numBoneInfluencers > 4) {
  46873. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46874. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46875. }
  46876. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46877. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46878. }
  46879. else {
  46880. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46881. }
  46882. // Instances
  46883. if (useInstances) {
  46884. defines.push("#define INSTANCES");
  46885. attribs.push("world0");
  46886. attribs.push("world1");
  46887. attribs.push("world2");
  46888. attribs.push("world3");
  46889. }
  46890. // Get correct effect
  46891. var join = defines.join("\n");
  46892. if (this._cachedDefines !== join) {
  46893. this._cachedDefines = join;
  46894. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  46895. }
  46896. return this._effect.isReady();
  46897. };
  46898. DepthRenderer.prototype.getDepthMap = function () {
  46899. return this._depthMap;
  46900. };
  46901. // Methods
  46902. DepthRenderer.prototype.dispose = function () {
  46903. this._depthMap.dispose();
  46904. };
  46905. return DepthRenderer;
  46906. }());
  46907. BABYLON.DepthRenderer = DepthRenderer;
  46908. })(BABYLON || (BABYLON = {}));
  46909. //# sourceMappingURL=babylon.depthRenderer.js.map
  46910. var BABYLON;
  46911. (function (BABYLON) {
  46912. var SSAORenderingPipeline = (function (_super) {
  46913. __extends(SSAORenderingPipeline, _super);
  46914. /**
  46915. * @constructor
  46916. * @param {string} name - The rendering pipeline name
  46917. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46918. * @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 }
  46919. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46920. */
  46921. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  46922. var _this = _super.call(this, scene.getEngine(), name) || this;
  46923. // Members
  46924. /**
  46925. * The PassPostProcess id in the pipeline that contains the original scene color
  46926. * @type {string}
  46927. */
  46928. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  46929. /**
  46930. * The SSAO PostProcess id in the pipeline
  46931. * @type {string}
  46932. */
  46933. _this.SSAORenderEffect = "SSAORenderEffect";
  46934. /**
  46935. * The horizontal blur PostProcess id in the pipeline
  46936. * @type {string}
  46937. */
  46938. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  46939. /**
  46940. * The vertical blur PostProcess id in the pipeline
  46941. * @type {string}
  46942. */
  46943. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  46944. /**
  46945. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  46946. * @type {string}
  46947. */
  46948. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  46949. /**
  46950. * The output strength of the SSAO post-process. Default value is 1.0.
  46951. * @type {number}
  46952. */
  46953. _this.totalStrength = 1.0;
  46954. /**
  46955. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  46956. * @type {number}
  46957. */
  46958. _this.radius = 0.0001;
  46959. /**
  46960. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  46961. * Must not be equal to fallOff and superior to fallOff.
  46962. * Default value is 0.975
  46963. * @type {number}
  46964. */
  46965. _this.area = 0.0075;
  46966. /**
  46967. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  46968. * Must not be equal to area and inferior to area.
  46969. * Default value is 0.0
  46970. * @type {number}
  46971. */
  46972. _this.fallOff = 0.000001;
  46973. /**
  46974. * The base color of the SSAO post-process
  46975. * The final result is "base + ssao" between [0, 1]
  46976. * @type {number}
  46977. */
  46978. _this.base = 0.5;
  46979. _this._firstUpdate = true;
  46980. _this._scene = scene;
  46981. // Set up assets
  46982. _this._createRandomTexture();
  46983. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  46984. var ssaoRatio = ratio.ssaoRatio || ratio;
  46985. var combineRatio = ratio.combineRatio || ratio;
  46986. _this._ratio = {
  46987. ssaoRatio: ssaoRatio,
  46988. combineRatio: combineRatio
  46989. };
  46990. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  46991. _this._createSSAOPostProcess(ssaoRatio);
  46992. _this._createBlurPostProcess(ssaoRatio);
  46993. _this._createSSAOCombinePostProcess(combineRatio);
  46994. // Set up pipeline
  46995. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  46996. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  46997. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  46998. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  46999. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  47000. // Finish
  47001. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47002. if (cameras)
  47003. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47004. return _this;
  47005. }
  47006. // Public Methods
  47007. /**
  47008. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  47009. */
  47010. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47011. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47012. for (var i = 0; i < this._scene.cameras.length; i++) {
  47013. var camera = this._scene.cameras[i];
  47014. this._originalColorPostProcess.dispose(camera);
  47015. this._ssaoPostProcess.dispose(camera);
  47016. this._blurHPostProcess.dispose(camera);
  47017. this._blurVPostProcess.dispose(camera);
  47018. this._ssaoCombinePostProcess.dispose(camera);
  47019. }
  47020. this._randomTexture.dispose();
  47021. if (disableDepthRender)
  47022. this._scene.disableDepthRenderer();
  47023. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47024. _super.prototype.dispose.call(this);
  47025. };
  47026. // Private Methods
  47027. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  47028. var _this = this;
  47029. /*
  47030. var samplerOffsets = [
  47031. -8.0, -6.0, -4.0, -2.0,
  47032. 0.0,
  47033. 2.0, 4.0, 6.0, 8.0
  47034. ];
  47035. */
  47036. var samples = 16;
  47037. var samplerOffsets = [];
  47038. for (var i = -8; i < 8; i++) {
  47039. samplerOffsets.push(i * 2);
  47040. }
  47041. 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");
  47042. this._blurHPostProcess.onApply = function (effect) {
  47043. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  47044. effect.setTexture("depthSampler", _this._depthTexture);
  47045. if (_this._firstUpdate) {
  47046. effect.setArray("samplerOffsets", samplerOffsets);
  47047. }
  47048. };
  47049. 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");
  47050. this._blurVPostProcess.onApply = function (effect) {
  47051. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  47052. effect.setTexture("depthSampler", _this._depthTexture);
  47053. if (_this._firstUpdate) {
  47054. effect.setArray("samplerOffsets", samplerOffsets);
  47055. _this._firstUpdate = false;
  47056. }
  47057. };
  47058. };
  47059. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  47060. var _this = this;
  47061. var numSamples = 16;
  47062. var sampleSphere = [
  47063. 0.5381, 0.1856, -0.4319,
  47064. 0.1379, 0.2486, 0.4430,
  47065. 0.3371, 0.5679, -0.0057,
  47066. -0.6999, -0.0451, -0.0019,
  47067. 0.0689, -0.1598, -0.8547,
  47068. 0.0560, 0.0069, -0.1843,
  47069. -0.0146, 0.1402, 0.0762,
  47070. 0.0100, -0.1924, -0.0344,
  47071. -0.3577, -0.5301, -0.4358,
  47072. -0.3169, 0.1063, 0.0158,
  47073. 0.0103, -0.5869, 0.0046,
  47074. -0.0897, -0.4940, 0.3287,
  47075. 0.7119, -0.0154, -0.0918,
  47076. -0.0533, 0.0596, -0.5411,
  47077. 0.0352, -0.0631, 0.5460,
  47078. -0.4776, 0.2847, -0.0271
  47079. ];
  47080. var samplesFactor = 1.0 / numSamples;
  47081. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  47082. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  47083. "area", "fallOff", "base", "range", "viewport"
  47084. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  47085. var viewport = new BABYLON.Vector2(0, 0);
  47086. this._ssaoPostProcess.onApply = function (effect) {
  47087. if (_this._firstUpdate) {
  47088. effect.setArray3("sampleSphere", sampleSphere);
  47089. effect.setFloat("samplesFactor", samplesFactor);
  47090. effect.setFloat("randTextureTiles", 4.0);
  47091. }
  47092. effect.setFloat("totalStrength", _this.totalStrength);
  47093. effect.setFloat("radius", _this.radius);
  47094. effect.setFloat("area", _this.area);
  47095. effect.setFloat("fallOff", _this.fallOff);
  47096. effect.setFloat("base", _this.base);
  47097. effect.setTexture("textureSampler", _this._depthTexture);
  47098. effect.setTexture("randomSampler", _this._randomTexture);
  47099. };
  47100. };
  47101. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  47102. var _this = this;
  47103. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47104. this._ssaoCombinePostProcess.onApply = function (effect) {
  47105. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  47106. };
  47107. };
  47108. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  47109. var size = 512;
  47110. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47111. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47112. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47113. var context = this._randomTexture.getContext();
  47114. var rand = function (min, max) {
  47115. return Math.random() * (max - min) + min;
  47116. };
  47117. var randVector = BABYLON.Vector3.Zero();
  47118. for (var x = 0; x < size; x++) {
  47119. for (var y = 0; y < size; y++) {
  47120. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  47121. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  47122. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  47123. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  47124. context.fillRect(x, y, 1, 1);
  47125. }
  47126. }
  47127. this._randomTexture.update(false);
  47128. };
  47129. return SSAORenderingPipeline;
  47130. }(BABYLON.PostProcessRenderPipeline));
  47131. __decorate([
  47132. BABYLON.serialize()
  47133. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  47134. __decorate([
  47135. BABYLON.serialize()
  47136. ], SSAORenderingPipeline.prototype, "radius", void 0);
  47137. __decorate([
  47138. BABYLON.serialize()
  47139. ], SSAORenderingPipeline.prototype, "area", void 0);
  47140. __decorate([
  47141. BABYLON.serialize()
  47142. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  47143. __decorate([
  47144. BABYLON.serialize()
  47145. ], SSAORenderingPipeline.prototype, "base", void 0);
  47146. __decorate([
  47147. BABYLON.serialize()
  47148. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  47149. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  47150. })(BABYLON || (BABYLON = {}));
  47151. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  47152. // BABYLON.JS Chromatic Aberration GLSL Shader
  47153. // Author: Olivier Guyot
  47154. // Separates very slightly R, G and B colors on the edges of the screen
  47155. // Inspired by Francois Tarlier & Martins Upitis
  47156. var BABYLON;
  47157. (function (BABYLON) {
  47158. var LensRenderingPipeline = (function (_super) {
  47159. __extends(LensRenderingPipeline, _super);
  47160. /**
  47161. * @constructor
  47162. *
  47163. * Effect parameters are as follow:
  47164. * {
  47165. * chromatic_aberration: number; // from 0 to x (1 for realism)
  47166. * edge_blur: number; // from 0 to x (1 for realism)
  47167. * distortion: number; // from 0 to x (1 for realism)
  47168. * grain_amount: number; // from 0 to 1
  47169. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  47170. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  47171. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  47172. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  47173. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  47174. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  47175. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  47176. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  47177. * }
  47178. * Note: if an effect parameter is unset, effect is disabled
  47179. *
  47180. * @param {string} name - The rendering pipeline name
  47181. * @param {object} parameters - An object containing all parameters (see above)
  47182. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47183. * @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)
  47184. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47185. */
  47186. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  47187. if (ratio === void 0) { ratio = 1.0; }
  47188. var _this = _super.call(this, scene.getEngine(), name) || this;
  47189. // Lens effects can be of the following:
  47190. // - chromatic aberration (slight shift of RGB colors)
  47191. // - blur on the edge of the lens
  47192. // - lens distortion
  47193. // - depth-of-field blur & highlights enhancing
  47194. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  47195. // - grain effect (noise or custom texture)
  47196. // Two additional texture samplers are needed:
  47197. // - depth map (for depth-of-field)
  47198. // - grain texture
  47199. /**
  47200. * The chromatic aberration PostProcess id in the pipeline
  47201. * @type {string}
  47202. */
  47203. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  47204. /**
  47205. * The highlights enhancing PostProcess id in the pipeline
  47206. * @type {string}
  47207. */
  47208. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  47209. /**
  47210. * The depth-of-field PostProcess id in the pipeline
  47211. * @type {string}
  47212. */
  47213. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  47214. _this._scene = scene;
  47215. // Fetch texture samplers
  47216. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47217. if (parameters.grain_texture) {
  47218. _this._grainTexture = parameters.grain_texture;
  47219. }
  47220. else {
  47221. _this._createGrainTexture();
  47222. }
  47223. // save parameters
  47224. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  47225. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  47226. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  47227. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  47228. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  47229. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  47230. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  47231. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  47232. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  47233. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  47234. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  47235. // Create effects
  47236. _this._createChromaticAberrationPostProcess(ratio);
  47237. _this._createHighlightsPostProcess(ratio);
  47238. _this._createDepthOfFieldPostProcess(ratio / 4);
  47239. // Set up pipeline
  47240. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  47241. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  47242. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  47243. if (_this._highlightsGain === -1) {
  47244. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  47245. }
  47246. // Finish
  47247. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47248. if (cameras) {
  47249. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47250. }
  47251. return _this;
  47252. }
  47253. // public methods (self explanatory)
  47254. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  47255. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  47256. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  47257. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  47258. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  47259. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  47260. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  47261. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  47262. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  47263. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  47264. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  47265. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  47266. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  47267. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  47268. };
  47269. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  47270. this._highlightsPostProcess.updateEffect();
  47271. };
  47272. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  47273. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  47274. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  47275. this._highlightsGain = amount;
  47276. };
  47277. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  47278. if (this._highlightsGain === -1) {
  47279. this._highlightsGain = 1.0;
  47280. }
  47281. this._highlightsThreshold = amount;
  47282. };
  47283. LensRenderingPipeline.prototype.disableHighlights = function () {
  47284. this._highlightsGain = -1;
  47285. };
  47286. /**
  47287. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  47288. */
  47289. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47290. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47291. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47292. this._chromaticAberrationPostProcess = undefined;
  47293. this._highlightsPostProcess = undefined;
  47294. this._depthOfFieldPostProcess = undefined;
  47295. this._grainTexture.dispose();
  47296. if (disableDepthRender)
  47297. this._scene.disableDepthRenderer();
  47298. };
  47299. // colors shifting and distortion
  47300. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  47301. var _this = this;
  47302. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  47303. [], // samplers
  47304. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47305. this._chromaticAberrationPostProcess.onApply = function (effect) {
  47306. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  47307. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47308. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47309. };
  47310. };
  47311. // highlights enhancing
  47312. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  47313. var _this = this;
  47314. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  47315. [], // samplers
  47316. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  47317. this._highlightsPostProcess.onApply = function (effect) {
  47318. effect.setFloat('gain', _this._highlightsGain);
  47319. effect.setFloat('threshold', _this._highlightsThreshold);
  47320. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  47321. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47322. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47323. };
  47324. };
  47325. // colors shifting and distortion
  47326. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  47327. var _this = this;
  47328. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  47329. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  47330. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  47331. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47332. this._depthOfFieldPostProcess.onApply = function (effect) {
  47333. effect.setTexture("depthSampler", _this._depthTexture);
  47334. effect.setTexture("grainSampler", _this._grainTexture);
  47335. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  47336. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  47337. effect.setFloat('grain_amount', _this._grainAmount);
  47338. effect.setBool('blur_noise', _this._blurNoise);
  47339. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47340. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47341. effect.setFloat('distortion', _this._distortion);
  47342. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  47343. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  47344. effect.setFloat('aperture', _this._dofAperture);
  47345. effect.setFloat('darken', _this._dofDarken);
  47346. effect.setFloat('edge_blur', _this._edgeBlur);
  47347. effect.setBool('highlights', (_this._highlightsGain !== -1));
  47348. effect.setFloat('near', _this._scene.activeCamera.minZ);
  47349. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  47350. };
  47351. };
  47352. // creates a black and white random noise texture, 512x512
  47353. LensRenderingPipeline.prototype._createGrainTexture = function () {
  47354. var size = 512;
  47355. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47356. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47357. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47358. var context = this._grainTexture.getContext();
  47359. var rand = function (min, max) {
  47360. return Math.random() * (max - min) + min;
  47361. };
  47362. var value;
  47363. for (var x = 0; x < size; x++) {
  47364. for (var y = 0; y < size; y++) {
  47365. value = Math.floor(rand(0.42, 0.58) * 255);
  47366. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  47367. context.fillRect(x, y, 1, 1);
  47368. }
  47369. }
  47370. this._grainTexture.update(false);
  47371. };
  47372. return LensRenderingPipeline;
  47373. }(BABYLON.PostProcessRenderPipeline));
  47374. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  47375. })(BABYLON || (BABYLON = {}));
  47376. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  47377. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  47378. var BABYLON;
  47379. (function (BABYLON) {
  47380. var HDRRenderingPipeline = (function (_super) {
  47381. __extends(HDRRenderingPipeline, _super);
  47382. /**
  47383. * @constructor
  47384. * @param {string} name - The rendering pipeline name
  47385. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47386. * @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)
  47387. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  47388. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47389. */
  47390. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  47391. if (originalPostProcess === void 0) { originalPostProcess = null; }
  47392. var _this = _super.call(this, scene.getEngine(), name) || this;
  47393. /**
  47394. * Public members
  47395. */
  47396. // Gaussian Blur
  47397. /**
  47398. * Gaussian blur coefficient
  47399. * @type {number}
  47400. */
  47401. _this.gaussCoeff = 0.3;
  47402. /**
  47403. * Gaussian blur mean
  47404. * @type {number}
  47405. */
  47406. _this.gaussMean = 1.0;
  47407. /**
  47408. * Gaussian blur standard deviation
  47409. * @type {number}
  47410. */
  47411. _this.gaussStandDev = 0.8;
  47412. /**
  47413. * Gaussian blur multiplier. Multiplies the blur effect
  47414. * @type {number}
  47415. */
  47416. _this.gaussMultiplier = 4.0;
  47417. // HDR
  47418. /**
  47419. * Exposure, controls the overall intensity of the pipeline
  47420. * @type {number}
  47421. */
  47422. _this.exposure = 1.0;
  47423. /**
  47424. * Minimum luminance that the post-process can output. Luminance is >= 0
  47425. * @type {number}
  47426. */
  47427. _this.minimumLuminance = 1.0;
  47428. /**
  47429. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  47430. * @type {number}
  47431. */
  47432. _this.maximumLuminance = 1e20;
  47433. /**
  47434. * Increase rate for luminance: eye adaptation speed to dark
  47435. * @type {number}
  47436. */
  47437. _this.luminanceIncreaserate = 0.5;
  47438. /**
  47439. * Decrease rate for luminance: eye adaptation speed to bright
  47440. * @type {number}
  47441. */
  47442. _this.luminanceDecreaseRate = 0.5;
  47443. // Bright pass
  47444. /**
  47445. * Minimum luminance needed to compute HDR
  47446. * @type {number}
  47447. */
  47448. _this.brightThreshold = 0.8;
  47449. _this._needUpdate = true;
  47450. _this._scene = scene;
  47451. // Bright pass
  47452. _this._createBrightPassPostProcess(scene, ratio);
  47453. // Down sample X4
  47454. _this._createDownSampleX4PostProcess(scene, ratio);
  47455. // Create gaussian blur post-processes
  47456. _this._createGaussianBlurPostProcess(scene, ratio);
  47457. // Texture adder
  47458. _this._createTextureAdderPostProcess(scene, ratio);
  47459. // Luminance generator
  47460. _this._createLuminanceGeneratorPostProcess(scene);
  47461. // HDR
  47462. _this._createHDRPostProcess(scene, ratio);
  47463. // Pass postprocess
  47464. if (originalPostProcess === null) {
  47465. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47466. }
  47467. else {
  47468. _this._originalPostProcess = originalPostProcess;
  47469. }
  47470. // Configure pipeline
  47471. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  47472. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  47473. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  47474. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  47475. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  47476. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  47477. var addDownSamplerPostProcess = function (id) {
  47478. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  47479. };
  47480. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  47481. addDownSamplerPostProcess(i);
  47482. }
  47483. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  47484. // Finish
  47485. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47486. if (cameras !== null) {
  47487. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47488. }
  47489. _this.update();
  47490. return _this;
  47491. }
  47492. /**
  47493. * Tells the pipeline to update its post-processes
  47494. */
  47495. HDRRenderingPipeline.prototype.update = function () {
  47496. this._needUpdate = true;
  47497. };
  47498. /**
  47499. * Returns the current calculated luminance
  47500. */
  47501. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  47502. return this._hdrCurrentLuminance;
  47503. };
  47504. /**
  47505. * Returns the currently drawn luminance
  47506. */
  47507. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  47508. return this._hdrOutputLuminance;
  47509. };
  47510. /**
  47511. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  47512. */
  47513. HDRRenderingPipeline.prototype.dispose = function () {
  47514. for (var i = 0; i < this._scene.cameras.length; i++) {
  47515. var camera = this._scene.cameras[i];
  47516. this._originalPostProcess.dispose(camera);
  47517. this._brightPassPostProcess.dispose(camera);
  47518. this._downSampleX4PostProcess.dispose(camera);
  47519. this._guassianBlurHPostProcess.dispose(camera);
  47520. this._guassianBlurVPostProcess.dispose(camera);
  47521. this._textureAdderPostProcess.dispose(camera);
  47522. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  47523. this._downSamplePostProcesses[j].dispose(camera);
  47524. }
  47525. this._hdrPostProcess.dispose(camera);
  47526. }
  47527. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47528. _super.prototype.dispose.call(this);
  47529. };
  47530. /**
  47531. * Creates the HDR post-process and computes the luminance adaptation
  47532. */
  47533. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  47534. var _this = this;
  47535. var hdrLastLuminance = 0.0;
  47536. this._hdrOutputLuminance = -1.0;
  47537. this._hdrCurrentLuminance = 1.0;
  47538. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  47539. this._hdrPostProcess.onApply = function (effect) {
  47540. if (_this._hdrOutputLuminance < 0.0) {
  47541. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  47542. }
  47543. else {
  47544. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  47545. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  47546. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  47547. }
  47548. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  47549. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  47550. }
  47551. else {
  47552. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  47553. }
  47554. }
  47555. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  47556. hdrLastLuminance += scene.getEngine().getDeltaTime();
  47557. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  47558. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  47559. effect.setFloat("exposure", _this.exposure);
  47560. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  47561. _this._needUpdate = false;
  47562. };
  47563. };
  47564. /**
  47565. * Texture Adder post-process
  47566. */
  47567. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  47568. var _this = this;
  47569. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  47570. this._textureAdderPostProcess.onApply = function (effect) {
  47571. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  47572. };
  47573. };
  47574. /**
  47575. * Down sample X4 post-process
  47576. */
  47577. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  47578. var _this = this;
  47579. var downSampleX4Offsets = new Array(32);
  47580. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  47581. this._downSampleX4PostProcess.onApply = function (effect) {
  47582. if (_this._needUpdate) {
  47583. var id = 0;
  47584. for (var i = -2; i < 2; i++) {
  47585. for (var j = -2; j < 2; j++) {
  47586. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  47587. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  47588. id += 2;
  47589. }
  47590. }
  47591. }
  47592. effect.setArray2("dsOffsets", downSampleX4Offsets);
  47593. };
  47594. };
  47595. /**
  47596. * Bright pass post-process
  47597. */
  47598. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  47599. var _this = this;
  47600. var brightOffsets = new Array(8);
  47601. var brightPassCallback = function (effect) {
  47602. if (_this._needUpdate) {
  47603. var sU = (1.0 / _this._brightPassPostProcess.width);
  47604. var sV = (1.0 / _this._brightPassPostProcess.height);
  47605. brightOffsets[0] = -0.5 * sU;
  47606. brightOffsets[1] = 0.5 * sV;
  47607. brightOffsets[2] = 0.5 * sU;
  47608. brightOffsets[3] = 0.5 * sV;
  47609. brightOffsets[4] = -0.5 * sU;
  47610. brightOffsets[5] = -0.5 * sV;
  47611. brightOffsets[6] = 0.5 * sU;
  47612. brightOffsets[7] = -0.5 * sV;
  47613. }
  47614. effect.setArray2("dsOffsets", brightOffsets);
  47615. effect.setFloat("brightThreshold", _this.brightThreshold);
  47616. };
  47617. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  47618. this._brightPassPostProcess.onApply = brightPassCallback;
  47619. };
  47620. /**
  47621. * Luminance generator. Creates the luminance post-process and down sample post-processes
  47622. */
  47623. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  47624. var _this = this;
  47625. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  47626. var luminanceOffsets = new Array(8);
  47627. var downSampleOffsets = new Array(18);
  47628. var halfDestPixelSize;
  47629. this._downSamplePostProcesses = new Array(lumSteps);
  47630. // Utils for luminance
  47631. var luminanceUpdateSourceOffsets = function (width, height) {
  47632. var sU = (1.0 / width);
  47633. var sV = (1.0 / height);
  47634. luminanceOffsets[0] = -0.5 * sU;
  47635. luminanceOffsets[1] = 0.5 * sV;
  47636. luminanceOffsets[2] = 0.5 * sU;
  47637. luminanceOffsets[3] = 0.5 * sV;
  47638. luminanceOffsets[4] = -0.5 * sU;
  47639. luminanceOffsets[5] = -0.5 * sV;
  47640. luminanceOffsets[6] = 0.5 * sU;
  47641. luminanceOffsets[7] = -0.5 * sV;
  47642. };
  47643. var luminanceUpdateDestOffsets = function (width, height) {
  47644. var id = 0;
  47645. for (var x = -1; x < 2; x++) {
  47646. for (var y = -1; y < 2; y++) {
  47647. downSampleOffsets[id] = (x) / width;
  47648. downSampleOffsets[id + 1] = (y) / height;
  47649. id += 2;
  47650. }
  47651. }
  47652. };
  47653. // Luminance callback
  47654. var luminanceCallback = function (effect) {
  47655. if (_this._needUpdate) {
  47656. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  47657. }
  47658. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  47659. effect.setArray2("lumOffsets", luminanceOffsets);
  47660. };
  47661. // Down sample callbacks
  47662. var downSampleCallback = function (indice) {
  47663. var i = indice;
  47664. return function (effect) {
  47665. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47666. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47667. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  47668. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  47669. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  47670. effect.setArray2("dsOffsets", downSampleOffsets);
  47671. };
  47672. };
  47673. var downSampleAfterRenderCallback = function (effect) {
  47674. // Unpack result
  47675. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  47676. 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);
  47677. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  47678. };
  47679. // Create luminance post-process
  47680. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  47681. this._downSamplePostProcesses[lumSteps - 1] = new BABYLON.PostProcess("hdr", "hdr", ["lumOffsets"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE_GENERATOR", BABYLON.Engine.TEXTURETYPE_FLOAT);
  47682. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  47683. // Create down sample post-processes
  47684. for (var i = lumSteps - 2; i >= 0; i--) {
  47685. var length = Math.pow(3, i);
  47686. ratio = { width: length, height: length };
  47687. var defines = "#define DOWN_SAMPLE\n";
  47688. if (i === 0) {
  47689. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  47690. }
  47691. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  47692. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  47693. if (i === 0) {
  47694. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  47695. }
  47696. }
  47697. };
  47698. /**
  47699. * Gaussian blur post-processes. Horizontal and Vertical
  47700. */
  47701. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  47702. var _this = this;
  47703. var blurOffsetsW = new Array(9);
  47704. var blurOffsetsH = new Array(9);
  47705. var blurWeights = new Array(9);
  47706. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  47707. // Utils for gaussian blur
  47708. var calculateBlurOffsets = function (height) {
  47709. var lastOutputDimensions = {
  47710. width: scene.getEngine().getRenderWidth(),
  47711. height: scene.getEngine().getRenderHeight()
  47712. };
  47713. for (var i = 0; i < 9; i++) {
  47714. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  47715. if (height) {
  47716. blurOffsetsH[i] = value;
  47717. }
  47718. else {
  47719. blurOffsetsW[i] = value;
  47720. }
  47721. }
  47722. };
  47723. var calculateWeights = function () {
  47724. var x = 0.0;
  47725. for (var i = 0; i < 9; i++) {
  47726. x = (i - 4.0) / 4.0;
  47727. blurWeights[i] = _this.gaussCoeff * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussStandDev)) * Math.exp((-((x - _this.gaussMean) * (x - _this.gaussMean))) / (2.0 * _this.gaussStandDev * _this.gaussStandDev));
  47728. }
  47729. };
  47730. // Callback
  47731. var gaussianBlurCallback = function (height) {
  47732. return function (effect) {
  47733. if (_this._needUpdate) {
  47734. calculateWeights();
  47735. calculateBlurOffsets(height);
  47736. }
  47737. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  47738. effect.setArray("blurWeights", blurWeights);
  47739. effect.setFloat("multiplier", _this.gaussMultiplier);
  47740. };
  47741. };
  47742. // Create horizontal gaussian blur post-processes
  47743. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  47744. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  47745. // Create vertical gaussian blur post-process
  47746. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  47747. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  47748. };
  47749. return HDRRenderingPipeline;
  47750. }(BABYLON.PostProcessRenderPipeline));
  47751. // Luminance generator
  47752. HDRRenderingPipeline.LUM_STEPS = 6;
  47753. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  47754. })(BABYLON || (BABYLON = {}));
  47755. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  47756. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  47757. var BABYLON;
  47758. (function (BABYLON) {
  47759. var StandardRenderingPipeline = (function (_super) {
  47760. __extends(StandardRenderingPipeline, _super);
  47761. /**
  47762. * @constructor
  47763. * @param {string} name - The rendering pipeline name
  47764. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47765. * @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)
  47766. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  47767. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47768. */
  47769. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  47770. if (originalPostProcess === void 0) { originalPostProcess = null; }
  47771. var _this = _super.call(this, scene.getEngine(), name) || this;
  47772. _this.downSampleX4PostProcess = null;
  47773. _this.brightPassPostProcess = null;
  47774. _this.gaussianBlurHPostProcesses = [];
  47775. _this.gaussianBlurVPostProcesses = [];
  47776. _this.textureAdderPostProcess = null;
  47777. _this.luminancePostProcess = null;
  47778. _this.luminanceDownSamplePostProcesses = [];
  47779. _this.hdrPostProcess = null;
  47780. _this.textureAdderFinalPostProcess = null;
  47781. _this.lensFlareFinalPostProcess = null;
  47782. _this.hdrFinalPostProcess = null;
  47783. _this.lensFlarePostProcess = null;
  47784. _this.lensFlareComposePostProcess = null;
  47785. _this.depthOfFieldPostProcess = null;
  47786. // Values
  47787. _this.brightThreshold = 1.0;
  47788. _this.blurWidth = 2.0;
  47789. _this.horizontalBlur = false;
  47790. _this.gaussianCoefficient = 0.25;
  47791. _this.gaussianMean = 1.0;
  47792. _this.gaussianStandardDeviation = 1.0;
  47793. _this.exposure = 1.0;
  47794. _this.lensTexture = null;
  47795. _this.hdrMinimumLuminance = 1.0;
  47796. _this.hdrDecreaseRate = 0.5;
  47797. _this.hdrIncreaseRate = 0.5;
  47798. _this.lensColorTexture = null;
  47799. _this.lensFlareStrength = 20.0;
  47800. _this.lensFlareGhostDispersal = 1.4;
  47801. _this.lensFlareHaloWidth = 0.7;
  47802. _this.lensFlareDistortionStrength = 16.0;
  47803. _this.lensStarTexture = null;
  47804. _this.lensFlareDirtTexture = null;
  47805. _this.depthOfFieldDistance = 10.0;
  47806. _this.depthOfFieldBlurWidth = 2.0;
  47807. // IAnimatable
  47808. _this.animations = [];
  47809. _this._depthRenderer = null;
  47810. _this._currentDepthOfFieldSource = null;
  47811. _this._currentHDRSource = null;
  47812. _this._hdrCurrentLuminance = 1.0;
  47813. // Getters and setters
  47814. _this._depthOfFieldEnabled = true;
  47815. _this._lensFlareEnabled = true;
  47816. _this._hdrEnabled = true;
  47817. _this._cameras = cameras || [];
  47818. // Initialize
  47819. _this._scene = scene;
  47820. // Create pass post-processe
  47821. if (!originalPostProcess) {
  47822. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  47823. }
  47824. else {
  47825. _this.originalPostProcess = originalPostProcess;
  47826. }
  47827. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  47828. // Create down sample X4 post-process
  47829. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  47830. // Create bright pass post-process
  47831. _this._createBrightPassPostProcess(scene, ratio / 2);
  47832. // Create gaussian blur post-processes (down sampling blurs)
  47833. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  47834. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  47835. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  47836. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  47837. // Create texture adder post-process
  47838. _this._createTextureAdderPostProcess(scene, ratio);
  47839. // Create depth-of-field source post-process
  47840. _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);
  47841. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  47842. // Create lens flare post-process
  47843. _this._createLensFlarePostProcess(scene, ratio);
  47844. // Create depth-of-field source post-process post lens-flare and disable it now
  47845. _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);
  47846. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  47847. // Create luminance
  47848. _this._createLuminancePostProcesses(scene);
  47849. // Create HDR
  47850. _this._createHdrPostProcess(scene, ratio);
  47851. // Create depth-of-field source post-process post lens-flare and disable it now
  47852. _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);
  47853. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  47854. // Create gaussian blur used by depth-of-field
  47855. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  47856. // Create depth-of-field post-process
  47857. _this._createDepthOfFieldPostProcess(scene, ratio);
  47858. // Finish
  47859. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47860. if (cameras !== null) {
  47861. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47862. }
  47863. // Deactivate
  47864. _this.LensFlareEnabled = false;
  47865. _this.DepthOfFieldEnabled = false;
  47866. _this.HDREnabled = false;
  47867. return _this;
  47868. }
  47869. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  47870. get: function () {
  47871. return this._depthOfFieldEnabled;
  47872. },
  47873. set: function (enabled) {
  47874. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  47875. if (enabled && !this._depthOfFieldEnabled) {
  47876. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  47877. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  47878. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  47879. this._depthRenderer = this._scene.enableDepthRenderer();
  47880. }
  47881. else if (!enabled && this._depthOfFieldEnabled) {
  47882. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  47883. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  47884. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._cameras);
  47885. }
  47886. this._depthOfFieldEnabled = enabled;
  47887. },
  47888. enumerable: true,
  47889. configurable: true
  47890. });
  47891. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  47892. get: function () {
  47893. return this._lensFlareEnabled;
  47894. },
  47895. set: function (enabled) {
  47896. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  47897. if (enabled && !this._lensFlareEnabled) {
  47898. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  47899. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  47900. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  47901. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  47902. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  47903. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  47904. }
  47905. else if (!enabled && this._lensFlareEnabled) {
  47906. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  47907. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  47908. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  47909. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  47910. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  47911. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._scene.cameras);
  47912. }
  47913. this._lensFlareEnabled = enabled;
  47914. },
  47915. enumerable: true,
  47916. configurable: true
  47917. });
  47918. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  47919. get: function () {
  47920. return this._hdrEnabled;
  47921. },
  47922. set: function (enabled) {
  47923. if (enabled && !this._hdrEnabled) {
  47924. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLuminance", this._scene.cameras);
  47925. for (var i = 0; i < this.luminanceDownSamplePostProcesses.length; i++) {
  47926. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLuminanceDownSample" + i, this._scene.cameras);
  47927. }
  47928. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDR", this._scene.cameras);
  47929. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRPostHDReDepthOfFieldSource", this._scene.cameras);
  47930. }
  47931. else if (!enabled && this._hdrEnabled) {
  47932. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLuminance", this._scene.cameras);
  47933. for (var i = 0; i < this.luminanceDownSamplePostProcesses.length; i++) {
  47934. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLuminanceDownSample" + i, this._scene.cameras);
  47935. }
  47936. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDR", this._scene.cameras);
  47937. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostHDReDepthOfFieldSource", this._scene.cameras);
  47938. }
  47939. this._hdrEnabled = enabled;
  47940. },
  47941. enumerable: true,
  47942. configurable: true
  47943. });
  47944. // Down Sample X4 Post-Processs
  47945. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  47946. var _this = this;
  47947. var downSampleX4Offsets = new Array(32);
  47948. 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);
  47949. this.downSampleX4PostProcess.onApply = function (effect) {
  47950. var id = 0;
  47951. for (var i = -2; i < 2; i++) {
  47952. for (var j = -2; j < 2; j++) {
  47953. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  47954. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  47955. id += 2;
  47956. }
  47957. }
  47958. effect.setArray2("dsOffsets", downSampleX4Offsets);
  47959. };
  47960. // Add to pipeline
  47961. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  47962. };
  47963. // Brightpass Post-Process
  47964. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  47965. var _this = this;
  47966. var brightOffsets = new Array(8);
  47967. 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);
  47968. this.brightPassPostProcess.onApply = function (effect) {
  47969. var sU = (1.0 / _this.brightPassPostProcess.width);
  47970. var sV = (1.0 / _this.brightPassPostProcess.height);
  47971. brightOffsets[0] = -0.5 * sU;
  47972. brightOffsets[1] = 0.5 * sV;
  47973. brightOffsets[2] = 0.5 * sU;
  47974. brightOffsets[3] = 0.5 * sV;
  47975. brightOffsets[4] = -0.5 * sU;
  47976. brightOffsets[5] = -0.5 * sV;
  47977. brightOffsets[6] = 0.5 * sU;
  47978. brightOffsets[7] = -0.5 * sV;
  47979. effect.setArray2("dsOffsets", brightOffsets);
  47980. effect.setFloat("brightThreshold", _this.brightThreshold);
  47981. };
  47982. // Add to pipeline
  47983. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  47984. };
  47985. // Create gaussian blur H&V post-processes
  47986. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  47987. var _this = this;
  47988. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  47989. var blurOffsets = new Array(9);
  47990. var blurWeights = new Array(9);
  47991. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  47992. var callback = function (height) {
  47993. return function (effect) {
  47994. // Weights
  47995. var x = 0.0;
  47996. for (var i = 0; i < 9; i++) {
  47997. x = (i - 4.0) / 4.0;
  47998. blurWeights[i] =
  47999. _this.gaussianCoefficient
  48000. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  48001. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  48002. }
  48003. var lastOutputDimensions = {
  48004. width: scene.getEngine().getRenderWidth(),
  48005. height: scene.getEngine().getRenderHeight()
  48006. };
  48007. for (var i = 0; i < 9; i++) {
  48008. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  48009. blurOffsets[i] = value;
  48010. }
  48011. effect.setArray("blurOffsets", blurOffsets);
  48012. effect.setArray("blurWeights", blurWeights);
  48013. if (height) {
  48014. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  48015. }
  48016. else {
  48017. effect.setFloat("blurWidth", _this[blurWidthKey]);
  48018. }
  48019. };
  48020. };
  48021. // Create horizontal gaussian blur post-processes
  48022. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48023. gaussianBlurHPostProcess.onApply = callback(false);
  48024. // Create vertical gaussian blur post-process
  48025. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV_" + ratio + "_" + indice, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48026. gaussianBlurVPostProcess.onApply = callback(true);
  48027. // Add to pipeline
  48028. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  48029. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  48030. // Finish
  48031. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  48032. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  48033. };
  48034. // Create texture adder post-process
  48035. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  48036. var _this = this;
  48037. 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);
  48038. this.textureAdderPostProcess.onApply = function (effect) {
  48039. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  48040. effect.setTexture("lensSampler", _this.lensTexture);
  48041. effect.setFloat("exposure", _this.exposure);
  48042. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  48043. _this._currentHDRSource = _this.textureAdderFinalPostProcess;
  48044. };
  48045. // Add to pipeline
  48046. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  48047. };
  48048. // Create luminance
  48049. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene) {
  48050. var _this = this;
  48051. // Create luminance
  48052. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  48053. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", BABYLON.Engine.TEXTURETYPE_FLOAT);
  48054. var offsets = [];
  48055. this.luminancePostProcess.onApply = function (effect) {
  48056. var sU = (1.0 / _this.luminancePostProcess.width);
  48057. var sV = (1.0 / _this.luminancePostProcess.height);
  48058. offsets[0] = -0.5 * sU;
  48059. offsets[1] = 0.5 * sV;
  48060. offsets[2] = 0.5 * sU;
  48061. offsets[3] = 0.5 * sV;
  48062. offsets[4] = -0.5 * sU;
  48063. offsets[5] = -0.5 * sV;
  48064. offsets[6] = 0.5 * sU;
  48065. offsets[7] = -0.5 * sV;
  48066. effect.setArray2("lumOffsets", offsets);
  48067. };
  48068. // Add to pipeline
  48069. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  48070. // Create down sample luminance
  48071. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  48072. var size = Math.pow(3, i);
  48073. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  48074. if (i === 0) {
  48075. defines += "#define FINAL_DOWN_SAMPLER";
  48076. }
  48077. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  48078. this.luminanceDownSamplePostProcesses.push(postProcess);
  48079. }
  48080. // Create callbacks and add effects
  48081. var lastLuminance = this.luminancePostProcess;
  48082. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  48083. var downSampleOffsets = new Array(18);
  48084. pp.onApply = function (effect) {
  48085. var id = 0;
  48086. for (var x = -1; x < 2; x++) {
  48087. for (var y = -1; y < 2; y++) {
  48088. downSampleOffsets[id] = x / lastLuminance.width;
  48089. downSampleOffsets[id + 1] = y / lastLuminance.height;
  48090. id += 2;
  48091. }
  48092. }
  48093. effect.setArray2("dsOffsets", downSampleOffsets);
  48094. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  48095. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  48096. lastLuminance = _this.luminancePostProcess;
  48097. }
  48098. else {
  48099. lastLuminance = pp;
  48100. }
  48101. };
  48102. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  48103. pp.onAfterRender = function (effect) {
  48104. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  48105. 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);
  48106. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  48107. };
  48108. }
  48109. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  48110. });
  48111. };
  48112. // Create HDR post-process
  48113. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  48114. var _this = this;
  48115. 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);
  48116. var outputLiminance = 1;
  48117. var time = 0;
  48118. var lastTime = 0;
  48119. this.hdrPostProcess.onApply = function (effect) {
  48120. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentHDRSource);
  48121. time += scene.getEngine().getDeltaTime();
  48122. if (outputLiminance < 0) {
  48123. outputLiminance = _this._hdrCurrentLuminance;
  48124. }
  48125. else {
  48126. var dt = (lastTime - time) / 1000.0;
  48127. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  48128. outputLiminance += _this.hdrDecreaseRate * dt;
  48129. }
  48130. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  48131. outputLiminance -= _this.hdrIncreaseRate * dt;
  48132. }
  48133. else {
  48134. outputLiminance = _this._hdrCurrentLuminance;
  48135. }
  48136. }
  48137. outputLiminance = BABYLON.MathTools.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  48138. effect.setFloat("averageLuminance", outputLiminance);
  48139. lastTime = time;
  48140. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  48141. };
  48142. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  48143. };
  48144. // Create lens flare post-process
  48145. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  48146. var _this = this;
  48147. 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);
  48148. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  48149. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  48150. 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);
  48151. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  48152. var resolution = new BABYLON.Vector2(0, 0);
  48153. // Lens flare
  48154. this.lensFlarePostProcess.onApply = function (effect) {
  48155. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  48156. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  48157. effect.setFloat("strength", _this.lensFlareStrength);
  48158. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  48159. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  48160. // Shift
  48161. resolution.x = _this.lensFlarePostProcess.width;
  48162. resolution.y = _this.lensFlarePostProcess.height;
  48163. effect.setVector2("resolution", resolution);
  48164. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  48165. };
  48166. // Compose
  48167. 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);
  48168. 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);
  48169. this.lensFlareComposePostProcess.onApply = function (effect) {
  48170. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  48171. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  48172. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  48173. // Lens start rotation matrix
  48174. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  48175. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  48176. 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));
  48177. camRot *= 4.0;
  48178. 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);
  48179. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  48180. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  48181. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  48182. _this._currentHDRSource = _this.lensFlareFinalPostProcess;
  48183. };
  48184. };
  48185. // Create depth-of-field post-process
  48186. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  48187. var _this = this;
  48188. 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);
  48189. this.depthOfFieldPostProcess.onApply = function (effect) {
  48190. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  48191. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  48192. effect.setFloat("distance", _this.depthOfFieldDistance);
  48193. };
  48194. // Add to pipeline
  48195. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  48196. };
  48197. // Dispose
  48198. StandardRenderingPipeline.prototype.dispose = function () {
  48199. for (var i = 0; i < this._cameras.length; i++) {
  48200. var camera = this._cameras[i];
  48201. this.originalPostProcess.dispose(camera);
  48202. this.downSampleX4PostProcess.dispose(camera);
  48203. this.brightPassPostProcess.dispose(camera);
  48204. this.textureAdderPostProcess.dispose(camera);
  48205. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  48206. this.gaussianBlurHPostProcesses[j].dispose(camera);
  48207. }
  48208. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  48209. this.gaussianBlurVPostProcesses[j].dispose(camera);
  48210. }
  48211. this.textureAdderFinalPostProcess.dispose(camera);
  48212. this.lensFlarePostProcess.dispose(camera);
  48213. this.lensFlareComposePostProcess.dispose(camera);
  48214. this.depthOfFieldPostProcess.dispose(camera);
  48215. }
  48216. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  48217. _super.prototype.dispose.call(this);
  48218. };
  48219. // Serialize rendering pipeline
  48220. StandardRenderingPipeline.prototype.serialize = function () {
  48221. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48222. serializationObject.customType = "StandardRenderingPipeline";
  48223. return serializationObject;
  48224. };
  48225. // Parse serialized pipeline
  48226. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  48227. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  48228. };
  48229. return StandardRenderingPipeline;
  48230. }(BABYLON.PostProcessRenderPipeline));
  48231. // Luminance steps
  48232. StandardRenderingPipeline.LuminanceSteps = 6;
  48233. __decorate([
  48234. BABYLON.serialize()
  48235. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  48236. __decorate([
  48237. BABYLON.serialize()
  48238. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  48239. __decorate([
  48240. BABYLON.serialize()
  48241. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  48242. __decorate([
  48243. BABYLON.serialize()
  48244. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  48245. __decorate([
  48246. BABYLON.serialize()
  48247. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  48248. __decorate([
  48249. BABYLON.serialize()
  48250. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  48251. __decorate([
  48252. BABYLON.serialize()
  48253. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  48254. __decorate([
  48255. BABYLON.serializeAsTexture("lensTexture")
  48256. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  48257. __decorate([
  48258. BABYLON.serialize()
  48259. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  48260. __decorate([
  48261. BABYLON.serialize()
  48262. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  48263. __decorate([
  48264. BABYLON.serialize()
  48265. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  48266. __decorate([
  48267. BABYLON.serializeAsTexture("lensColorTexture")
  48268. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  48269. __decorate([
  48270. BABYLON.serialize()
  48271. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  48272. __decorate([
  48273. BABYLON.serialize()
  48274. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  48275. __decorate([
  48276. BABYLON.serialize()
  48277. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  48278. __decorate([
  48279. BABYLON.serialize()
  48280. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  48281. __decorate([
  48282. BABYLON.serializeAsTexture("lensStarTexture")
  48283. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  48284. __decorate([
  48285. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  48286. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  48287. __decorate([
  48288. BABYLON.serialize()
  48289. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  48290. __decorate([
  48291. BABYLON.serialize()
  48292. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  48293. __decorate([
  48294. BABYLON.serialize()
  48295. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  48296. __decorate([
  48297. BABYLON.serialize()
  48298. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  48299. __decorate([
  48300. BABYLON.serialize()
  48301. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  48302. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  48303. })(BABYLON || (BABYLON = {}));
  48304. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  48305. var BABYLON;
  48306. (function (BABYLON) {
  48307. var BlurPostProcess = (function (_super) {
  48308. __extends(BlurPostProcess, _super);
  48309. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  48310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48311. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  48312. _this.direction = direction;
  48313. _this.blurWidth = blurWidth;
  48314. _this.onApplyObservable.add(function (effect) {
  48315. effect.setFloat2("screenSize", _this.width, _this.height);
  48316. effect.setVector2("direction", _this.direction);
  48317. effect.setFloat("blurWidth", _this.blurWidth);
  48318. });
  48319. return _this;
  48320. }
  48321. return BlurPostProcess;
  48322. }(BABYLON.PostProcess));
  48323. BABYLON.BlurPostProcess = BlurPostProcess;
  48324. })(BABYLON || (BABYLON = {}));
  48325. //# sourceMappingURL=babylon.blurPostProcess.js.map
  48326. var BABYLON;
  48327. (function (BABYLON) {
  48328. var RefractionPostProcess = (function (_super) {
  48329. __extends(RefractionPostProcess, _super);
  48330. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  48331. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  48332. _this.color = color;
  48333. _this.depth = depth;
  48334. _this.colorLevel = colorLevel;
  48335. _this.onActivateObservable.add(function (cam) {
  48336. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  48337. });
  48338. _this.onApplyObservable.add(function (effect) {
  48339. effect.setColor3("baseColor", _this.color);
  48340. effect.setFloat("depth", _this.depth);
  48341. effect.setFloat("colorLevel", _this.colorLevel);
  48342. effect.setTexture("refractionSampler", _this._refRexture);
  48343. });
  48344. return _this;
  48345. }
  48346. // Methods
  48347. RefractionPostProcess.prototype.dispose = function (camera) {
  48348. if (this._refRexture) {
  48349. this._refRexture.dispose();
  48350. }
  48351. _super.prototype.dispose.call(this, camera);
  48352. };
  48353. return RefractionPostProcess;
  48354. }(BABYLON.PostProcess));
  48355. BABYLON.RefractionPostProcess = RefractionPostProcess;
  48356. })(BABYLON || (BABYLON = {}));
  48357. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  48358. var BABYLON;
  48359. (function (BABYLON) {
  48360. var BlackAndWhitePostProcess = (function (_super) {
  48361. __extends(BlackAndWhitePostProcess, _super);
  48362. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  48363. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  48364. }
  48365. return BlackAndWhitePostProcess;
  48366. }(BABYLON.PostProcess));
  48367. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  48368. })(BABYLON || (BABYLON = {}));
  48369. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  48370. var BABYLON;
  48371. (function (BABYLON) {
  48372. var ConvolutionPostProcess = (function (_super) {
  48373. __extends(ConvolutionPostProcess, _super);
  48374. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  48375. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  48376. _this.kernel = kernel;
  48377. _this.onApply = function (effect) {
  48378. effect.setFloat2("screenSize", _this.width, _this.height);
  48379. effect.setArray("kernel", _this.kernel);
  48380. };
  48381. return _this;
  48382. }
  48383. return ConvolutionPostProcess;
  48384. }(BABYLON.PostProcess));
  48385. // Statics
  48386. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  48387. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  48388. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  48389. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  48390. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  48391. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  48392. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  48393. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  48394. })(BABYLON || (BABYLON = {}));
  48395. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  48396. var BABYLON;
  48397. (function (BABYLON) {
  48398. var FilterPostProcess = (function (_super) {
  48399. __extends(FilterPostProcess, _super);
  48400. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  48401. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  48402. _this.kernelMatrix = kernelMatrix;
  48403. _this.onApply = function (effect) {
  48404. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  48405. };
  48406. return _this;
  48407. }
  48408. return FilterPostProcess;
  48409. }(BABYLON.PostProcess));
  48410. BABYLON.FilterPostProcess = FilterPostProcess;
  48411. })(BABYLON || (BABYLON = {}));
  48412. //# sourceMappingURL=babylon.filterPostProcess.js.map
  48413. var BABYLON;
  48414. (function (BABYLON) {
  48415. var FxaaPostProcess = (function (_super) {
  48416. __extends(FxaaPostProcess, _super);
  48417. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  48418. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable) || this;
  48419. _this.onSizeChangedObservable.add(function () {
  48420. _this.texelWidth = 1.0 / _this.width;
  48421. _this.texelHeight = 1.0 / _this.height;
  48422. });
  48423. _this.onApplyObservable.add(function (effect) {
  48424. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  48425. });
  48426. return _this;
  48427. }
  48428. return FxaaPostProcess;
  48429. }(BABYLON.PostProcess));
  48430. BABYLON.FxaaPostProcess = FxaaPostProcess;
  48431. })(BABYLON || (BABYLON = {}));
  48432. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  48433. var BABYLON;
  48434. (function (BABYLON) {
  48435. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  48436. var VolumetricLightScatteringPostProcess = (function (_super) {
  48437. __extends(VolumetricLightScatteringPostProcess, _super);
  48438. /**
  48439. * @constructor
  48440. * @param {string} name - The post-process name
  48441. * @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)
  48442. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  48443. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  48444. * @param {number} samples - The post-process quality, default 100
  48445. * @param {number} samplingMode - The post-process filtering mode
  48446. * @param {BABYLON.Engine} engine - The babylon engine
  48447. * @param {boolean} reusable - If the post-process is reusable
  48448. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  48449. */
  48450. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  48451. if (samples === void 0) { samples = 100; }
  48452. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48453. 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;
  48454. _this._screenCoordinates = BABYLON.Vector2.Zero();
  48455. /**
  48456. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  48457. * @type {Vector3}
  48458. */
  48459. _this.customMeshPosition = BABYLON.Vector3.Zero();
  48460. /**
  48461. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  48462. * @type {boolean}
  48463. */
  48464. _this.useCustomMeshPosition = false;
  48465. /**
  48466. * If the post-process should inverse the light scattering direction
  48467. * @type {boolean}
  48468. */
  48469. _this.invert = true;
  48470. /**
  48471. * Array containing the excluded meshes not rendered in the internal pass
  48472. */
  48473. _this.excludedMeshes = new Array();
  48474. /**
  48475. * Controls the overall intensity of the post-process
  48476. * @type {number}
  48477. */
  48478. _this.exposure = 0.3;
  48479. /**
  48480. * Dissipates each sample's contribution in range [0, 1]
  48481. * @type {number}
  48482. */
  48483. _this.decay = 0.96815;
  48484. /**
  48485. * Controls the overall intensity of each sample
  48486. * @type {number}
  48487. */
  48488. _this.weight = 0.58767;
  48489. /**
  48490. * Controls the density of each sample
  48491. * @type {number}
  48492. */
  48493. _this.density = 0.926;
  48494. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  48495. var engine = scene.getEngine();
  48496. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  48497. // Configure mesh
  48498. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  48499. // Configure
  48500. _this._createPass(scene, ratio.passRatio || ratio);
  48501. _this.onActivate = function (camera) {
  48502. if (!_this.isSupported) {
  48503. _this.dispose(camera);
  48504. }
  48505. _this.onActivate = null;
  48506. };
  48507. _this.onApplyObservable.add(function (effect) {
  48508. _this._updateMeshScreenCoordinates(scene);
  48509. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  48510. effect.setFloat("exposure", _this.exposure);
  48511. effect.setFloat("decay", _this.decay);
  48512. effect.setFloat("weight", _this.weight);
  48513. effect.setFloat("density", _this.density);
  48514. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  48515. });
  48516. return _this;
  48517. }
  48518. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  48519. get: function () {
  48520. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48521. return false;
  48522. },
  48523. set: function (useDiffuseColor) {
  48524. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48525. },
  48526. enumerable: true,
  48527. configurable: true
  48528. });
  48529. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  48530. var mesh = subMesh.getMesh();
  48531. // Render this.mesh as default
  48532. if (mesh === this.mesh) {
  48533. return mesh.material.isReady(mesh);
  48534. }
  48535. var defines = [];
  48536. var attribs = [BABYLON.VertexBuffer.PositionKind];
  48537. var material = subMesh.getMaterial();
  48538. var needUV = false;
  48539. // Alpha test
  48540. if (material) {
  48541. if (material.needAlphaTesting()) {
  48542. defines.push("#define ALPHATEST");
  48543. }
  48544. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48545. attribs.push(BABYLON.VertexBuffer.UVKind);
  48546. defines.push("#define UV1");
  48547. }
  48548. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48549. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48550. defines.push("#define UV2");
  48551. }
  48552. }
  48553. // Bones
  48554. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48555. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48556. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48557. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48558. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48559. }
  48560. else {
  48561. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48562. }
  48563. // Instances
  48564. if (useInstances) {
  48565. defines.push("#define INSTANCES");
  48566. attribs.push("world0");
  48567. attribs.push("world1");
  48568. attribs.push("world2");
  48569. attribs.push("world3");
  48570. }
  48571. // Get correct effect
  48572. var join = defines.join("\n");
  48573. if (this._cachedDefines !== join) {
  48574. this._cachedDefines = join;
  48575. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  48576. }
  48577. return this._volumetricLightScatteringPass.isReady();
  48578. };
  48579. /**
  48580. * Sets the new light position for light scattering effect
  48581. * @param {BABYLON.Vector3} The new custom light position
  48582. */
  48583. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  48584. this.customMeshPosition = position;
  48585. };
  48586. /**
  48587. * Returns the light position for light scattering effect
  48588. * @return {BABYLON.Vector3} The custom light position
  48589. */
  48590. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  48591. return this.customMeshPosition;
  48592. };
  48593. /**
  48594. * Disposes the internal assets and detaches the post-process from the camera
  48595. */
  48596. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  48597. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  48598. if (rttIndex !== -1) {
  48599. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  48600. }
  48601. this._volumetricLightScatteringRTT.dispose();
  48602. _super.prototype.dispose.call(this, camera);
  48603. };
  48604. /**
  48605. * Returns the render target texture used by the post-process
  48606. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  48607. */
  48608. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  48609. return this._volumetricLightScatteringRTT;
  48610. };
  48611. // Private methods
  48612. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  48613. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  48614. return true;
  48615. }
  48616. return false;
  48617. };
  48618. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  48619. var _this = this;
  48620. var engine = scene.getEngine();
  48621. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48622. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48623. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48624. this._volumetricLightScatteringRTT.renderList = null;
  48625. this._volumetricLightScatteringRTT.renderParticles = false;
  48626. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  48627. // Custom render function for submeshes
  48628. var renderSubMesh = function (subMesh) {
  48629. var mesh = subMesh.getRenderingMesh();
  48630. if (_this._meshExcluded(mesh)) {
  48631. return;
  48632. }
  48633. var scene = mesh.getScene();
  48634. var engine = scene.getEngine();
  48635. // Culling
  48636. engine.setState(subMesh.getMaterial().backFaceCulling);
  48637. // Managing instances
  48638. var batch = mesh._getInstancesRenderList(subMesh._id);
  48639. if (batch.mustReturn) {
  48640. return;
  48641. }
  48642. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  48643. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  48644. var effect = _this._volumetricLightScatteringPass;
  48645. if (mesh === _this.mesh) {
  48646. if (subMesh.effect) {
  48647. effect = subMesh.effect;
  48648. }
  48649. else {
  48650. effect = subMesh.getMaterial().getEffect();
  48651. }
  48652. }
  48653. engine.enableEffect(effect);
  48654. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  48655. if (mesh === _this.mesh) {
  48656. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  48657. }
  48658. else {
  48659. var material = subMesh.getMaterial();
  48660. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  48661. // Alpha test
  48662. if (material && material.needAlphaTesting()) {
  48663. var alphaTexture = material.getAlphaTestTexture();
  48664. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  48665. if (alphaTexture) {
  48666. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48667. }
  48668. }
  48669. // Bones
  48670. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48671. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48672. }
  48673. }
  48674. // Draw
  48675. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  48676. }
  48677. };
  48678. // Render target texture callbacks
  48679. var savedSceneClearColor;
  48680. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  48681. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  48682. savedSceneClearColor = scene.clearColor;
  48683. scene.clearColor = sceneClearColor;
  48684. });
  48685. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  48686. scene.clearColor = savedSceneClearColor;
  48687. });
  48688. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  48689. var engine = scene.getEngine();
  48690. var index;
  48691. for (index = 0; index < opaqueSubMeshes.length; index++) {
  48692. renderSubMesh(opaqueSubMeshes.data[index]);
  48693. }
  48694. engine.setAlphaTesting(true);
  48695. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  48696. renderSubMesh(alphaTestSubMeshes.data[index]);
  48697. }
  48698. engine.setAlphaTesting(false);
  48699. if (transparentSubMeshes.length) {
  48700. // Sort sub meshes
  48701. for (index = 0; index < transparentSubMeshes.length; index++) {
  48702. var submesh = transparentSubMeshes.data[index];
  48703. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  48704. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  48705. }
  48706. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  48707. sortedArray.sort(function (a, b) {
  48708. // Alpha index first
  48709. if (a._alphaIndex > b._alphaIndex) {
  48710. return 1;
  48711. }
  48712. if (a._alphaIndex < b._alphaIndex) {
  48713. return -1;
  48714. }
  48715. // Then distance to camera
  48716. if (a._distanceToCamera < b._distanceToCamera) {
  48717. return 1;
  48718. }
  48719. if (a._distanceToCamera > b._distanceToCamera) {
  48720. return -1;
  48721. }
  48722. return 0;
  48723. });
  48724. // Render sub meshes
  48725. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48726. for (index = 0; index < sortedArray.length; index++) {
  48727. renderSubMesh(sortedArray[index]);
  48728. }
  48729. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48730. }
  48731. };
  48732. };
  48733. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  48734. var transform = scene.getTransformMatrix();
  48735. var meshPosition;
  48736. if (this.useCustomMeshPosition) {
  48737. meshPosition = this.customMeshPosition;
  48738. }
  48739. else if (this.attachedNode) {
  48740. meshPosition = this.attachedNode.position;
  48741. }
  48742. else {
  48743. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  48744. }
  48745. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  48746. this._screenCoordinates.x = pos.x / this._viewPort.width;
  48747. this._screenCoordinates.y = pos.y / this._viewPort.height;
  48748. if (this.invert)
  48749. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  48750. };
  48751. // Static methods
  48752. /**
  48753. * Creates a default mesh for the Volumeric Light Scattering post-process
  48754. * @param {string} The mesh name
  48755. * @param {BABYLON.Scene} The scene where to create the mesh
  48756. * @return {BABYLON.Mesh} the default mesh
  48757. */
  48758. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  48759. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  48760. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  48761. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  48762. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  48763. mesh.material = material;
  48764. return mesh;
  48765. };
  48766. return VolumetricLightScatteringPostProcess;
  48767. }(BABYLON.PostProcess));
  48768. __decorate([
  48769. BABYLON.serializeAsVector3()
  48770. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  48771. __decorate([
  48772. BABYLON.serialize()
  48773. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  48774. __decorate([
  48775. BABYLON.serialize()
  48776. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  48777. __decorate([
  48778. BABYLON.serializeAsMeshReference()
  48779. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  48780. __decorate([
  48781. BABYLON.serialize()
  48782. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  48783. __decorate([
  48784. BABYLON.serialize()
  48785. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  48786. __decorate([
  48787. BABYLON.serialize()
  48788. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  48789. __decorate([
  48790. BABYLON.serialize()
  48791. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  48792. __decorate([
  48793. BABYLON.serialize()
  48794. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  48795. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  48796. })(BABYLON || (BABYLON = {}));
  48797. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  48798. //
  48799. // This post-process allows the modification of rendered colors by using
  48800. // a 'look-up table' (LUT). This effect is also called Color Grading.
  48801. //
  48802. // The object needs to be provided an url to a texture containing the color
  48803. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  48804. // Use an image editing software to tweak the LUT to match your needs.
  48805. //
  48806. // For an example of a color LUT, see here:
  48807. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  48808. // For explanations on color grading, see here:
  48809. // http://udn.epicgames.com/Three/ColorGrading.html
  48810. //
  48811. var BABYLON;
  48812. (function (BABYLON) {
  48813. var ColorCorrectionPostProcess = (function (_super) {
  48814. __extends(ColorCorrectionPostProcess, _super);
  48815. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  48816. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  48817. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  48818. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  48819. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48820. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48821. _this.onApply = function (effect) {
  48822. effect.setTexture("colorTable", _this._colorTableTexture);
  48823. };
  48824. return _this;
  48825. }
  48826. return ColorCorrectionPostProcess;
  48827. }(BABYLON.PostProcess));
  48828. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  48829. })(BABYLON || (BABYLON = {}));
  48830. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  48831. var BABYLON;
  48832. (function (BABYLON) {
  48833. var TonemappingOperator;
  48834. (function (TonemappingOperator) {
  48835. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  48836. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  48837. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  48838. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  48839. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  48840. ;
  48841. var TonemapPostProcess = (function (_super) {
  48842. __extends(TonemapPostProcess, _super);
  48843. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  48844. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48845. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48846. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  48847. _this._operator = _operator;
  48848. _this.exposureAdjustment = exposureAdjustment;
  48849. var defines = "#define ";
  48850. if (_this._operator === TonemappingOperator.Hable)
  48851. defines += "HABLE_TONEMAPPING";
  48852. else if (_this._operator === TonemappingOperator.Reinhard)
  48853. defines += "REINHARD_TONEMAPPING";
  48854. else if (_this._operator === TonemappingOperator.HejiDawson)
  48855. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  48856. else if (_this._operator === TonemappingOperator.Photographic)
  48857. defines += "PHOTOGRAPHIC_TONEMAPPING";
  48858. //sadly a second call to create the effect.
  48859. _this.updateEffect(defines);
  48860. _this.onApply = function (effect) {
  48861. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  48862. };
  48863. return _this;
  48864. }
  48865. return TonemapPostProcess;
  48866. }(BABYLON.PostProcess));
  48867. BABYLON.TonemapPostProcess = TonemapPostProcess;
  48868. })(BABYLON || (BABYLON = {}));
  48869. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  48870. var BABYLON;
  48871. (function (BABYLON) {
  48872. var DisplayPassPostProcess = (function (_super) {
  48873. __extends(DisplayPassPostProcess, _super);
  48874. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  48875. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  48876. }
  48877. return DisplayPassPostProcess;
  48878. }(BABYLON.PostProcess));
  48879. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  48880. })(BABYLON || (BABYLON = {}));
  48881. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  48882. /// <reference path="..\babylon.node.ts" />
  48883. var BABYLON;
  48884. (function (BABYLON) {
  48885. var Bone = (function (_super) {
  48886. __extends(Bone, _super);
  48887. function Bone(name, skeleton, parentBone, matrix, restPose) {
  48888. var _this = _super.call(this, name, skeleton.getScene()) || this;
  48889. _this.name = name;
  48890. _this.children = new Array();
  48891. _this.animations = new Array();
  48892. _this._worldTransform = new BABYLON.Matrix();
  48893. _this._absoluteTransform = new BABYLON.Matrix();
  48894. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  48895. _this._scaleMatrix = BABYLON.Matrix.Identity();
  48896. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  48897. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  48898. _this._scalingDeterminant = 1;
  48899. _this._skeleton = skeleton;
  48900. _this._localMatrix = matrix;
  48901. _this._baseMatrix = matrix.clone();
  48902. _this._restPose = restPose ? restPose : matrix.clone();
  48903. skeleton.bones.push(_this);
  48904. if (parentBone) {
  48905. _this._parent = parentBone;
  48906. parentBone.children.push(_this);
  48907. }
  48908. else {
  48909. _this._parent = null;
  48910. }
  48911. _this._updateDifferenceMatrix();
  48912. if (_this.getAbsoluteTransform().determinant() < 0) {
  48913. _this._scalingDeterminant *= -1;
  48914. }
  48915. return _this;
  48916. }
  48917. Object.defineProperty(Bone.prototype, "_matrix", {
  48918. get: function () {
  48919. return this._localMatrix;
  48920. },
  48921. set: function (val) {
  48922. if (this._localMatrix) {
  48923. this._localMatrix.copyFrom(val);
  48924. }
  48925. else {
  48926. this._localMatrix = val;
  48927. }
  48928. },
  48929. enumerable: true,
  48930. configurable: true
  48931. });
  48932. // Members
  48933. Bone.prototype.getParent = function () {
  48934. return this._parent;
  48935. };
  48936. Bone.prototype.getLocalMatrix = function () {
  48937. return this._localMatrix;
  48938. };
  48939. Bone.prototype.getBaseMatrix = function () {
  48940. return this._baseMatrix;
  48941. };
  48942. Bone.prototype.getRestPose = function () {
  48943. return this._restPose;
  48944. };
  48945. Bone.prototype.returnToRest = function () {
  48946. this.updateMatrix(this._restPose.clone());
  48947. };
  48948. Bone.prototype.getWorldMatrix = function () {
  48949. return this._worldTransform;
  48950. };
  48951. Bone.prototype.getInvertedAbsoluteTransform = function () {
  48952. return this._invertedAbsoluteTransform;
  48953. };
  48954. Bone.prototype.getAbsoluteTransform = function () {
  48955. return this._absoluteTransform;
  48956. };
  48957. // Methods
  48958. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  48959. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  48960. this._baseMatrix = matrix.clone();
  48961. this._localMatrix = matrix.clone();
  48962. this._skeleton._markAsDirty();
  48963. if (updateDifferenceMatrix) {
  48964. this._updateDifferenceMatrix();
  48965. }
  48966. };
  48967. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  48968. if (!rootMatrix) {
  48969. rootMatrix = this._baseMatrix;
  48970. }
  48971. if (this._parent) {
  48972. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  48973. }
  48974. else {
  48975. this._absoluteTransform.copyFrom(rootMatrix);
  48976. }
  48977. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  48978. for (var index = 0; index < this.children.length; index++) {
  48979. this.children[index]._updateDifferenceMatrix();
  48980. }
  48981. };
  48982. Bone.prototype.markAsDirty = function () {
  48983. this._currentRenderId++;
  48984. this._skeleton._markAsDirty();
  48985. };
  48986. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  48987. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  48988. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  48989. // all animation may be coming from a library skeleton, so may need to create animation
  48990. if (this.animations.length === 0) {
  48991. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  48992. this.animations[0].setKeys([]);
  48993. }
  48994. // get animation info / verify there is such a range from the source bone
  48995. var sourceRange = source.animations[0].getRange(rangeName);
  48996. if (!sourceRange) {
  48997. return false;
  48998. }
  48999. var from = sourceRange.from;
  49000. var to = sourceRange.to;
  49001. var sourceKeys = source.animations[0].getKeys();
  49002. // rescaling prep
  49003. var sourceBoneLength = source.length;
  49004. var sourceParent = source.getParent();
  49005. var parent = this.getParent();
  49006. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  49007. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  49008. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  49009. var destKeys = this.animations[0].getKeys();
  49010. // loop vars declaration
  49011. var orig;
  49012. var origTranslation;
  49013. var mat;
  49014. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  49015. orig = sourceKeys[key];
  49016. if (orig.frame >= from && orig.frame <= to) {
  49017. if (rescaleAsRequired) {
  49018. mat = orig.value.clone();
  49019. // scale based on parent ratio, when bone has parent
  49020. if (parentScalingReqd) {
  49021. origTranslation = mat.getTranslation();
  49022. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  49023. // scale based on skeleton dimension ratio when root bone, and value is passed
  49024. }
  49025. else if (dimensionsScalingReqd) {
  49026. origTranslation = mat.getTranslation();
  49027. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  49028. // use original when root bone, and no data for skelDimensionsRatio
  49029. }
  49030. else {
  49031. mat = orig.value;
  49032. }
  49033. }
  49034. else {
  49035. mat = orig.value;
  49036. }
  49037. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  49038. }
  49039. }
  49040. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  49041. return true;
  49042. };
  49043. /**
  49044. * Translate the bone in local or world space.
  49045. * @param vec The amount to translate the bone.
  49046. * @param space The space that the translation is in.
  49047. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49048. */
  49049. Bone.prototype.translate = function (vec, space, mesh) {
  49050. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49051. var lm = this.getLocalMatrix();
  49052. if (space == BABYLON.Space.LOCAL) {
  49053. lm.m[12] += vec.x;
  49054. lm.m[13] += vec.y;
  49055. lm.m[14] += vec.z;
  49056. }
  49057. else {
  49058. var wm;
  49059. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49060. if (mesh) {
  49061. wm = mesh.getWorldMatrix();
  49062. }
  49063. this._skeleton.computeAbsoluteTransforms();
  49064. var tmat = Bone._tmpMats[0];
  49065. var tvec = Bone._tmpVecs[0];
  49066. if (mesh) {
  49067. tmat.copyFrom(this._parent.getAbsoluteTransform());
  49068. tmat.multiplyToRef(wm, tmat);
  49069. }
  49070. else {
  49071. tmat.copyFrom(this._parent.getAbsoluteTransform());
  49072. }
  49073. tmat.m[12] = 0;
  49074. tmat.m[13] = 0;
  49075. tmat.m[14] = 0;
  49076. tmat.invert();
  49077. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  49078. lm.m[12] += tvec.x;
  49079. lm.m[13] += tvec.y;
  49080. lm.m[14] += tvec.z;
  49081. }
  49082. this.markAsDirty();
  49083. };
  49084. /**
  49085. * Set the postion of the bone in local or world space.
  49086. * @param position The position to set the bone.
  49087. * @param space The space that the position is in.
  49088. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49089. */
  49090. Bone.prototype.setPosition = function (position, space, mesh) {
  49091. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49092. var lm = this.getLocalMatrix();
  49093. if (space == BABYLON.Space.LOCAL) {
  49094. lm.m[12] = position.x;
  49095. lm.m[13] = position.y;
  49096. lm.m[14] = position.z;
  49097. }
  49098. else {
  49099. var wm;
  49100. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49101. if (mesh) {
  49102. wm = mesh.getWorldMatrix();
  49103. }
  49104. this._skeleton.computeAbsoluteTransforms();
  49105. var tmat = Bone._tmpMats[0];
  49106. var vec = Bone._tmpVecs[0];
  49107. if (mesh) {
  49108. tmat.copyFrom(this._parent.getAbsoluteTransform());
  49109. tmat.multiplyToRef(wm, tmat);
  49110. }
  49111. else {
  49112. tmat.copyFrom(this._parent.getAbsoluteTransform());
  49113. }
  49114. tmat.invert();
  49115. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  49116. lm.m[12] = vec.x;
  49117. lm.m[13] = vec.y;
  49118. lm.m[14] = vec.z;
  49119. }
  49120. this.markAsDirty();
  49121. };
  49122. /**
  49123. * Set the absolute postion of the bone (world space).
  49124. * @param position The position to set the bone.
  49125. * @param mesh The mesh that this bone is attached to.
  49126. */
  49127. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  49128. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  49129. };
  49130. /**
  49131. * Set the scale of the bone on the x, y and z axes.
  49132. * @param x The scale of the bone on the x axis.
  49133. * @param x The scale of the bone on the y axis.
  49134. * @param z The scale of the bone on the z axis.
  49135. * @param scaleChildren Set this to true if children of the bone should be scaled.
  49136. */
  49137. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  49138. if (scaleChildren === void 0) { scaleChildren = false; }
  49139. if (this.animations[0] && !this.animations[0].isStopped()) {
  49140. if (!scaleChildren) {
  49141. this._negateScaleChildren.x = 1 / x;
  49142. this._negateScaleChildren.y = 1 / y;
  49143. this._negateScaleChildren.z = 1 / z;
  49144. }
  49145. this._syncScaleVector();
  49146. }
  49147. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  49148. };
  49149. /**
  49150. * Scale the bone on the x, y and z axes.
  49151. * @param x The amount to scale the bone on the x axis.
  49152. * @param x The amount to scale the bone on the y axis.
  49153. * @param z The amount to scale the bone on the z axis.
  49154. * @param scaleChildren Set this to true if children of the bone should be scaled.
  49155. */
  49156. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  49157. if (scaleChildren === void 0) { scaleChildren = false; }
  49158. var locMat = this.getLocalMatrix();
  49159. var origLocMat = Bone._tmpMats[0];
  49160. origLocMat.copyFrom(locMat);
  49161. var origLocMatInv = Bone._tmpMats[1];
  49162. origLocMatInv.copyFrom(origLocMat);
  49163. origLocMatInv.invert();
  49164. var scaleMat = Bone._tmpMats[2];
  49165. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  49166. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  49167. this._scaleVector.x *= x;
  49168. this._scaleVector.y *= y;
  49169. this._scaleVector.z *= z;
  49170. locMat.multiplyToRef(origLocMatInv, locMat);
  49171. locMat.multiplyToRef(scaleMat, locMat);
  49172. locMat.multiplyToRef(origLocMat, locMat);
  49173. var parent = this.getParent();
  49174. if (parent) {
  49175. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  49176. }
  49177. else {
  49178. this.getAbsoluteTransform().copyFrom(locMat);
  49179. }
  49180. var len = this.children.length;
  49181. scaleMat.invert();
  49182. for (var i = 0; i < len; i++) {
  49183. var child = this.children[i];
  49184. var cm = child.getLocalMatrix();
  49185. cm.multiplyToRef(scaleMat, cm);
  49186. var lm = child.getLocalMatrix();
  49187. lm.m[12] *= x;
  49188. lm.m[13] *= y;
  49189. lm.m[14] *= z;
  49190. }
  49191. this.computeAbsoluteTransforms();
  49192. if (scaleChildren) {
  49193. for (var i = 0; i < len; i++) {
  49194. this.children[i].scale(x, y, z, scaleChildren);
  49195. }
  49196. }
  49197. this.markAsDirty();
  49198. };
  49199. /**
  49200. * Set the yaw, pitch, and roll of the bone in local or world space.
  49201. * @param yaw The rotation of the bone on the y axis.
  49202. * @param pitch The rotation of the bone on the x axis.
  49203. * @param roll The rotation of the bone on the z axis.
  49204. * @param space The space that the axes of rotation are in.
  49205. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49206. */
  49207. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  49208. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49209. var rotMat = Bone._tmpMats[0];
  49210. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  49211. var rotMatInv = Bone._tmpMats[1];
  49212. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  49213. rotMatInv.multiplyToRef(rotMat, rotMat);
  49214. this._rotateWithMatrix(rotMat, space, mesh);
  49215. };
  49216. /**
  49217. * Rotate the bone on an axis in local or world space.
  49218. * @param axis The axis to rotate the bone on.
  49219. * @param amount The amount to rotate the bone.
  49220. * @param space The space that the axis is in.
  49221. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49222. */
  49223. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  49224. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49225. var rmat = Bone._tmpMats[0];
  49226. rmat.m[12] = 0;
  49227. rmat.m[13] = 0;
  49228. rmat.m[14] = 0;
  49229. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  49230. this._rotateWithMatrix(rmat, space, mesh);
  49231. };
  49232. /**
  49233. * Set the rotation of the bone to a particular axis angle in local or world space.
  49234. * @param axis The axis to rotate the bone on.
  49235. * @param angle The angle that the bone should be rotated to.
  49236. * @param space The space that the axis is in.
  49237. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49238. */
  49239. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  49240. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49241. var rotMat = Bone._tmpMats[0];
  49242. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  49243. var rotMatInv = Bone._tmpMats[1];
  49244. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  49245. rotMatInv.multiplyToRef(rotMat, rotMat);
  49246. this._rotateWithMatrix(rotMat, space, mesh);
  49247. };
  49248. /**
  49249. * Set the euler rotation of the bone in local of world space.
  49250. * @param rotation The euler rotation that the bone should be set to.
  49251. * @param space The space that the rotation is in.
  49252. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49253. */
  49254. Bone.prototype.setRotation = function (rotation, space, mesh) {
  49255. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49256. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  49257. };
  49258. /**
  49259. * Set the quaternion rotation of the bone in local of world space.
  49260. * @param quat The quaternion rotation that the bone should be set to.
  49261. * @param space The space that the rotation is in.
  49262. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49263. */
  49264. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  49265. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49266. var rotMatInv = Bone._tmpMats[0];
  49267. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  49268. var rotMat = Bone._tmpMats[1];
  49269. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  49270. rotMatInv.multiplyToRef(rotMat, rotMat);
  49271. this._rotateWithMatrix(rotMat, space, mesh);
  49272. };
  49273. /**
  49274. * Set the rotation matrix of the bone in local of world space.
  49275. * @param rotMat The rotation matrix that the bone should be set to.
  49276. * @param space The space that the rotation is in.
  49277. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49278. */
  49279. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  49280. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49281. var rotMatInv = Bone._tmpMats[0];
  49282. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  49283. var rotMat2 = Bone._tmpMats[1];
  49284. rotMat2.copyFrom(rotMat);
  49285. rotMatInv.multiplyToRef(rotMat, rotMat2);
  49286. this._rotateWithMatrix(rotMat2, space, mesh);
  49287. };
  49288. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  49289. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49290. var lmat = this.getLocalMatrix();
  49291. var lx = lmat.m[12];
  49292. var ly = lmat.m[13];
  49293. var lz = lmat.m[14];
  49294. var parent = this.getParent();
  49295. var parentScale = Bone._tmpMats[3];
  49296. var parentScaleInv = Bone._tmpMats[4];
  49297. if (parent) {
  49298. if (space == BABYLON.Space.WORLD) {
  49299. if (mesh) {
  49300. parentScale.copyFrom(mesh.getWorldMatrix());
  49301. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  49302. }
  49303. else {
  49304. parentScale.copyFrom(parent.getAbsoluteTransform());
  49305. }
  49306. }
  49307. else {
  49308. parentScale = parent._scaleMatrix;
  49309. }
  49310. parentScaleInv.copyFrom(parentScale);
  49311. parentScaleInv.invert();
  49312. lmat.multiplyToRef(parentScale, lmat);
  49313. lmat.multiplyToRef(rmat, lmat);
  49314. lmat.multiplyToRef(parentScaleInv, lmat);
  49315. }
  49316. else {
  49317. if (space == BABYLON.Space.WORLD && mesh) {
  49318. parentScale.copyFrom(mesh.getWorldMatrix());
  49319. parentScaleInv.copyFrom(parentScale);
  49320. parentScaleInv.invert();
  49321. lmat.multiplyToRef(parentScale, lmat);
  49322. lmat.multiplyToRef(rmat, lmat);
  49323. lmat.multiplyToRef(parentScaleInv, lmat);
  49324. }
  49325. else {
  49326. lmat.multiplyToRef(rmat, lmat);
  49327. }
  49328. }
  49329. lmat.m[12] = lx;
  49330. lmat.m[13] = ly;
  49331. lmat.m[14] = lz;
  49332. this.computeAbsoluteTransforms();
  49333. this.markAsDirty();
  49334. };
  49335. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  49336. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49337. if (space == BABYLON.Space.WORLD) {
  49338. var scaleMatrix = Bone._tmpMats[2];
  49339. scaleMatrix.copyFrom(this._scaleMatrix);
  49340. rotMatInv.copyFrom(this.getAbsoluteTransform());
  49341. if (mesh) {
  49342. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  49343. var meshScale = Bone._tmpMats[3];
  49344. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  49345. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  49346. }
  49347. rotMatInv.invert();
  49348. scaleMatrix.m[0] *= this._scalingDeterminant;
  49349. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  49350. }
  49351. else {
  49352. rotMatInv.copyFrom(this.getLocalMatrix());
  49353. rotMatInv.invert();
  49354. var scaleMatrix = Bone._tmpMats[2];
  49355. scaleMatrix.copyFrom(this._scaleMatrix);
  49356. if (this._parent) {
  49357. var pscaleMatrix = Bone._tmpMats[3];
  49358. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  49359. pscaleMatrix.invert();
  49360. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  49361. }
  49362. else {
  49363. scaleMatrix.m[0] *= this._scalingDeterminant;
  49364. }
  49365. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  49366. }
  49367. };
  49368. /**
  49369. * Get the scale of the bone
  49370. * @returns the scale of the bone
  49371. */
  49372. Bone.prototype.getScale = function () {
  49373. return this._scaleVector.clone();
  49374. };
  49375. /**
  49376. * Copy the scale of the bone to a vector3.
  49377. * @param result The vector3 to copy the scale to
  49378. */
  49379. Bone.prototype.getScaleToRef = function (result) {
  49380. result.copyFrom(this._scaleVector);
  49381. };
  49382. /**
  49383. * Get the position of the bone in local or world space.
  49384. * @param space The space that the returned position is in.
  49385. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49386. * @returns The position of the bone
  49387. */
  49388. Bone.prototype.getPosition = function (space, mesh) {
  49389. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49390. var pos = BABYLON.Vector3.Zero();
  49391. this.getPositionToRef(space, mesh, pos);
  49392. return pos;
  49393. };
  49394. /**
  49395. * Copy the position of the bone to a vector3 in local or world space.
  49396. * @param space The space that the returned position is in.
  49397. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49398. * @param result The vector3 to copy the position to.
  49399. */
  49400. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  49401. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49402. if (space == BABYLON.Space.LOCAL) {
  49403. var lm = this.getLocalMatrix();
  49404. result.x = lm.m[12];
  49405. result.y = lm.m[13];
  49406. result.z = lm.m[14];
  49407. }
  49408. else {
  49409. var wm;
  49410. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49411. if (mesh) {
  49412. wm = mesh.getWorldMatrix();
  49413. }
  49414. this._skeleton.computeAbsoluteTransforms();
  49415. var tmat = Bone._tmpMats[0];
  49416. if (mesh) {
  49417. tmat.copyFrom(this.getAbsoluteTransform());
  49418. tmat.multiplyToRef(wm, tmat);
  49419. }
  49420. else {
  49421. tmat = this.getAbsoluteTransform();
  49422. }
  49423. result.x = tmat.m[12];
  49424. result.y = tmat.m[13];
  49425. result.z = tmat.m[14];
  49426. }
  49427. };
  49428. /**
  49429. * Get the absolute position of the bone (world space).
  49430. * @param mesh The mesh that this bone is attached to.
  49431. * @returns The absolute position of the bone
  49432. */
  49433. Bone.prototype.getAbsolutePosition = function (mesh) {
  49434. var pos = BABYLON.Vector3.Zero();
  49435. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  49436. return pos;
  49437. };
  49438. /**
  49439. * Copy the absolute position of the bone (world space) to the result param.
  49440. * @param mesh The mesh that this bone is attached to.
  49441. * @param result The vector3 to copy the absolute position to.
  49442. */
  49443. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  49444. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  49445. };
  49446. /**
  49447. * Compute the absolute transforms of this bone and its children.
  49448. */
  49449. Bone.prototype.computeAbsoluteTransforms = function () {
  49450. if (this._parent) {
  49451. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  49452. }
  49453. else {
  49454. this._absoluteTransform.copyFrom(this._localMatrix);
  49455. var poseMatrix = this._skeleton.getPoseMatrix();
  49456. if (poseMatrix) {
  49457. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  49458. }
  49459. }
  49460. var children = this.children;
  49461. var len = children.length;
  49462. for (var i = 0; i < len; i++) {
  49463. children[i].computeAbsoluteTransforms();
  49464. }
  49465. };
  49466. Bone.prototype._syncScaleVector = function () {
  49467. var lm = this.getLocalMatrix();
  49468. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  49469. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  49470. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  49471. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  49472. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  49473. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  49474. this._scaleVector.x = xs * Math.sqrt(xsq);
  49475. this._scaleVector.y = ys * Math.sqrt(ysq);
  49476. this._scaleVector.z = zs * Math.sqrt(zsq);
  49477. if (this._parent) {
  49478. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  49479. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  49480. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  49481. }
  49482. 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);
  49483. };
  49484. /**
  49485. * Get the world direction from an axis that is in the local space of the bone.
  49486. * @param localAxis The local direction that is used to compute the world direction.
  49487. * @param mesh The mesh that this bone is attached to.
  49488. * @returns The world direction
  49489. */
  49490. Bone.prototype.getDirection = function (localAxis, mesh) {
  49491. var result = BABYLON.Vector3.Zero();
  49492. this.getDirectionToRef(localAxis, mesh, result);
  49493. return result;
  49494. };
  49495. /**
  49496. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  49497. * @param localAxis The local direction that is used to compute the world direction.
  49498. * @param mesh The mesh that this bone is attached to.
  49499. * @param result The vector3 that the world direction will be copied to.
  49500. */
  49501. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  49502. var wm;
  49503. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49504. if (mesh) {
  49505. wm = mesh.getWorldMatrix();
  49506. }
  49507. this._skeleton.computeAbsoluteTransforms();
  49508. var mat = Bone._tmpMats[0];
  49509. mat.copyFrom(this.getAbsoluteTransform());
  49510. if (mesh) {
  49511. mat.multiplyToRef(wm, mat);
  49512. }
  49513. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  49514. result.normalize();
  49515. };
  49516. /**
  49517. * Get the euler rotation of the bone in local or world space.
  49518. * @param space The space that the rotation should be in.
  49519. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49520. * @returns The euler rotation
  49521. */
  49522. Bone.prototype.getRotation = function (space, mesh) {
  49523. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49524. var result = BABYLON.Vector3.Zero();
  49525. this.getRotationToRef(space, mesh, result);
  49526. return result;
  49527. };
  49528. /**
  49529. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  49530. * @param space The space that the rotation should be in.
  49531. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49532. * @param result The vector3 that the rotation should be copied to.
  49533. */
  49534. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  49535. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49536. var quat = Bone._tmpQuat;
  49537. this.getRotationQuaternionToRef(space, mesh, quat);
  49538. quat.toEulerAnglesToRef(result);
  49539. };
  49540. /**
  49541. * Get the quaternion rotation of the bone in either local or world space.
  49542. * @param space The space that the rotation should be in.
  49543. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49544. * @returns The quaternion rotation
  49545. */
  49546. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  49547. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49548. var result = BABYLON.Quaternion.Identity();
  49549. this.getRotationQuaternionToRef(space, mesh, result);
  49550. return result;
  49551. };
  49552. /**
  49553. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  49554. * @param space The space that the rotation should be in.
  49555. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49556. * @param result The quaternion that the rotation should be copied to.
  49557. */
  49558. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  49559. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49560. if (space == BABYLON.Space.LOCAL) {
  49561. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  49562. }
  49563. else {
  49564. var mat = Bone._tmpMats[0];
  49565. var amat = this.getAbsoluteTransform();
  49566. if (mesh) {
  49567. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  49568. }
  49569. else {
  49570. mat.copyFrom(amat);
  49571. }
  49572. mat.m[0] *= this._scalingDeterminant;
  49573. mat.m[1] *= this._scalingDeterminant;
  49574. mat.m[2] *= this._scalingDeterminant;
  49575. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  49576. }
  49577. };
  49578. /**
  49579. * Get the rotation matrix of the bone in local or world space.
  49580. * @param space The space that the rotation should be in.
  49581. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49582. * @returns The rotation matrix
  49583. */
  49584. Bone.prototype.getRotationMatrix = function (space, mesh) {
  49585. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49586. var result = BABYLON.Matrix.Identity();
  49587. this.getRotationMatrixToRef(space, mesh, result);
  49588. return result;
  49589. };
  49590. /**
  49591. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  49592. * @param space The space that the rotation should be in.
  49593. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49594. * @param result The quaternion that the rotation should be copied to.
  49595. */
  49596. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  49597. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49598. if (space == BABYLON.Space.LOCAL) {
  49599. this.getLocalMatrix().getRotationMatrixToRef(result);
  49600. }
  49601. else {
  49602. var mat = Bone._tmpMats[0];
  49603. var amat = this.getAbsoluteTransform();
  49604. if (mesh) {
  49605. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  49606. }
  49607. else {
  49608. mat.copyFrom(amat);
  49609. }
  49610. mat.m[0] *= this._scalingDeterminant;
  49611. mat.m[1] *= this._scalingDeterminant;
  49612. mat.m[2] *= this._scalingDeterminant;
  49613. mat.getRotationMatrixToRef(result);
  49614. }
  49615. };
  49616. /**
  49617. * Get the world position of a point that is in the local space of the bone.
  49618. * @param position The local position
  49619. * @param mesh The mesh that this bone is attached to.
  49620. * @returns The world position
  49621. */
  49622. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  49623. var result = BABYLON.Vector3.Zero();
  49624. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  49625. return result;
  49626. };
  49627. /**
  49628. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  49629. * @param position The local position
  49630. * @param mesh The mesh that this bone is attached to.
  49631. * @param result The vector3 that the world position should be copied to.
  49632. */
  49633. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  49634. var wm;
  49635. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49636. if (mesh) {
  49637. wm = mesh.getWorldMatrix();
  49638. }
  49639. this._skeleton.computeAbsoluteTransforms();
  49640. var tmat = Bone._tmpMats[0];
  49641. if (mesh) {
  49642. tmat.copyFrom(this.getAbsoluteTransform());
  49643. tmat.multiplyToRef(wm, tmat);
  49644. }
  49645. else {
  49646. tmat = this.getAbsoluteTransform();
  49647. }
  49648. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  49649. };
  49650. /**
  49651. * Get the local position of a point that is in world space.
  49652. * @param position The world position
  49653. * @param mesh The mesh that this bone is attached to.
  49654. * @returns The local position
  49655. */
  49656. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  49657. var result = BABYLON.Vector3.Zero();
  49658. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  49659. return result;
  49660. };
  49661. /**
  49662. * Get the local position of a point that is in world space and copy it to the result param.
  49663. * @param position The world position
  49664. * @param mesh The mesh that this bone is attached to.
  49665. * @param result The vector3 that the local position should be copied to.
  49666. */
  49667. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  49668. var wm;
  49669. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49670. if (mesh) {
  49671. wm = mesh.getWorldMatrix();
  49672. }
  49673. this._skeleton.computeAbsoluteTransforms();
  49674. var tmat = Bone._tmpMats[0];
  49675. tmat.copyFrom(this.getAbsoluteTransform());
  49676. if (mesh) {
  49677. tmat.multiplyToRef(wm, tmat);
  49678. }
  49679. tmat.invert();
  49680. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  49681. };
  49682. return Bone;
  49683. }(BABYLON.Node));
  49684. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  49685. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  49686. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  49687. BABYLON.Bone = Bone;
  49688. })(BABYLON || (BABYLON = {}));
  49689. //# sourceMappingURL=babylon.bone.js.map
  49690. var BABYLON;
  49691. (function (BABYLON) {
  49692. var BoneIKController = (function () {
  49693. function BoneIKController(mesh, bone, options) {
  49694. this.targetPosition = BABYLON.Vector3.Zero();
  49695. this.poleTargetPosition = BABYLON.Vector3.Zero();
  49696. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  49697. this.poleAngle = 0;
  49698. this.slerpAmount = 1;
  49699. this._bone1Quat = BABYLON.Quaternion.Identity();
  49700. this._bone1Mat = BABYLON.Matrix.Identity();
  49701. this._bone2Ang = Math.PI;
  49702. this._maxAngle = Math.PI;
  49703. this._rightHandedSystem = false;
  49704. this._bendAxis = BABYLON.Vector3.Right();
  49705. this._slerping = false;
  49706. this._adjustRoll = 0;
  49707. this._bone2 = bone;
  49708. this._bone1 = bone.getParent();
  49709. this.mesh = mesh;
  49710. var bonePos = bone.getPosition();
  49711. if (bone.getAbsoluteTransform().determinant() > 0) {
  49712. this._rightHandedSystem = true;
  49713. this._bendAxis.x = 0;
  49714. this._bendAxis.y = 0;
  49715. this._bendAxis.z = -1;
  49716. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  49717. this._adjustRoll = Math.PI * .5;
  49718. this._bendAxis.z = 1;
  49719. }
  49720. }
  49721. if (this._bone1.length) {
  49722. var boneScale1 = this._bone1.getScale();
  49723. var boneScale2 = this._bone2.getScale();
  49724. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  49725. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  49726. }
  49727. else if (this._bone1.children[0]) {
  49728. mesh.computeWorldMatrix(true);
  49729. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  49730. var pos2 = this._bone2.getAbsolutePosition(mesh);
  49731. var pos3 = this._bone1.getAbsolutePosition(mesh);
  49732. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  49733. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  49734. }
  49735. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  49736. this.maxAngle = Math.PI;
  49737. if (options) {
  49738. if (options.targetMesh) {
  49739. this.targetMesh = options.targetMesh;
  49740. this.targetMesh.computeWorldMatrix(true);
  49741. }
  49742. if (options.poleTargetMesh) {
  49743. this.poleTargetMesh = options.poleTargetMesh;
  49744. this.poleTargetMesh.computeWorldMatrix(true);
  49745. }
  49746. else if (options.poleTargetBone) {
  49747. this.poleTargetBone = options.poleTargetBone;
  49748. }
  49749. else if (this._bone1.getParent()) {
  49750. this.poleTargetBone = this._bone1.getParent();
  49751. }
  49752. if (options.poleTargetLocalOffset) {
  49753. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  49754. }
  49755. if (options.poleAngle) {
  49756. this.poleAngle = options.poleAngle;
  49757. }
  49758. if (options.bendAxis) {
  49759. this._bendAxis.copyFrom(options.bendAxis);
  49760. }
  49761. if (options.maxAngle) {
  49762. this.maxAngle = options.maxAngle;
  49763. }
  49764. if (options.slerpAmount) {
  49765. this.slerpAmount = options.slerpAmount;
  49766. }
  49767. }
  49768. }
  49769. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  49770. get: function () {
  49771. return this._maxAngle;
  49772. },
  49773. set: function (value) {
  49774. this._setMaxAngle(value);
  49775. },
  49776. enumerable: true,
  49777. configurable: true
  49778. });
  49779. BoneIKController.prototype._setMaxAngle = function (ang) {
  49780. if (ang < 0) {
  49781. ang = 0;
  49782. }
  49783. if (ang > Math.PI || ang == undefined) {
  49784. ang = Math.PI;
  49785. }
  49786. this._maxAngle = ang;
  49787. var a = this._bone1Length;
  49788. var b = this._bone2Length;
  49789. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  49790. };
  49791. BoneIKController.prototype.update = function () {
  49792. var bone1 = this._bone1;
  49793. var target = this.targetPosition;
  49794. var poleTarget = this.poleTargetPosition;
  49795. var mat1 = BoneIKController._tmpMats[0];
  49796. var mat2 = BoneIKController._tmpMats[1];
  49797. if (this.targetMesh) {
  49798. target.copyFrom(this.targetMesh.getAbsolutePosition());
  49799. }
  49800. if (this.poleTargetBone) {
  49801. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  49802. }
  49803. else if (this.poleTargetMesh) {
  49804. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  49805. }
  49806. var bonePos = BoneIKController._tmpVecs[0];
  49807. var zaxis = BoneIKController._tmpVecs[1];
  49808. var xaxis = BoneIKController._tmpVecs[2];
  49809. var yaxis = BoneIKController._tmpVecs[3];
  49810. var upAxis = BoneIKController._tmpVecs[4];
  49811. var _tmpQuat = BoneIKController._tmpQuat;
  49812. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  49813. poleTarget.subtractToRef(bonePos, upAxis);
  49814. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  49815. upAxis.y = 1;
  49816. }
  49817. else {
  49818. upAxis.normalize();
  49819. }
  49820. target.subtractToRef(bonePos, yaxis);
  49821. yaxis.normalize();
  49822. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  49823. zaxis.normalize();
  49824. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  49825. xaxis.normalize();
  49826. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  49827. var a = this._bone1Length;
  49828. var b = this._bone2Length;
  49829. var c = BABYLON.Vector3.Distance(bonePos, target);
  49830. if (this._maxReach > 0) {
  49831. c = Math.min(this._maxReach, c);
  49832. }
  49833. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  49834. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  49835. if (acosa > 1) {
  49836. acosa = 1;
  49837. }
  49838. if (acosb > 1) {
  49839. acosb = 1;
  49840. }
  49841. if (acosa < -1) {
  49842. acosa = -1;
  49843. }
  49844. if (acosb < -1) {
  49845. acosb = -1;
  49846. }
  49847. var angA = Math.acos(acosa);
  49848. var angB = Math.acos(acosb);
  49849. var angC = -angA - angB;
  49850. if (this._rightHandedSystem) {
  49851. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  49852. mat2.multiplyToRef(mat1, mat1);
  49853. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  49854. mat2.multiplyToRef(mat1, mat1);
  49855. }
  49856. else {
  49857. var _tmpVec = BoneIKController._tmpVecs[5];
  49858. _tmpVec.copyFrom(this._bendAxis);
  49859. _tmpVec.x *= -1;
  49860. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  49861. mat2.multiplyToRef(mat1, mat1);
  49862. }
  49863. if (this.poleAngle) {
  49864. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  49865. mat1.multiplyToRef(mat2, mat1);
  49866. }
  49867. if (this.slerpAmount < 1) {
  49868. if (!this._slerping) {
  49869. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  49870. }
  49871. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  49872. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  49873. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  49874. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  49875. this._slerping = true;
  49876. }
  49877. else {
  49878. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  49879. this._bone1Mat.copyFrom(mat1);
  49880. this._slerping = false;
  49881. }
  49882. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  49883. this._bone2Ang = angC;
  49884. };
  49885. return BoneIKController;
  49886. }());
  49887. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  49888. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  49889. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  49890. BABYLON.BoneIKController = BoneIKController;
  49891. })(BABYLON || (BABYLON = {}));
  49892. //# sourceMappingURL=babylon.boneIKController.js.map
  49893. var BABYLON;
  49894. (function (BABYLON) {
  49895. var BoneLookController = (function () {
  49896. /**
  49897. * Create a BoneLookController
  49898. * @param mesh the mesh that the bone belongs to
  49899. * @param bone the bone that will be looking to the target
  49900. * @param target the target Vector3 to look at
  49901. * @param settings optional settings:
  49902. * - maxYaw: the maximum angle the bone will yaw to
  49903. * - minYaw: the minimum angle the bone will yaw to
  49904. * - maxPitch: the maximum angle the bone will pitch to
  49905. * - minPitch: the minimum angle the bone will yaw to
  49906. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  49907. * - upAxis: the up axis of the coordinate system
  49908. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  49909. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  49910. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  49911. * - adjustYaw: used to make an adjustment to the yaw of the bone
  49912. * - adjustPitch: used to make an adjustment to the pitch of the bone
  49913. * - adjustRoll: used to make an adjustment to the roll of the bone
  49914. **/
  49915. function BoneLookController(mesh, bone, target, options) {
  49916. /**
  49917. * The up axis of the coordinate system that is used when the bone is rotated.
  49918. */
  49919. this.upAxis = BABYLON.Vector3.Up();
  49920. /**
  49921. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  49922. */
  49923. this.upAxisSpace = BABYLON.Space.LOCAL;
  49924. /**
  49925. * Used to make an adjustment to the yaw of the bone.
  49926. */
  49927. this.adjustYaw = 0;
  49928. /**
  49929. * Used to make an adjustment to the pitch of the bone.
  49930. */
  49931. this.adjustPitch = 0;
  49932. /**
  49933. * Used to make an adjustment to the roll of the bone.
  49934. */
  49935. this.adjustRoll = 0;
  49936. /**
  49937. * 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).
  49938. */
  49939. this.slerpAmount = 1;
  49940. this._boneQuat = BABYLON.Quaternion.Identity();
  49941. this._slerping = false;
  49942. this._firstFrameSkipped = false;
  49943. this._fowardAxis = BABYLON.Vector3.Forward();
  49944. this.mesh = mesh;
  49945. this.bone = bone;
  49946. this.target = target;
  49947. if (options) {
  49948. if (options.adjustYaw) {
  49949. this.adjustYaw = options.adjustYaw;
  49950. }
  49951. if (options.adjustPitch) {
  49952. this.adjustPitch = options.adjustPitch;
  49953. }
  49954. if (options.adjustRoll) {
  49955. this.adjustRoll = options.adjustRoll;
  49956. }
  49957. if (options.maxYaw != null) {
  49958. this.maxYaw = options.maxYaw;
  49959. }
  49960. else {
  49961. this.maxYaw = Math.PI;
  49962. }
  49963. if (options.minYaw != null) {
  49964. this.minYaw = options.minYaw;
  49965. }
  49966. else {
  49967. this.minYaw = -Math.PI;
  49968. }
  49969. if (options.maxPitch != null) {
  49970. this.maxPitch = options.maxPitch;
  49971. }
  49972. else {
  49973. this.maxPitch = Math.PI;
  49974. }
  49975. if (options.minPitch != null) {
  49976. this.minPitch = options.minPitch;
  49977. }
  49978. else {
  49979. this.minPitch = -Math.PI;
  49980. }
  49981. if (options.slerpAmount != null) {
  49982. this.slerpAmount = options.slerpAmount;
  49983. }
  49984. if (options.upAxis != null) {
  49985. this.upAxis = options.upAxis;
  49986. }
  49987. if (options.upAxisSpace != null) {
  49988. this.upAxisSpace = options.upAxisSpace;
  49989. }
  49990. if (options.yawAxis != null || options.pitchAxis != null) {
  49991. var newYawAxis = BABYLON.Axis.Y;
  49992. var newPitchAxis = BABYLON.Axis.X;
  49993. if (options.yawAxis != null) {
  49994. newYawAxis = options.yawAxis.clone();
  49995. newYawAxis.normalize();
  49996. }
  49997. if (options.pitchAxis != null) {
  49998. newPitchAxis = options.pitchAxis.clone();
  49999. newPitchAxis.normalize();
  50000. }
  50001. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  50002. this._transformYawPitch = BABYLON.Matrix.Identity();
  50003. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  50004. this._transformYawPitchInv = this._transformYawPitch.clone();
  50005. this._transformYawPitch.invert();
  50006. }
  50007. }
  50008. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  50009. this.upAxisSpace = BABYLON.Space.LOCAL;
  50010. }
  50011. }
  50012. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  50013. /**
  50014. * Get/set the minimum yaw angle that the bone can look to.
  50015. */
  50016. get: function () {
  50017. return this._minYaw;
  50018. },
  50019. set: function (value) {
  50020. this._minYaw = value;
  50021. this._minYawSin = Math.sin(value);
  50022. this._minYawCos = Math.cos(value);
  50023. if (this._maxYaw != null) {
  50024. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  50025. this._yawRange = this._maxYaw - this._minYaw;
  50026. }
  50027. },
  50028. enumerable: true,
  50029. configurable: true
  50030. });
  50031. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  50032. /**
  50033. * Get/set the maximum yaw angle that the bone can look to.
  50034. */
  50035. get: function () {
  50036. return this._maxYaw;
  50037. },
  50038. set: function (value) {
  50039. this._maxYaw = value;
  50040. this._maxYawSin = Math.sin(value);
  50041. this._maxYawCos = Math.cos(value);
  50042. if (this._minYaw != null) {
  50043. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  50044. this._yawRange = this._maxYaw - this._minYaw;
  50045. }
  50046. },
  50047. enumerable: true,
  50048. configurable: true
  50049. });
  50050. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  50051. /**
  50052. * Get/set the minimum pitch angle that the bone can look to.
  50053. */
  50054. get: function () {
  50055. return this._minPitch;
  50056. },
  50057. set: function (value) {
  50058. this._minPitch = value;
  50059. this._minPitchTan = Math.tan(value);
  50060. },
  50061. enumerable: true,
  50062. configurable: true
  50063. });
  50064. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  50065. /**
  50066. * Get/set the maximum pitch angle that the bone can look to.
  50067. */
  50068. get: function () {
  50069. return this._maxPitch;
  50070. },
  50071. set: function (value) {
  50072. this._maxPitch = value;
  50073. this._maxPitchTan = Math.tan(value);
  50074. },
  50075. enumerable: true,
  50076. configurable: true
  50077. });
  50078. /**
  50079. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  50080. */
  50081. BoneLookController.prototype.update = function () {
  50082. //skip the first frame when slerping so that the mesh rotation is correct
  50083. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  50084. this._firstFrameSkipped = true;
  50085. return;
  50086. }
  50087. var bone = this.bone;
  50088. var bonePos = BoneLookController._tmpVecs[0];
  50089. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  50090. var target = this.target;
  50091. var _tmpMat1 = BoneLookController._tmpMats[0];
  50092. var _tmpMat2 = BoneLookController._tmpMats[1];
  50093. var mesh = this.mesh;
  50094. var parentBone = bone.getParent();
  50095. var upAxis = BoneLookController._tmpVecs[1];
  50096. upAxis.copyFrom(this.upAxis);
  50097. if (this.upAxisSpace == BABYLON.Space.BONE) {
  50098. if (this._transformYawPitch) {
  50099. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  50100. }
  50101. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  50102. }
  50103. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  50104. mesh.getDirectionToRef(upAxis, upAxis);
  50105. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  50106. upAxis.normalize();
  50107. }
  50108. }
  50109. var checkYaw = false;
  50110. var checkPitch = false;
  50111. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  50112. checkYaw = true;
  50113. }
  50114. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  50115. checkPitch = true;
  50116. }
  50117. if (checkYaw || checkPitch) {
  50118. var spaceMat = BoneLookController._tmpMats[2];
  50119. var spaceMatInv = BoneLookController._tmpMats[3];
  50120. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  50121. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  50122. }
  50123. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  50124. spaceMat.copyFrom(mesh.getWorldMatrix());
  50125. }
  50126. else {
  50127. var forwardAxis = BoneLookController._tmpVecs[2];
  50128. forwardAxis.copyFrom(this._fowardAxis);
  50129. if (this._transformYawPitch) {
  50130. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  50131. }
  50132. if (parentBone) {
  50133. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  50134. }
  50135. else {
  50136. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  50137. }
  50138. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  50139. rightAxis.normalize();
  50140. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  50141. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  50142. }
  50143. spaceMat.invertToRef(spaceMatInv);
  50144. var xzlen;
  50145. if (checkPitch) {
  50146. var localTarget = BoneLookController._tmpVecs[3];
  50147. target.subtractToRef(bonePos, localTarget);
  50148. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  50149. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  50150. var pitch = Math.atan2(localTarget.y, xzlen);
  50151. var newPitch = pitch;
  50152. if (pitch > this._maxPitch) {
  50153. localTarget.y = this._maxPitchTan * xzlen;
  50154. newPitch = this._maxPitch;
  50155. }
  50156. else if (pitch < this._minPitch) {
  50157. localTarget.y = this._minPitchTan * xzlen;
  50158. newPitch = this._minPitch;
  50159. }
  50160. if (pitch != newPitch) {
  50161. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  50162. localTarget.addInPlace(bonePos);
  50163. target = localTarget;
  50164. }
  50165. }
  50166. if (checkYaw) {
  50167. var localTarget = BoneLookController._tmpVecs[4];
  50168. target.subtractToRef(bonePos, localTarget);
  50169. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  50170. var yaw = Math.atan2(localTarget.x, localTarget.z);
  50171. var newYaw = yaw;
  50172. if (yaw > this._maxYaw || yaw < this._minYaw) {
  50173. if (xzlen == null) {
  50174. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  50175. }
  50176. if (this._yawRange > Math.PI) {
  50177. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  50178. localTarget.z = this._maxYawCos * xzlen;
  50179. localTarget.x = this._maxYawSin * xzlen;
  50180. newYaw = this._maxYaw;
  50181. }
  50182. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  50183. localTarget.z = this._minYawCos * xzlen;
  50184. localTarget.x = this._minYawSin * xzlen;
  50185. newYaw = this._minYaw;
  50186. }
  50187. }
  50188. else {
  50189. if (yaw > this._maxYaw) {
  50190. localTarget.z = this._maxYawCos * xzlen;
  50191. localTarget.x = this._maxYawSin * xzlen;
  50192. newYaw = this._maxYaw;
  50193. }
  50194. else if (yaw < this._minYaw) {
  50195. localTarget.z = this._minYawCos * xzlen;
  50196. localTarget.x = this._minYawSin * xzlen;
  50197. newYaw = this._minYaw;
  50198. }
  50199. }
  50200. }
  50201. if (this._slerping && this._yawRange > Math.PI) {
  50202. //are we going to be crossing into the min/max region?
  50203. var boneFwd = BoneLookController._tmpVecs[8];
  50204. boneFwd.copyFrom(BABYLON.Axis.Z);
  50205. if (this._transformYawPitch) {
  50206. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  50207. }
  50208. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  50209. this._boneQuat.toRotationMatrix(boneRotMat);
  50210. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  50211. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  50212. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  50213. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  50214. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  50215. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  50216. if (angBtwTar > angBtwMidYaw) {
  50217. if (xzlen == null) {
  50218. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  50219. }
  50220. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  50221. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  50222. if (angBtwMin < angBtwMax) {
  50223. newYaw = boneYaw + Math.PI * .75;
  50224. localTarget.z = Math.cos(newYaw) * xzlen;
  50225. localTarget.x = Math.sin(newYaw) * xzlen;
  50226. }
  50227. else {
  50228. newYaw = boneYaw - Math.PI * .75;
  50229. localTarget.z = Math.cos(newYaw) * xzlen;
  50230. localTarget.x = Math.sin(newYaw) * xzlen;
  50231. }
  50232. }
  50233. }
  50234. if (yaw != newYaw) {
  50235. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  50236. localTarget.addInPlace(bonePos);
  50237. target = localTarget;
  50238. }
  50239. }
  50240. }
  50241. var zaxis = BoneLookController._tmpVecs[5];
  50242. var xaxis = BoneLookController._tmpVecs[6];
  50243. var yaxis = BoneLookController._tmpVecs[7];
  50244. var _tmpQuat = BoneLookController._tmpQuat;
  50245. target.subtractToRef(bonePos, zaxis);
  50246. zaxis.normalize();
  50247. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  50248. xaxis.normalize();
  50249. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  50250. yaxis.normalize();
  50251. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  50252. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  50253. return;
  50254. }
  50255. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  50256. return;
  50257. }
  50258. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  50259. return;
  50260. }
  50261. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  50262. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  50263. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  50264. }
  50265. if (this.slerpAmount < 1) {
  50266. if (!this._slerping) {
  50267. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  50268. }
  50269. if (this._transformYawPitch) {
  50270. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  50271. }
  50272. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  50273. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  50274. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  50275. this._slerping = true;
  50276. }
  50277. else {
  50278. if (this._transformYawPitch) {
  50279. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  50280. }
  50281. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  50282. this._slerping = false;
  50283. }
  50284. };
  50285. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  50286. var angDiff = ang2 - ang1;
  50287. angDiff %= Math.PI * 2;
  50288. if (angDiff > Math.PI) {
  50289. angDiff -= Math.PI * 2;
  50290. }
  50291. else if (angDiff < -Math.PI) {
  50292. angDiff += Math.PI * 2;
  50293. }
  50294. return angDiff;
  50295. };
  50296. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  50297. ang1 %= (2 * Math.PI);
  50298. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  50299. ang2 %= (2 * Math.PI);
  50300. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  50301. var ab = 0;
  50302. if (ang1 < ang2) {
  50303. ab = ang2 - ang1;
  50304. }
  50305. else {
  50306. ab = ang1 - ang2;
  50307. }
  50308. if (ab > Math.PI) {
  50309. ab = Math.PI * 2 - ab;
  50310. }
  50311. return ab;
  50312. };
  50313. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  50314. ang %= (2 * Math.PI);
  50315. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  50316. ang1 %= (2 * Math.PI);
  50317. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  50318. ang2 %= (2 * Math.PI);
  50319. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  50320. if (ang1 < ang2) {
  50321. if (ang > ang1 && ang < ang2) {
  50322. return true;
  50323. }
  50324. }
  50325. else {
  50326. if (ang > ang2 && ang < ang1) {
  50327. return true;
  50328. }
  50329. }
  50330. return false;
  50331. };
  50332. return BoneLookController;
  50333. }());
  50334. 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()];
  50335. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  50336. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  50337. BABYLON.BoneLookController = BoneLookController;
  50338. })(BABYLON || (BABYLON = {}));
  50339. //# sourceMappingURL=babylon.boneLookController.js.map
  50340. var BABYLON;
  50341. (function (BABYLON) {
  50342. var Skeleton = (function () {
  50343. function Skeleton(name, id, scene) {
  50344. this.name = name;
  50345. this.id = id;
  50346. this.bones = new Array();
  50347. this.needInitialSkinMatrix = false;
  50348. this._isDirty = true;
  50349. this._meshesWithPoseMatrix = new Array();
  50350. this._identity = BABYLON.Matrix.Identity();
  50351. this._ranges = {};
  50352. this._lastAbsoluteTransformsUpdateId = -1;
  50353. // Events
  50354. /**
  50355. * An event triggered before computing the skeleton's matrices
  50356. * @type {BABYLON.Observable}
  50357. */
  50358. this.onBeforeComputeObservable = new BABYLON.Observable();
  50359. this.bones = [];
  50360. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50361. scene.skeletons.push(this);
  50362. //make sure it will recalculate the matrix next time prepare is called.
  50363. this._isDirty = true;
  50364. }
  50365. // Members
  50366. Skeleton.prototype.getTransformMatrices = function (mesh) {
  50367. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  50368. return mesh._bonesTransformMatrices;
  50369. }
  50370. if (!this._transformMatrices) {
  50371. this.prepare();
  50372. }
  50373. return this._transformMatrices;
  50374. };
  50375. Skeleton.prototype.getScene = function () {
  50376. return this._scene;
  50377. };
  50378. // Methods
  50379. /**
  50380. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  50381. */
  50382. Skeleton.prototype.toString = function (fullDetails) {
  50383. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  50384. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50385. if (fullDetails) {
  50386. ret += ", Ranges: {";
  50387. var first = true;
  50388. for (var name_1 in this._ranges) {
  50389. if (first) {
  50390. ret += ", ";
  50391. first = false;
  50392. }
  50393. ret += name_1;
  50394. }
  50395. ret += "}";
  50396. }
  50397. return ret;
  50398. };
  50399. /**
  50400. * Get bone's index searching by name
  50401. * @param {string} name is bone's name to search for
  50402. * @return {number} Indice of the bone. Returns -1 if not found
  50403. */
  50404. Skeleton.prototype.getBoneIndexByName = function (name) {
  50405. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  50406. if (this.bones[boneIndex].name === name) {
  50407. return boneIndex;
  50408. }
  50409. }
  50410. return -1;
  50411. };
  50412. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  50413. // check name not already in use
  50414. if (!this._ranges[name]) {
  50415. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  50416. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  50417. if (this.bones[i].animations[0]) {
  50418. this.bones[i].animations[0].createRange(name, from, to);
  50419. }
  50420. }
  50421. }
  50422. };
  50423. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  50424. if (deleteFrames === void 0) { deleteFrames = true; }
  50425. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  50426. if (this.bones[i].animations[0]) {
  50427. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  50428. }
  50429. }
  50430. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  50431. };
  50432. Skeleton.prototype.getAnimationRange = function (name) {
  50433. return this._ranges[name];
  50434. };
  50435. /**
  50436. * Returns as an Array, all AnimationRanges defined on this skeleton
  50437. */
  50438. Skeleton.prototype.getAnimationRanges = function () {
  50439. var animationRanges = [];
  50440. var name;
  50441. var i = 0;
  50442. for (name in this._ranges) {
  50443. animationRanges[i] = this._ranges[name];
  50444. i++;
  50445. }
  50446. return animationRanges;
  50447. };
  50448. /**
  50449. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  50450. */
  50451. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  50452. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  50453. if (this._ranges[name] || !source.getAnimationRange(name)) {
  50454. return false;
  50455. }
  50456. var ret = true;
  50457. var frameOffset = this._getHighestAnimationFrame() + 1;
  50458. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  50459. var boneDict = {};
  50460. var sourceBones = source.bones;
  50461. var nBones;
  50462. var i;
  50463. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  50464. boneDict[sourceBones[i].name] = sourceBones[i];
  50465. }
  50466. if (this.bones.length !== sourceBones.length) {
  50467. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  50468. ret = false;
  50469. }
  50470. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  50471. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  50472. var boneName = this.bones[i].name;
  50473. var sourceBone = boneDict[boneName];
  50474. if (sourceBone) {
  50475. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  50476. }
  50477. else {
  50478. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  50479. ret = false;
  50480. }
  50481. }
  50482. // do not call createAnimationRange(), since it also is done to bones, which was already done
  50483. var range = source.getAnimationRange(name);
  50484. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  50485. return ret;
  50486. };
  50487. Skeleton.prototype.returnToRest = function () {
  50488. for (var index = 0; index < this.bones.length; index++) {
  50489. this.bones[index].returnToRest();
  50490. }
  50491. };
  50492. Skeleton.prototype._getHighestAnimationFrame = function () {
  50493. var ret = 0;
  50494. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  50495. if (this.bones[i].animations[0]) {
  50496. var highest = this.bones[i].animations[0].getHighestFrame();
  50497. if (ret < highest) {
  50498. ret = highest;
  50499. }
  50500. }
  50501. }
  50502. return ret;
  50503. };
  50504. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  50505. var range = this.getAnimationRange(name);
  50506. if (!range) {
  50507. return null;
  50508. }
  50509. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  50510. };
  50511. Skeleton.prototype._markAsDirty = function () {
  50512. this._isDirty = true;
  50513. };
  50514. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  50515. this._meshesWithPoseMatrix.push(mesh);
  50516. };
  50517. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  50518. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  50519. if (index > -1) {
  50520. this._meshesWithPoseMatrix.splice(index, 1);
  50521. }
  50522. };
  50523. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  50524. this.onBeforeComputeObservable.notifyObservers(this);
  50525. for (var index = 0; index < this.bones.length; index++) {
  50526. var bone = this.bones[index];
  50527. var parentBone = bone.getParent();
  50528. if (parentBone) {
  50529. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  50530. }
  50531. else {
  50532. if (initialSkinMatrix) {
  50533. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  50534. }
  50535. else {
  50536. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  50537. }
  50538. }
  50539. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  50540. }
  50541. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  50542. };
  50543. Skeleton.prototype.prepare = function () {
  50544. if (!this._isDirty) {
  50545. return;
  50546. }
  50547. if (this.needInitialSkinMatrix) {
  50548. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  50549. var mesh = this._meshesWithPoseMatrix[index];
  50550. var poseMatrix = mesh.getPoseMatrix();
  50551. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  50552. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  50553. }
  50554. if (this._synchronizedWithMesh !== mesh) {
  50555. this._synchronizedWithMesh = mesh;
  50556. // Prepare bones
  50557. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  50558. var bone = this.bones[boneIndex];
  50559. if (!bone.getParent()) {
  50560. var matrix = bone.getBaseMatrix();
  50561. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  50562. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  50563. }
  50564. }
  50565. }
  50566. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  50567. }
  50568. }
  50569. else {
  50570. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  50571. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  50572. }
  50573. this._computeTransformMatrices(this._transformMatrices, null);
  50574. }
  50575. this._isDirty = false;
  50576. this._scene._activeBones.addCount(this.bones.length, false);
  50577. };
  50578. Skeleton.prototype.getAnimatables = function () {
  50579. if (!this._animatables || this._animatables.length !== this.bones.length) {
  50580. this._animatables = [];
  50581. for (var index = 0; index < this.bones.length; index++) {
  50582. this._animatables.push(this.bones[index]);
  50583. }
  50584. }
  50585. return this._animatables;
  50586. };
  50587. Skeleton.prototype.clone = function (name, id) {
  50588. var result = new Skeleton(name, id || name, this._scene);
  50589. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  50590. for (var index = 0; index < this.bones.length; index++) {
  50591. var source = this.bones[index];
  50592. var parentBone = null;
  50593. if (source.getParent()) {
  50594. var parentIndex = this.bones.indexOf(source.getParent());
  50595. parentBone = result.bones[parentIndex];
  50596. }
  50597. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  50598. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  50599. }
  50600. if (this._ranges) {
  50601. result._ranges = {};
  50602. for (var rangeName in this._ranges) {
  50603. result._ranges[rangeName] = this._ranges[rangeName].clone();
  50604. }
  50605. }
  50606. this._isDirty = true;
  50607. return result;
  50608. };
  50609. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  50610. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  50611. this.bones.forEach(function (bone) {
  50612. bone.animations.forEach(function (animation) {
  50613. animation.enableBlending = true;
  50614. animation.blendingSpeed = blendingSpeed;
  50615. });
  50616. });
  50617. };
  50618. Skeleton.prototype.dispose = function () {
  50619. this._meshesWithPoseMatrix = [];
  50620. // Animations
  50621. this.getScene().stopAnimation(this);
  50622. // Remove from scene
  50623. this.getScene().removeSkeleton(this);
  50624. };
  50625. Skeleton.prototype.serialize = function () {
  50626. var serializationObject = {};
  50627. serializationObject.name = this.name;
  50628. serializationObject.id = this.id;
  50629. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  50630. serializationObject.bones = [];
  50631. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  50632. for (var index = 0; index < this.bones.length; index++) {
  50633. var bone = this.bones[index];
  50634. var serializedBone = {
  50635. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  50636. name: bone.name,
  50637. matrix: bone.getBaseMatrix().toArray(),
  50638. rest: bone.getRestPose().toArray()
  50639. };
  50640. serializationObject.bones.push(serializedBone);
  50641. if (bone.length) {
  50642. serializedBone.length = bone.length;
  50643. }
  50644. if (bone.animations && bone.animations.length > 0) {
  50645. serializedBone.animation = bone.animations[0].serialize();
  50646. }
  50647. serializationObject.ranges = [];
  50648. for (var name in this._ranges) {
  50649. var range = {};
  50650. range.name = name;
  50651. range.from = this._ranges[name].from;
  50652. range.to = this._ranges[name].to;
  50653. serializationObject.ranges.push(range);
  50654. }
  50655. }
  50656. return serializationObject;
  50657. };
  50658. Skeleton.Parse = function (parsedSkeleton, scene) {
  50659. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  50660. if (parsedSkeleton.dimensionsAtRest) {
  50661. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  50662. }
  50663. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  50664. var index;
  50665. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  50666. var parsedBone = parsedSkeleton.bones[index];
  50667. var parentBone = null;
  50668. if (parsedBone.parentBoneIndex > -1) {
  50669. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  50670. }
  50671. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  50672. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  50673. if (parsedBone.length) {
  50674. bone.length = parsedBone.length;
  50675. }
  50676. if (parsedBone.animation) {
  50677. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  50678. }
  50679. }
  50680. // placed after bones, so createAnimationRange can cascade down
  50681. if (parsedSkeleton.ranges) {
  50682. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  50683. var data = parsedSkeleton.ranges[index];
  50684. skeleton.createAnimationRange(data.name, data.from, data.to);
  50685. }
  50686. }
  50687. return skeleton;
  50688. };
  50689. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  50690. if (forceUpdate === void 0) { forceUpdate = false; }
  50691. var renderId = this._scene.getRenderId();
  50692. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  50693. this.bones[0].computeAbsoluteTransforms();
  50694. this._lastAbsoluteTransformsUpdateId = renderId;
  50695. }
  50696. };
  50697. Skeleton.prototype.getPoseMatrix = function () {
  50698. var poseMatrix;
  50699. if (this._meshesWithPoseMatrix.length > 0) {
  50700. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  50701. }
  50702. return poseMatrix;
  50703. };
  50704. return Skeleton;
  50705. }());
  50706. BABYLON.Skeleton = Skeleton;
  50707. })(BABYLON || (BABYLON = {}));
  50708. //# sourceMappingURL=babylon.skeleton.js.map
  50709. var BABYLON;
  50710. (function (BABYLON) {
  50711. var Internals;
  50712. (function (Internals) {
  50713. var FileFaceOrientation = (function () {
  50714. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  50715. this.name = name;
  50716. this.worldAxisForNormal = worldAxisForNormal;
  50717. this.worldAxisForFileX = worldAxisForFileX;
  50718. this.worldAxisForFileY = worldAxisForFileY;
  50719. }
  50720. return FileFaceOrientation;
  50721. }());
  50722. ;
  50723. /**
  50724. * Helper class dealing with the extraction of spherical polynomial dataArray
  50725. * from a cube map.
  50726. */
  50727. var CubeMapToSphericalPolynomialTools = (function () {
  50728. function CubeMapToSphericalPolynomialTools() {
  50729. }
  50730. /**
  50731. * Converts a cubemap to the according Spherical Polynomial data.
  50732. * This extracts the first 3 orders only as they are the only one used in the lighting.
  50733. *
  50734. * @param cubeInfo The Cube map to extract the information from.
  50735. * @return The Spherical Polynomial data.
  50736. */
  50737. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  50738. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  50739. var totalSolidAngle = 0.0;
  50740. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  50741. var du = 2.0 / cubeInfo.size;
  50742. var dv = du;
  50743. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  50744. var minUV = du * 0.5 - 1.0;
  50745. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50746. var fileFace = this.FileFaces[faceIndex];
  50747. var dataArray = cubeInfo[fileFace.name];
  50748. var v = minUV;
  50749. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  50750. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  50751. // Because SP is still linear, so summation is fine in that basis.
  50752. for (var y = 0; y < cubeInfo.size; y++) {
  50753. var u = minUV;
  50754. for (var x = 0; x < cubeInfo.size; x++) {
  50755. // World direction (not normalised)
  50756. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  50757. worldDirection.normalize();
  50758. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  50759. if (1) {
  50760. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  50761. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  50762. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  50763. var color = new BABYLON.Color3(r, g, b);
  50764. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50765. }
  50766. else {
  50767. if (faceIndex == 0) {
  50768. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50769. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50770. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50771. }
  50772. else if (faceIndex == 1) {
  50773. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50774. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50775. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50776. }
  50777. else if (faceIndex == 2) {
  50778. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50779. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50780. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50781. }
  50782. else if (faceIndex == 3) {
  50783. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50784. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50785. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50786. }
  50787. else if (faceIndex == 4) {
  50788. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50789. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50790. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50791. }
  50792. else if (faceIndex == 5) {
  50793. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50794. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50795. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50796. }
  50797. 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]);
  50798. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50799. }
  50800. totalSolidAngle += deltaSolidAngle;
  50801. u += du;
  50802. }
  50803. v += dv;
  50804. }
  50805. }
  50806. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  50807. var correction = correctSolidAngle / totalSolidAngle;
  50808. sphericalHarmonics.scale(correction);
  50809. // Additionally scale by pi -- audit needed
  50810. sphericalHarmonics.scale(1.0 / Math.PI);
  50811. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  50812. };
  50813. return CubeMapToSphericalPolynomialTools;
  50814. }());
  50815. CubeMapToSphericalPolynomialTools.FileFaces = [
  50816. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  50817. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  50818. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  50819. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  50820. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  50821. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  50822. ];
  50823. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  50824. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50825. })(BABYLON || (BABYLON = {}));
  50826. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  50827. var BABYLON;
  50828. (function (BABYLON) {
  50829. var Internals;
  50830. (function (Internals) {
  50831. /**
  50832. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  50833. */
  50834. var PanoramaToCubeMapTools = (function () {
  50835. function PanoramaToCubeMapTools() {
  50836. }
  50837. /**
  50838. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  50839. *
  50840. * @param float32Array The source data.
  50841. * @param inputWidth The width of the input panorama.
  50842. * @param inputhHeight The height of the input panorama.
  50843. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  50844. * @return The cubemap data
  50845. */
  50846. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  50847. if (!float32Array) {
  50848. throw "ConvertPanoramaToCubemap: input cannot be null";
  50849. }
  50850. if (float32Array.length != inputWidth * inputHeight * 3) {
  50851. throw "ConvertPanoramaToCubemap: input size is wrong";
  50852. }
  50853. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  50854. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  50855. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  50856. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  50857. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  50858. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  50859. return {
  50860. front: textureFront,
  50861. back: textureBack,
  50862. left: textureLeft,
  50863. right: textureRight,
  50864. up: textureUp,
  50865. down: textureDown,
  50866. size: size
  50867. };
  50868. };
  50869. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  50870. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  50871. var textureArray = new Float32Array(buffer);
  50872. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  50873. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  50874. var dy = 1 / texSize;
  50875. var fy = 0;
  50876. for (var y = 0; y < texSize; y++) {
  50877. var xv1 = faceData[0];
  50878. var xv2 = faceData[2];
  50879. for (var x = 0; x < texSize; x++) {
  50880. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  50881. v.normalize();
  50882. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  50883. // 3 channels per pixels
  50884. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  50885. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  50886. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  50887. xv1 = xv1.add(rotDX1);
  50888. xv2 = xv2.add(rotDX2);
  50889. }
  50890. fy += dy;
  50891. }
  50892. return textureArray;
  50893. };
  50894. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  50895. var theta = Math.atan2(vDir.z, vDir.x);
  50896. var phi = Math.acos(vDir.y);
  50897. while (theta < -Math.PI)
  50898. theta += 2 * Math.PI;
  50899. while (theta > Math.PI)
  50900. theta -= 2 * Math.PI;
  50901. var dx = theta / Math.PI;
  50902. var dy = phi / Math.PI;
  50903. // recenter.
  50904. dx = dx * 0.5 + 0.5;
  50905. var px = Math.round(dx * inputWidth);
  50906. if (px < 0)
  50907. px = 0;
  50908. else if (px >= inputWidth)
  50909. px = inputWidth - 1;
  50910. var py = Math.round(dy * inputHeight);
  50911. if (py < 0)
  50912. py = 0;
  50913. else if (py >= inputHeight)
  50914. py = inputHeight - 1;
  50915. var inputY = (inputHeight - py - 1);
  50916. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  50917. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  50918. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  50919. return {
  50920. r: r,
  50921. g: g,
  50922. b: b
  50923. };
  50924. };
  50925. return PanoramaToCubeMapTools;
  50926. }());
  50927. PanoramaToCubeMapTools.FACE_FRONT = [
  50928. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50929. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50930. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50931. new BABYLON.Vector3(1.0, 1.0, -1.0)
  50932. ];
  50933. PanoramaToCubeMapTools.FACE_BACK = [
  50934. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50935. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50936. new BABYLON.Vector3(1.0, 1.0, 1.0),
  50937. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  50938. ];
  50939. PanoramaToCubeMapTools.FACE_RIGHT = [
  50940. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50941. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50942. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50943. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50944. ];
  50945. PanoramaToCubeMapTools.FACE_LEFT = [
  50946. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50947. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50948. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50949. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  50950. ];
  50951. PanoramaToCubeMapTools.FACE_DOWN = [
  50952. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50953. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50954. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50955. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50956. ];
  50957. PanoramaToCubeMapTools.FACE_UP = [
  50958. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50959. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50960. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50961. new BABYLON.Vector3(1.0, -1.0, -1.0)
  50962. ];
  50963. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  50964. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50965. })(BABYLON || (BABYLON = {}));
  50966. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  50967. var BABYLON;
  50968. (function (BABYLON) {
  50969. var Internals;
  50970. (function (Internals) {
  50971. ;
  50972. /**
  50973. * This groups tools to convert HDR texture to native colors array.
  50974. */
  50975. var HDRTools = (function () {
  50976. function HDRTools() {
  50977. }
  50978. HDRTools.Ldexp = function (mantissa, exponent) {
  50979. if (exponent > 1023) {
  50980. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  50981. }
  50982. if (exponent < -1074) {
  50983. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  50984. }
  50985. return mantissa * Math.pow(2, exponent);
  50986. };
  50987. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  50988. if (exponent > 0) {
  50989. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  50990. float32array[index + 0] = red * exponent;
  50991. float32array[index + 1] = green * exponent;
  50992. float32array[index + 2] = blue * exponent;
  50993. }
  50994. else {
  50995. float32array[index + 0] = 0;
  50996. float32array[index + 1] = 0;
  50997. float32array[index + 2] = 0;
  50998. }
  50999. };
  51000. HDRTools.readStringLine = function (uint8array, startIndex) {
  51001. var line = "";
  51002. var character = "";
  51003. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  51004. character = String.fromCharCode(uint8array[i]);
  51005. if (character == "\n") {
  51006. break;
  51007. }
  51008. line += character;
  51009. }
  51010. return line;
  51011. };
  51012. /**
  51013. * Reads header information from an RGBE texture stored in a native array.
  51014. * More information on this format are available here:
  51015. * https://en.wikipedia.org/wiki/RGBE_image_format
  51016. *
  51017. * @param uint8array The binary file stored in native array.
  51018. * @return The header information.
  51019. */
  51020. HDRTools.RGBE_ReadHeader = function (uint8array) {
  51021. var height = 0;
  51022. var width = 0;
  51023. var line = this.readStringLine(uint8array, 0);
  51024. if (line[0] != '#' || line[1] != '?') {
  51025. throw "Bad HDR Format.";
  51026. }
  51027. var endOfHeader = false;
  51028. var findFormat = false;
  51029. var lineIndex = 0;
  51030. do {
  51031. lineIndex += (line.length + 1);
  51032. line = this.readStringLine(uint8array, lineIndex);
  51033. if (line == "FORMAT=32-bit_rle_rgbe") {
  51034. findFormat = true;
  51035. }
  51036. else if (line.length == 0) {
  51037. endOfHeader = true;
  51038. }
  51039. } while (!endOfHeader);
  51040. if (!findFormat) {
  51041. throw "HDR Bad header format, unsupported FORMAT";
  51042. }
  51043. lineIndex += (line.length + 1);
  51044. line = this.readStringLine(uint8array, lineIndex);
  51045. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  51046. var match = sizeRegexp.exec(line);
  51047. // TODO. Support +Y and -X if needed.
  51048. if (match.length < 3) {
  51049. throw "HDR Bad header format, no size";
  51050. }
  51051. width = parseInt(match[2]);
  51052. height = parseInt(match[1]);
  51053. if (width < 8 || width > 0x7fff) {
  51054. throw "HDR Bad header format, unsupported size";
  51055. }
  51056. lineIndex += (line.length + 1);
  51057. return {
  51058. height: height,
  51059. width: width,
  51060. dataPosition: lineIndex
  51061. };
  51062. };
  51063. /**
  51064. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  51065. * This RGBE texture needs to store the information as a panorama.
  51066. *
  51067. * More information on this format are available here:
  51068. * https://en.wikipedia.org/wiki/RGBE_image_format
  51069. *
  51070. * @param buffer The binary file stored in an array buffer.
  51071. * @param size The expected size of the extracted cubemap.
  51072. * @return The Cube Map information.
  51073. */
  51074. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  51075. var uint8array = new Uint8Array(buffer);
  51076. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  51077. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  51078. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  51079. return cubeMapData;
  51080. };
  51081. /**
  51082. * Returns the pixels data extracted from an RGBE texture.
  51083. * This pixels will be stored left to right up to down in the R G B order in one array.
  51084. *
  51085. * More information on this format are available here:
  51086. * https://en.wikipedia.org/wiki/RGBE_image_format
  51087. *
  51088. * @param uint8array The binary file stored in an array buffer.
  51089. * @param hdrInfo The header information of the file.
  51090. * @return The pixels data in RGB right to left up to down order.
  51091. */
  51092. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  51093. // Keep for multi format supports.
  51094. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  51095. };
  51096. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  51097. var num_scanlines = hdrInfo.height;
  51098. var scanline_width = hdrInfo.width;
  51099. var a, b, c, d, count;
  51100. var dataIndex = hdrInfo.dataPosition;
  51101. var index = 0, endIndex = 0, i = 0;
  51102. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  51103. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  51104. // 3 channels of 4 bytes per pixel in float.
  51105. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  51106. var resultArray = new Float32Array(resultBuffer);
  51107. // read in each successive scanline
  51108. while (num_scanlines > 0) {
  51109. a = uint8array[dataIndex++];
  51110. b = uint8array[dataIndex++];
  51111. c = uint8array[dataIndex++];
  51112. d = uint8array[dataIndex++];
  51113. if (a != 2 || b != 2 || (c & 0x80)) {
  51114. // this file is not run length encoded
  51115. throw "HDR Bad header format, not RLE";
  51116. }
  51117. if (((c << 8) | d) != scanline_width) {
  51118. throw "HDR Bad header format, wrong scan line width";
  51119. }
  51120. index = 0;
  51121. // read each of the four channels for the scanline into the buffer
  51122. for (i = 0; i < 4; i++) {
  51123. endIndex = (i + 1) * scanline_width;
  51124. while (index < endIndex) {
  51125. a = uint8array[dataIndex++];
  51126. b = uint8array[dataIndex++];
  51127. if (a > 128) {
  51128. // a run of the same value
  51129. count = a - 128;
  51130. if ((count == 0) || (count > endIndex - index)) {
  51131. throw "HDR Bad Format, bad scanline data (run)";
  51132. }
  51133. while (count-- > 0) {
  51134. scanLineArray[index++] = b;
  51135. }
  51136. }
  51137. else {
  51138. // a non-run
  51139. count = a;
  51140. if ((count == 0) || (count > endIndex - index)) {
  51141. throw "HDR Bad Format, bad scanline data (non-run)";
  51142. }
  51143. scanLineArray[index++] = b;
  51144. if (--count > 0) {
  51145. for (var j = 0; j < count; j++) {
  51146. scanLineArray[index++] = uint8array[dataIndex++];
  51147. }
  51148. }
  51149. }
  51150. }
  51151. }
  51152. // now convert data from buffer into floats
  51153. for (i = 0; i < scanline_width; i++) {
  51154. a = scanLineArray[i];
  51155. b = scanLineArray[i + scanline_width];
  51156. c = scanLineArray[i + 2 * scanline_width];
  51157. d = scanLineArray[i + 3 * scanline_width];
  51158. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  51159. }
  51160. num_scanlines--;
  51161. }
  51162. return resultArray;
  51163. };
  51164. return HDRTools;
  51165. }());
  51166. Internals.HDRTools = HDRTools;
  51167. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51168. })(BABYLON || (BABYLON = {}));
  51169. //# sourceMappingURL=babylon.hdr.js.map
  51170. //_______________________________________________________________
  51171. // Extracted from CubeMapGen:
  51172. // https://code.google.com/archive/p/cubemapgen/
  51173. //
  51174. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  51175. //_______________________________________________________________
  51176. var BABYLON;
  51177. (function (BABYLON) {
  51178. var Internals;
  51179. (function (Internals) {
  51180. /**
  51181. * The bounding box information used during the conversion process.
  51182. */
  51183. var CMGBoundinBox = (function () {
  51184. function CMGBoundinBox() {
  51185. this.min = new BABYLON.Vector3(0, 0, 0);
  51186. this.max = new BABYLON.Vector3(0, 0, 0);
  51187. this.clear();
  51188. }
  51189. CMGBoundinBox.prototype.clear = function () {
  51190. this.min.x = CMGBoundinBox.MAX;
  51191. this.min.y = CMGBoundinBox.MAX;
  51192. this.min.z = CMGBoundinBox.MAX;
  51193. this.max.x = CMGBoundinBox.MIN;
  51194. this.max.y = CMGBoundinBox.MIN;
  51195. this.max.z = CMGBoundinBox.MIN;
  51196. };
  51197. CMGBoundinBox.prototype.augment = function (x, y, z) {
  51198. this.min.x = Math.min(this.min.x, x);
  51199. this.min.y = Math.min(this.min.y, y);
  51200. this.min.z = Math.min(this.min.z, z);
  51201. this.max.x = Math.max(this.max.x, x);
  51202. this.max.y = Math.max(this.max.y, y);
  51203. this.max.z = Math.max(this.max.z, z);
  51204. };
  51205. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  51206. this.min.x = Math.max(this.min.x, x);
  51207. this.min.y = Math.max(this.min.y, y);
  51208. this.min.z = Math.max(this.min.z, z);
  51209. };
  51210. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  51211. this.max.x = Math.min(this.max.x, x);
  51212. this.max.y = Math.min(this.max.y, y);
  51213. this.max.z = Math.min(this.max.z, z);
  51214. };
  51215. CMGBoundinBox.prototype.empty = function () {
  51216. if ((this.min.x > this.max.y) ||
  51217. (this.min.y > this.max.y) ||
  51218. (this.min.z > this.max.y)) {
  51219. return true;
  51220. }
  51221. else {
  51222. return false;
  51223. }
  51224. };
  51225. return CMGBoundinBox;
  51226. }());
  51227. CMGBoundinBox.MAX = Number.MAX_VALUE;
  51228. CMGBoundinBox.MIN = Number.MIN_VALUE;
  51229. /**
  51230. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  51231. * required by the glossinees of a material.
  51232. *
  51233. * This only supports the cosine drop power as well as Warp fixup generation method.
  51234. *
  51235. * This is using the process from CubeMapGen described here:
  51236. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  51237. */
  51238. var PMREMGenerator = (function () {
  51239. /**
  51240. * Constructor of the generator.
  51241. *
  51242. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  51243. * @param inputSize The size of the cubemap faces
  51244. * @param outputSize The size of the output cubemap faces
  51245. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  51246. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  51247. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  51248. * @param specularPower The max specular level of the desired cubemap
  51249. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  51250. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  51251. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  51252. */
  51253. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  51254. this.input = input;
  51255. this.inputSize = inputSize;
  51256. this.outputSize = outputSize;
  51257. this.maxNumMipLevels = maxNumMipLevels;
  51258. this.numChannels = numChannels;
  51259. this.isFloat = isFloat;
  51260. this.specularPower = specularPower;
  51261. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  51262. this.excludeBase = excludeBase;
  51263. this.fixup = fixup;
  51264. this._outputSurface = [];
  51265. this._numMipLevels = 0;
  51266. }
  51267. /**
  51268. * Launches the filter process and return the result.
  51269. *
  51270. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  51271. */
  51272. PMREMGenerator.prototype.filterCubeMap = function () {
  51273. // Init cubemap processor
  51274. this.init();
  51275. // Filters the cubemap
  51276. this.filterCubeMapMipChain();
  51277. // Returns the filtered mips.
  51278. return this._outputSurface;
  51279. };
  51280. PMREMGenerator.prototype.init = function () {
  51281. var i;
  51282. var j;
  51283. var mipLevelSize;
  51284. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  51285. if (this.maxNumMipLevels == 0) {
  51286. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  51287. }
  51288. //first miplevel size
  51289. mipLevelSize = this.outputSize;
  51290. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  51291. for (j = 0; j < this.maxNumMipLevels; j++) {
  51292. this._outputSurface.length++;
  51293. this._outputSurface[j] = [];
  51294. //Iterate over faces for output images
  51295. for (i = 0; i < 6; i++) {
  51296. this._outputSurface[j].length++;
  51297. // Initializes a new array for the output.
  51298. if (this.isFloat) {
  51299. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51300. }
  51301. else {
  51302. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51303. }
  51304. }
  51305. //next mip level is half size
  51306. mipLevelSize >>= 1;
  51307. this._numMipLevels++;
  51308. //terminate if mip chain becomes too small
  51309. if (mipLevelSize == 0) {
  51310. this.maxNumMipLevels = j;
  51311. return;
  51312. }
  51313. }
  51314. };
  51315. //--------------------------------------------------------------------------------------
  51316. //Cube map filtering and mip chain generation.
  51317. // the cube map filtereing is specified using a number of parameters:
  51318. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  51319. // indicates the region of the hemisphere to filter over for each tap.
  51320. //
  51321. // Note that the top mip level is also a filtered version of the original input images
  51322. // as well in order to create mip chains for diffuse environment illumination.
  51323. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  51324. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  51325. //
  51326. // Then the mip angle used to genreate the next level of the mip chain from the first level
  51327. // is a_InitialMipAngle
  51328. //
  51329. // The angle for the subsequent levels of the mip chain are specified by their parents
  51330. // filtering angle and a per-level scale and bias
  51331. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  51332. //
  51333. //--------------------------------------------------------------------------------------
  51334. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  51335. // First, take count of the lighting model to modify SpecularPower
  51336. // 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;
  51337. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  51338. //Cone angle start (for generating subsequent mip levels)
  51339. var currentSpecularPower = this.specularPower;
  51340. //Build filter lookup tables based on the source miplevel size
  51341. this.precomputeFilterLookupTables(this.inputSize);
  51342. // Note that we need to filter the first level before generating mipmap
  51343. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  51344. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  51345. // TODO : Write a function to copy and scale the base mipmap in output
  51346. // I am just lazy here and just put a high specular power value, and do some if.
  51347. if (this.excludeBase && (levelIndex == 0)) {
  51348. // 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).
  51349. currentSpecularPower = 100000.0;
  51350. }
  51351. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  51352. var srcCubeImage = this.input;
  51353. var dstCubeImage = this._outputSurface[levelIndex];
  51354. var dstSize = this.outputSize >> levelIndex;
  51355. // Compute required angle.
  51356. var angle = this.getBaseFilterAngle(currentSpecularPower);
  51357. // filter cube surfaces
  51358. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  51359. // fix seams
  51360. if (this.fixup) {
  51361. this.fixupCubeEdges(dstCubeImage, dstSize);
  51362. }
  51363. // Decrease the specular power to generate the mipmap chain
  51364. // TODO : Use another method for Exclude (see first comment at start of the function
  51365. if (this.excludeBase && (levelIndex == 0)) {
  51366. currentSpecularPower = this.specularPower;
  51367. }
  51368. currentSpecularPower *= this.cosinePowerDropPerMip;
  51369. }
  51370. };
  51371. //--------------------------------------------------------------------------------------
  51372. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  51373. // It allow to optimize the texel to access base on the specular power.
  51374. //--------------------------------------------------------------------------------------
  51375. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  51376. // We want to find the alpha such that:
  51377. // cos(alpha)^cosinePower = epsilon
  51378. // That's: acos(epsilon^(1/cosinePower))
  51379. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  51380. var angle = 180.0;
  51381. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  51382. angle *= 180.0 / Math.PI; // Convert to degree
  51383. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  51384. return angle;
  51385. };
  51386. //--------------------------------------------------------------------------------------
  51387. //Builds the following lookup tables prior to filtering:
  51388. // -normalizer cube map
  51389. // -tap weight lookup table
  51390. //
  51391. //--------------------------------------------------------------------------------------
  51392. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  51393. var srcTexelAngle;
  51394. var iCubeFace;
  51395. //clear pre-existing normalizer cube map
  51396. this._normCubeMap = [];
  51397. //Normalized vectors per cubeface and per-texel solid angle
  51398. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  51399. };
  51400. //--------------------------------------------------------------------------------------
  51401. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  51402. //
  51403. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  51404. //
  51405. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  51406. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  51407. // below
  51408. //--------------------------------------------------------------------------------------
  51409. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  51410. var iCubeFace;
  51411. var u;
  51412. var v;
  51413. //iterate over cube faces
  51414. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51415. //First three channels for norm cube, and last channel for solid angle
  51416. this._normCubeMap.push(new Float32Array(size * size * 4));
  51417. //fast texture walk, build normalizer cube map
  51418. var facesData = this.input[iCubeFace];
  51419. for (v = 0; v < size; v++) {
  51420. for (u = 0; u < size; u++) {
  51421. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  51422. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  51423. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  51424. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  51425. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  51426. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  51427. }
  51428. }
  51429. }
  51430. };
  51431. //--------------------------------------------------------------------------------------
  51432. // Convert cubemap face texel coordinates and face idx to 3D vector
  51433. // note the U and V coords are integer coords and range from 0 to size-1
  51434. // this routine can be used to generate a normalizer cube map
  51435. //--------------------------------------------------------------------------------------
  51436. // SL BEGIN
  51437. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  51438. var nvcU;
  51439. var nvcV;
  51440. var tempVec;
  51441. // Change from original AMD code
  51442. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51443. // + 0.5f is for texel center addressing
  51444. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  51445. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  51446. // warp fixup
  51447. if (fixup && size > 1) {
  51448. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  51449. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  51450. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  51451. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  51452. }
  51453. // Get current vector
  51454. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  51455. // U contribution
  51456. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51457. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  51458. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  51459. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  51460. // V contribution and Sum
  51461. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51462. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  51463. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  51464. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  51465. //add face axis
  51466. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  51467. PMREMGenerator._vectorTemp.x += faceAxis[0];
  51468. PMREMGenerator._vectorTemp.y += faceAxis[1];
  51469. PMREMGenerator._vectorTemp.z += faceAxis[2];
  51470. //normalize vector
  51471. PMREMGenerator._vectorTemp.normalize();
  51472. return PMREMGenerator._vectorTemp;
  51473. };
  51474. //--------------------------------------------------------------------------------------
  51475. // Convert 3D vector to cubemap face texel coordinates and face idx
  51476. // note the U and V coords are integer coords and range from 0 to size-1
  51477. // this routine can be used to generate a normalizer cube map
  51478. //
  51479. // returns face IDX and texel coords
  51480. //--------------------------------------------------------------------------------------
  51481. // SL BEGIN
  51482. /*
  51483. Mapping Texture Coordinates to Cube Map Faces
  51484. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  51485. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  51486. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  51487. map arrangement in Pixar's RenderMan package.
  51488. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  51489. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  51490. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  51491. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  51492. the major axis direction). The target column in the table below explains how the major axis direction
  51493. maps to the 2D image of a particular cube map target.
  51494. major axis
  51495. direction target sc tc ma
  51496. ---------- --------------------------------- --- --- ---
  51497. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  51498. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  51499. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  51500. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  51501. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  51502. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  51503. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  51504. an updated (s,t) is calculated as follows
  51505. s = ( sc/|ma| + 1 ) / 2
  51506. t = ( tc/|ma| + 1 ) / 2
  51507. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  51508. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  51509. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  51510. */
  51511. // Note this method return U and V in range from 0 to size-1
  51512. // SL END
  51513. // Store the information in vector3 for convenience (faceindex, u, v)
  51514. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  51515. var maxCoord;
  51516. var faceIdx;
  51517. //absolute value 3
  51518. var absX = Math.abs(x);
  51519. var absY = Math.abs(y);
  51520. var absZ = Math.abs(z);
  51521. if (absX >= absY && absX >= absZ) {
  51522. maxCoord = absX;
  51523. if (x >= 0) {
  51524. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  51525. }
  51526. else {
  51527. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51528. }
  51529. }
  51530. else if (absY >= absX && absY >= absZ) {
  51531. maxCoord = absY;
  51532. if (y >= 0) {
  51533. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51534. }
  51535. else {
  51536. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51537. }
  51538. }
  51539. else {
  51540. maxCoord = absZ;
  51541. if (z >= 0) {
  51542. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51543. }
  51544. else {
  51545. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51546. }
  51547. }
  51548. //divide through by max coord so face vector lies on cube face
  51549. var scale = 1 / maxCoord;
  51550. x *= scale;
  51551. y *= scale;
  51552. z *= scale;
  51553. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51554. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  51555. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51556. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  51557. // Modify original AMD code to return value from 0 to Size - 1
  51558. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  51559. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  51560. PMREMGenerator._vectorTemp.x = faceIdx;
  51561. PMREMGenerator._vectorTemp.y = u;
  51562. PMREMGenerator._vectorTemp.z = v;
  51563. return PMREMGenerator._vectorTemp;
  51564. };
  51565. //--------------------------------------------------------------------------------------
  51566. //Original code from Ignacio CastaÒo
  51567. // This formula is from Manne ÷hrstrˆm's thesis.
  51568. // Take two coordiantes in the range [-1, 1] that define a portion of a
  51569. // cube face and return the area of the projection of that portion on the
  51570. // surface of the sphere.
  51571. //--------------------------------------------------------------------------------------
  51572. PMREMGenerator.prototype.areaElement = function (x, y) {
  51573. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  51574. };
  51575. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  51576. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51577. // (+ 0.5f is for texel center addressing)
  51578. u = (2.0 * (u + 0.5) / size) - 1.0;
  51579. v = (2.0 * (v + 0.5) / size) - 1.0;
  51580. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  51581. var invResolution = 1.0 / size;
  51582. // U and V are the -1..1 texture coordinate on the current face.
  51583. // Get projected area for this texel
  51584. var x0 = u - invResolution;
  51585. var y0 = v - invResolution;
  51586. var x1 = u + invResolution;
  51587. var y1 = v + invResolution;
  51588. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  51589. return solidAngle;
  51590. };
  51591. //--------------------------------------------------------------------------------------
  51592. //The key to the speed of these filtering routines is to quickly define a per-face
  51593. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  51594. // Later these pixels are selectively processed based on their dot products to see if
  51595. // they reside within the filtering cone.
  51596. //
  51597. //This is done by computing the smallest per-texel angle to get a conservative estimate
  51598. // of the number of texels needed to be covered in width and height order to filter the
  51599. // region. the bounding box for the center taps face is defined first, and if the
  51600. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  51601. // defined next
  51602. //--------------------------------------------------------------------------------------
  51603. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  51604. // note that pixels within these regions may be rejected
  51605. // based on the anlge
  51606. var iCubeFace;
  51607. var u;
  51608. var v;
  51609. // bounding box per face to specify region to process
  51610. var filterExtents = [];
  51611. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51612. filterExtents.push(new CMGBoundinBox());
  51613. }
  51614. // min angle a src texel can cover (in degrees)
  51615. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  51616. // angle about center tap to define filter cone
  51617. // filter angle is 1/2 the cone angle
  51618. var filterAngle = filterConeAngle / 2.0;
  51619. //ensure filter angle is larger than a texel
  51620. if (filterAngle < srcTexelAngle) {
  51621. filterAngle = srcTexelAngle;
  51622. }
  51623. //ensure filter cone is always smaller than the hemisphere
  51624. if (filterAngle > 90.0) {
  51625. filterAngle = 90.0;
  51626. }
  51627. // the maximum number of texels in 1D the filter cone angle will cover
  51628. // used to determine bounding box size for filter extents
  51629. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  51630. // ensure conservative region always covers at least one texel
  51631. if (filterSize < 1) {
  51632. filterSize = 1;
  51633. }
  51634. // dotProdThresh threshold based on cone angle to determine whether or not taps
  51635. // reside within the cone angle
  51636. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  51637. // process required faces
  51638. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51639. //iterate over dst cube map face texel
  51640. for (v = 0; v < dstSize; v++) {
  51641. for (u = 0; u < dstSize; u++) {
  51642. //get center tap direction
  51643. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  51644. //clear old per-face filter extents
  51645. this.clearFilterExtents(filterExtents);
  51646. //define per-face filter extents
  51647. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  51648. //perform filtering of src faces using filter extents
  51649. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  51650. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  51651. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  51652. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  51653. }
  51654. }
  51655. }
  51656. };
  51657. //--------------------------------------------------------------------------------------
  51658. //Clear filter extents for the 6 cube map faces
  51659. //--------------------------------------------------------------------------------------
  51660. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  51661. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  51662. filterExtents[iCubeFaces].clear();
  51663. }
  51664. };
  51665. //--------------------------------------------------------------------------------------
  51666. //Define per-face bounding box filter extents
  51667. //
  51668. // These define conservative texel regions in each of the faces the filter can possibly
  51669. // process. When the pixels in the regions are actually processed, the dot product
  51670. // between the tap vector and the center tap vector is used to determine the weight of
  51671. // the tap and whether or not the tap is within the cone.
  51672. //
  51673. //--------------------------------------------------------------------------------------
  51674. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  51675. //neighboring face and bleed over amount, and width of BBOX for
  51676. // left, right, top, and bottom edges of this face
  51677. var bleedOverAmount = [0, 0, 0, 0];
  51678. var bleedOverBBoxMin = [0, 0, 0, 0];
  51679. var bleedOverBBoxMax = [0, 0, 0, 0];
  51680. var neighborFace;
  51681. var neighborEdge;
  51682. var oppositeFaceIdx;
  51683. //get face idx, and u, v info from center tap dir
  51684. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  51685. var faceIdx = result.x;
  51686. var u = result.y;
  51687. var v = result.z;
  51688. //define bbox size within face
  51689. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  51690. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  51691. filterExtents[faceIdx].clampMin(0, 0, 0);
  51692. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  51693. //u and v extent in face corresponding to center tap
  51694. var minU = filterExtents[faceIdx].min.x;
  51695. var minV = filterExtents[faceIdx].min.y;
  51696. var maxU = filterExtents[faceIdx].max.x;
  51697. var maxV = filterExtents[faceIdx].max.y;
  51698. //bleed over amounts for face across u=0 edge (left)
  51699. bleedOverAmount[0] = (bboxSize - u);
  51700. bleedOverBBoxMin[0] = minV;
  51701. bleedOverBBoxMax[0] = maxV;
  51702. //bleed over amounts for face across u=1 edge (right)
  51703. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  51704. bleedOverBBoxMin[1] = minV;
  51705. bleedOverBBoxMax[1] = maxV;
  51706. //bleed over to face across v=0 edge (up)
  51707. bleedOverAmount[2] = (bboxSize - v);
  51708. bleedOverBBoxMin[2] = minU;
  51709. bleedOverBBoxMax[2] = maxU;
  51710. //bleed over to face across v=1 edge (down)
  51711. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  51712. bleedOverBBoxMin[3] = minU;
  51713. bleedOverBBoxMax[3] = maxU;
  51714. //compute bleed over regions in neighboring faces
  51715. for (var i = 0; i < 4; i++) {
  51716. if (bleedOverAmount[i] > 0) {
  51717. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  51718. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  51719. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  51720. // be flipped: the cases are
  51721. // if a left edge mates with a left or bottom edge on the neighbor
  51722. // if a top edge mates with a top or right edge on the neighbor
  51723. // if a right edge mates with a right or top edge on the neighbor
  51724. // if a bottom edge mates with a bottom or left edge on the neighbor
  51725. //Seeing as the edges are enumerated as follows
  51726. // left =0
  51727. // right =1
  51728. // top =2
  51729. // bottom =3
  51730. //
  51731. // so if the edge enums are the same, or the sum of the enums == 3,
  51732. // the bbox needs to be flipped
  51733. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  51734. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  51735. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  51736. }
  51737. //The way the bounding box is extended onto the neighboring face
  51738. // depends on which edge of neighboring face abuts with this one
  51739. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  51740. case PMREMGenerator.CP_EDGE_LEFT:
  51741. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  51742. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51743. break;
  51744. case PMREMGenerator.CP_EDGE_RIGHT:
  51745. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  51746. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51747. break;
  51748. case PMREMGenerator.CP_EDGE_TOP:
  51749. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  51750. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  51751. break;
  51752. case PMREMGenerator.CP_EDGE_BOTTOM:
  51753. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  51754. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  51755. break;
  51756. }
  51757. //clamp filter extents in non-center tap faces to remain within surface
  51758. filterExtents[neighborFace].clampMin(0, 0, 0);
  51759. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  51760. }
  51761. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  51762. // from the center tap face, then process the opposite face entirely for now.
  51763. //Note that the cases in which this happens, what usually happens is that
  51764. // more than one edge bleeds onto the opposite face, and the bounding box
  51765. // encompasses the entire cube map face.
  51766. if (bleedOverAmount[i] > srcSize) {
  51767. //determine opposite face
  51768. switch (faceIdx) {
  51769. case PMREMGenerator.CP_FACE_X_POS:
  51770. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51771. break;
  51772. case PMREMGenerator.CP_FACE_X_NEG:
  51773. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  51774. break;
  51775. case PMREMGenerator.CP_FACE_Y_POS:
  51776. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51777. break;
  51778. case PMREMGenerator.CP_FACE_Y_NEG:
  51779. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51780. break;
  51781. case PMREMGenerator.CP_FACE_Z_POS:
  51782. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51783. break;
  51784. case PMREMGenerator.CP_FACE_Z_NEG:
  51785. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51786. break;
  51787. default:
  51788. break;
  51789. }
  51790. //just encompass entire face for now
  51791. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  51792. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  51793. }
  51794. }
  51795. };
  51796. //--------------------------------------------------------------------------------------
  51797. //ProcessFilterExtents
  51798. // Process bounding box in each cube face
  51799. //
  51800. //--------------------------------------------------------------------------------------
  51801. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  51802. //accumulators are 64-bit floats in order to have the precision needed
  51803. // over a summation of a large number of pixels
  51804. var dstAccum = [0, 0, 0, 0];
  51805. var weightAccum = 0;
  51806. var k = 0;
  51807. var nSrcChannels = this.numChannels;
  51808. // norm cube map and srcCubeMap have same face width
  51809. var faceWidth = srcSize;
  51810. //amount to add to pointer to move to next scanline in images
  51811. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  51812. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  51813. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  51814. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  51815. // iterate over cubefaces
  51816. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  51817. //if bbox is non empty
  51818. if (!filterExtents[iFaceIdx].empty()) {
  51819. var uStart = filterExtents[iFaceIdx].min.x;
  51820. var vStart = filterExtents[iFaceIdx].min.y;
  51821. var uEnd = filterExtents[iFaceIdx].max.x;
  51822. var vEnd = filterExtents[iFaceIdx].max.y;
  51823. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  51824. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  51825. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  51826. for (var v = vStart; v <= vEnd; v++) {
  51827. var normCubeRowWalk = 0;
  51828. var srcCubeRowWalk = 0;
  51829. for (var u = uStart; u <= uEnd; u++) {
  51830. //pointer to direction in cube map associated with texel
  51831. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  51832. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  51833. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  51834. //check dot product to see if texel is within cone
  51835. var tapDotProd = texelVectX * centerTapDir.x +
  51836. texelVectY * centerTapDir.y +
  51837. texelVectZ * centerTapDir.z;
  51838. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  51839. //solid angle stored in 4th channel of normalizer/solid angle cube map
  51840. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  51841. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  51842. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  51843. // so just adding one to specularpower do the trick.
  51844. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  51845. //iterate over channels
  51846. for (k = 0; k < nSrcChannels; k++) {
  51847. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  51848. srcCubeRowWalk++;
  51849. }
  51850. weightAccum += weight; //accumulate weight
  51851. }
  51852. else {
  51853. //step across source pixel
  51854. srcCubeRowWalk += nSrcChannels;
  51855. }
  51856. normCubeRowWalk += 4; // 4 channels per norm cube map.
  51857. }
  51858. startIndexNormCubeMap += normCubePitch;
  51859. startIndexSrcCubeMap += srcCubePitch;
  51860. }
  51861. }
  51862. }
  51863. //divide through by weights if weight is non zero
  51864. if (weightAccum != 0.0) {
  51865. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  51866. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  51867. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  51868. if (this.numChannels > 3) {
  51869. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  51870. }
  51871. }
  51872. else {
  51873. // otherwise sample nearest
  51874. // get face idx and u, v texel coordinate in face
  51875. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  51876. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  51877. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  51878. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  51879. if (this.numChannels > 3) {
  51880. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  51881. }
  51882. }
  51883. return PMREMGenerator._vectorTemp;
  51884. };
  51885. //--------------------------------------------------------------------------------------
  51886. // Fixup cube edges
  51887. //
  51888. // average texels on cube map faces across the edges
  51889. // WARP/BENT Method Only.
  51890. //--------------------------------------------------------------------------------------
  51891. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  51892. var k;
  51893. var j;
  51894. var i;
  51895. var iFace;
  51896. var iCorner = 0;
  51897. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  51898. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  51899. // note that if functionality to filter across the three texels for each corner, then
  51900. //indexed by corner and face idx. the array contains the face the start points belongs to.
  51901. var cornerPtr = [
  51902. [[], [], []],
  51903. [[], [], []],
  51904. [[], [], []],
  51905. [[], [], []],
  51906. [[], [], []],
  51907. [[], [], []],
  51908. [[], [], []],
  51909. [[], [], []]
  51910. ];
  51911. //if there is no fixup, or fixup width = 0, do nothing
  51912. if (cubeMapSize < 1) {
  51913. return;
  51914. }
  51915. //special case 1x1 cubemap, average face colors
  51916. if (cubeMapSize == 1) {
  51917. //iterate over channels
  51918. for (k = 0; k < this.numChannels; k++) {
  51919. var accum = 0.0;
  51920. //iterate over faces to accumulate face colors
  51921. for (iFace = 0; iFace < 6; iFace++) {
  51922. accum += cubeMap[iFace][k];
  51923. }
  51924. //compute average over 6 face colors
  51925. accum /= 6.0;
  51926. //iterate over faces to distribute face colors
  51927. for (iFace = 0; iFace < 6; iFace++) {
  51928. cubeMap[iFace][k] = accum;
  51929. }
  51930. }
  51931. return;
  51932. }
  51933. //iterate over faces to collect list of corner texel pointers
  51934. for (iFace = 0; iFace < 6; iFace++) {
  51935. //the 4 corner pointers for this face
  51936. faceCornerStartIndicies[0] = [iFace, 0];
  51937. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  51938. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  51939. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  51940. //iterate over face corners to collect cube corner pointers
  51941. for (iCorner = 0; iCorner < 4; iCorner++) {
  51942. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  51943. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  51944. cornerNumPtrs[corner]++;
  51945. }
  51946. }
  51947. //iterate over corners to average across corner tap values
  51948. for (iCorner = 0; iCorner < 8; iCorner++) {
  51949. for (k = 0; k < this.numChannels; k++) {
  51950. var cornerTapAccum = 0.0;
  51951. //iterate over corner texels and average results
  51952. for (i = 0; i < 3; i++) {
  51953. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  51954. }
  51955. //divide by 3 to compute average of corner tap values
  51956. cornerTapAccum *= (1.0 / 3.0);
  51957. //iterate over corner texels and average results
  51958. for (i = 0; i < 3; i++) {
  51959. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  51960. }
  51961. }
  51962. }
  51963. //iterate over the twelve edges of the cube to average across edges
  51964. for (i = 0; i < 12; i++) {
  51965. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  51966. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  51967. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  51968. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  51969. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  51970. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  51971. var edgeWalk = 0;
  51972. var neighborEdgeWalk = 0;
  51973. //Determine walking pointers based on edge type
  51974. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  51975. switch (edge) {
  51976. case PMREMGenerator.CP_EDGE_LEFT:
  51977. // no change to faceEdgeStartPtr
  51978. edgeWalk = this.numChannels * cubeMapSize;
  51979. break;
  51980. case PMREMGenerator.CP_EDGE_RIGHT:
  51981. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51982. edgeWalk = this.numChannels * cubeMapSize;
  51983. break;
  51984. case PMREMGenerator.CP_EDGE_TOP:
  51985. // no change to faceEdgeStartPtr
  51986. edgeWalk = this.numChannels;
  51987. break;
  51988. case PMREMGenerator.CP_EDGE_BOTTOM:
  51989. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51990. edgeWalk = this.numChannels;
  51991. break;
  51992. }
  51993. //For certain types of edge abutments, the neighbor edge walk needs to
  51994. // be flipped: the cases are
  51995. // if a left edge mates with a left or bottom edge on the neighbor
  51996. // if a top edge mates with a top or right edge on the neighbor
  51997. // if a right edge mates with a right or top edge on the neighbor
  51998. // if a bottom edge mates with a bottom or left edge on the neighbor
  51999. //Seeing as the edges are enumerated as follows
  52000. // left =0
  52001. // right =1
  52002. // top =2
  52003. // bottom =3
  52004. //
  52005. //If the edge enums are the same, or the sum of the enums == 3,
  52006. // the neighbor edge walk needs to be flipped
  52007. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  52008. switch (neighborEdge) {
  52009. case PMREMGenerator.CP_EDGE_LEFT:
  52010. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  52011. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  52012. break;
  52013. case PMREMGenerator.CP_EDGE_RIGHT:
  52014. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  52015. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  52016. break;
  52017. case PMREMGenerator.CP_EDGE_TOP:
  52018. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  52019. neighborEdgeWalk = -this.numChannels;
  52020. break;
  52021. case PMREMGenerator.CP_EDGE_BOTTOM:
  52022. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  52023. neighborEdgeWalk = -this.numChannels;
  52024. break;
  52025. }
  52026. }
  52027. else {
  52028. //swapped direction neighbor edge walk
  52029. switch (neighborEdge) {
  52030. case PMREMGenerator.CP_EDGE_LEFT:
  52031. //no change to neighborEdgeStartPtr for this case since it points
  52032. // to the upper left corner already
  52033. neighborEdgeWalk = this.numChannels * cubeMapSize;
  52034. break;
  52035. case PMREMGenerator.CP_EDGE_RIGHT:
  52036. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  52037. neighborEdgeWalk = this.numChannels * cubeMapSize;
  52038. break;
  52039. case PMREMGenerator.CP_EDGE_TOP:
  52040. //no change to neighborEdgeStartPtr for this case since it points
  52041. // to the upper left corner already
  52042. neighborEdgeWalk = this.numChannels;
  52043. break;
  52044. case PMREMGenerator.CP_EDGE_BOTTOM:
  52045. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  52046. neighborEdgeWalk = this.numChannels;
  52047. break;
  52048. }
  52049. }
  52050. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  52051. //nearby neighborhood
  52052. //step ahead one texel on edge
  52053. edgeStartIndex += edgeWalk;
  52054. neighborEdgeStartIndex += neighborEdgeWalk;
  52055. // note that this loop does not process the corner texels, since they have already been
  52056. // averaged across faces across earlier
  52057. for (j = 1; j < (cubeMapSize - 1); j++) {
  52058. //for each set of taps along edge, average them
  52059. // and rewrite the results into the edges
  52060. for (k = 0; k < this.numChannels; k++) {
  52061. var edgeTap = cubeMap[face][edgeStartIndex + k];
  52062. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  52063. //compute average of tap intensity values
  52064. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  52065. //propagate average of taps to edge taps
  52066. cubeMap[face][edgeStartIndex + k] = avgTap;
  52067. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  52068. }
  52069. edgeStartIndex += edgeWalk;
  52070. neighborEdgeStartIndex += neighborEdgeWalk;
  52071. }
  52072. }
  52073. };
  52074. return PMREMGenerator;
  52075. }());
  52076. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  52077. PMREMGenerator.CP_UDIR = 0;
  52078. PMREMGenerator.CP_VDIR = 1;
  52079. PMREMGenerator.CP_FACEAXIS = 2;
  52080. //used to index cube faces
  52081. PMREMGenerator.CP_FACE_X_POS = 0;
  52082. PMREMGenerator.CP_FACE_X_NEG = 1;
  52083. PMREMGenerator.CP_FACE_Y_POS = 2;
  52084. PMREMGenerator.CP_FACE_Y_NEG = 3;
  52085. PMREMGenerator.CP_FACE_Z_POS = 4;
  52086. PMREMGenerator.CP_FACE_Z_NEG = 5;
  52087. //used to index image edges
  52088. // NOTE.. the actual number corresponding to the edge is important
  52089. // do not change these, or the code will break
  52090. //
  52091. // CP_EDGE_LEFT is u = 0
  52092. // CP_EDGE_RIGHT is u = width-1
  52093. // CP_EDGE_TOP is v = 0
  52094. // CP_EDGE_BOTTOM is v = height-1
  52095. PMREMGenerator.CP_EDGE_LEFT = 0;
  52096. PMREMGenerator.CP_EDGE_RIGHT = 1;
  52097. PMREMGenerator.CP_EDGE_TOP = 2;
  52098. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  52099. //corners of CUBE map (P or N specifys if it corresponds to the
  52100. // positive or negative direction each of X, Y, and Z
  52101. PMREMGenerator.CP_CORNER_NNN = 0;
  52102. PMREMGenerator.CP_CORNER_NNP = 1;
  52103. PMREMGenerator.CP_CORNER_NPN = 2;
  52104. PMREMGenerator.CP_CORNER_NPP = 3;
  52105. PMREMGenerator.CP_CORNER_PNN = 4;
  52106. PMREMGenerator.CP_CORNER_PNP = 5;
  52107. PMREMGenerator.CP_CORNER_PPN = 6;
  52108. PMREMGenerator.CP_CORNER_PPP = 7;
  52109. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  52110. //3x2 matrices that map cube map indexing vectors in 3d
  52111. // (after face selection and divide through by the
  52112. // _ABSOLUTE VALUE_ of the max coord)
  52113. // into NVC space
  52114. //Note this currently assumes the D3D cube face ordering and orientation
  52115. PMREMGenerator._sgFace2DMapping = [
  52116. //XPOS face
  52117. [[0, 0, -1],
  52118. [0, -1, 0],
  52119. [1, 0, 0]],
  52120. //XNEG face
  52121. [[0, 0, 1],
  52122. [0, -1, 0],
  52123. [-1, 0, 0]],
  52124. //YPOS face
  52125. [[1, 0, 0],
  52126. [0, 0, 1],
  52127. [0, 1, 0]],
  52128. //YNEG face
  52129. [[1, 0, 0],
  52130. [0, 0, -1],
  52131. [0, -1, 0]],
  52132. //ZPOS face
  52133. [[1, 0, 0],
  52134. [0, -1, 0],
  52135. [0, 0, 1]],
  52136. //ZNEG face
  52137. [[-1, 0, 0],
  52138. [0, -1, 0],
  52139. [0, 0, -1]],
  52140. ];
  52141. //------------------------------------------------------------------------------
  52142. // D3D cube map face specification
  52143. // mapping from 3D x,y,z cube map lookup coordinates
  52144. // to 2D within face u,v coordinates
  52145. //
  52146. // --------------------> U direction
  52147. // | (within-face texture space)
  52148. // | _____
  52149. // | | |
  52150. // | | +Y |
  52151. // | _____|_____|_____ _____
  52152. // | | | | | |
  52153. // | | -X | +Z | +X | -Z |
  52154. // | |_____|_____|_____|_____|
  52155. // | | |
  52156. // | | -Y |
  52157. // | |_____|
  52158. // |
  52159. // v V direction
  52160. // (within-face texture space)
  52161. //------------------------------------------------------------------------------
  52162. //Information about neighbors and how texture coorrdinates change across faces
  52163. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  52164. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  52165. //Note this currently assumes the D3D cube face ordering and orientation
  52166. PMREMGenerator._sgCubeNgh = [
  52167. //XPOS face
  52168. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52169. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52170. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52171. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  52172. //XNEG face
  52173. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52174. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  52175. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  52176. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  52177. //YPOS face
  52178. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  52179. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  52180. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  52181. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  52182. //YNEG face
  52183. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  52184. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52185. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52186. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  52187. //ZPOS face
  52188. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52189. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  52190. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52191. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  52192. //ZNEG face
  52193. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52194. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52195. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  52196. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  52197. ];
  52198. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  52199. // this table is used to average over the edges.
  52200. PMREMGenerator._sgCubeEdgeList = [
  52201. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  52202. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52203. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  52204. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52205. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52206. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52207. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  52208. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  52209. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  52210. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52211. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  52212. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  52213. ];
  52214. //Information about which of the 8 cube corners are correspond to the
  52215. // the 4 corners in each cube face
  52216. // the order is upper left, upper right, lower left, lower right
  52217. PMREMGenerator._sgCubeCornerList = [
  52218. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  52219. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  52220. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  52221. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  52222. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  52223. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  52224. ];
  52225. Internals.PMREMGenerator = PMREMGenerator;
  52226. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52227. })(BABYLON || (BABYLON = {}));
  52228. //# sourceMappingURL=babylon.pmremgenerator.js.map
  52229. var BABYLON;
  52230. (function (BABYLON) {
  52231. /**
  52232. * This represents a texture coming from an HDR input.
  52233. *
  52234. * The only supported format is currently panorama picture stored in RGBE format.
  52235. * Example of such files can be found on HDRLib: http://hdrlib.com/
  52236. */
  52237. var HDRCubeTexture = (function (_super) {
  52238. __extends(HDRCubeTexture, _super);
  52239. /**
  52240. * Instantiates an HDRTexture from the following parameters.
  52241. *
  52242. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  52243. * @param scene The scene the texture will be used in
  52244. * @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.
  52245. * @param noMipmap Forces to not generate the mipmap if true
  52246. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  52247. * @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)
  52248. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  52249. */
  52250. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  52251. if (noMipmap === void 0) { noMipmap = false; }
  52252. if (generateHarmonics === void 0) { generateHarmonics = true; }
  52253. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  52254. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  52255. if (onLoad === void 0) { onLoad = null; }
  52256. if (onError === void 0) { onError = null; }
  52257. var _this = _super.call(this, scene) || this;
  52258. _this._useInGammaSpace = false;
  52259. _this._generateHarmonics = true;
  52260. _this._isBABYLONPreprocessed = false;
  52261. _this._onLoad = null;
  52262. _this._onError = null;
  52263. /**
  52264. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  52265. */
  52266. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  52267. /**
  52268. * The spherical polynomial data extracted from the texture.
  52269. */
  52270. _this.sphericalPolynomial = null;
  52271. /**
  52272. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  52273. * This is usefull at run time to apply the good shader.
  52274. */
  52275. _this.isPMREM = false;
  52276. if (!url) {
  52277. return _this;
  52278. }
  52279. _this.name = url;
  52280. _this.url = url;
  52281. _this.hasAlpha = false;
  52282. _this.isCube = true;
  52283. _this._textureMatrix = BABYLON.Matrix.Identity();
  52284. _this._onLoad = onLoad;
  52285. _this._onError = onError;
  52286. if (size) {
  52287. _this._isBABYLONPreprocessed = false;
  52288. _this._noMipmap = noMipmap;
  52289. _this._size = size;
  52290. _this._useInGammaSpace = useInGammaSpace;
  52291. _this._usePMREMGenerator = usePMREMGenerator &&
  52292. scene.getEngine().getCaps().textureLOD &&
  52293. _this.getScene().getEngine().getCaps().textureFloat &&
  52294. !_this._useInGammaSpace;
  52295. }
  52296. else {
  52297. _this._isBABYLONPreprocessed = true;
  52298. _this._noMipmap = false;
  52299. _this._useInGammaSpace = false;
  52300. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  52301. _this.getScene().getEngine().getCaps().textureFloat &&
  52302. !_this._useInGammaSpace;
  52303. }
  52304. _this.isPMREM = _this._usePMREMGenerator;
  52305. _this._texture = _this._getFromCache(url, _this._noMipmap);
  52306. if (!_this._texture) {
  52307. if (!scene.useDelayedTextureLoading) {
  52308. _this.loadTexture();
  52309. }
  52310. else {
  52311. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52312. }
  52313. }
  52314. return _this;
  52315. }
  52316. /**
  52317. * Occurs when the file is a preprocessed .babylon.hdr file.
  52318. */
  52319. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  52320. var _this = this;
  52321. var mipLevels = 0;
  52322. var floatArrayView = null;
  52323. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  52324. var mips = [];
  52325. var startIndex = 30;
  52326. for (var level = 0; level < mipLevels; level++) {
  52327. mips.push([]);
  52328. // Fill each pixel of the mip level.
  52329. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  52330. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52331. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  52332. mips[level].push(faceData);
  52333. startIndex += faceSize;
  52334. }
  52335. }
  52336. return mips;
  52337. } : null;
  52338. var callback = function (buffer) {
  52339. // Create Native Array Views
  52340. var intArrayView = new Int32Array(buffer);
  52341. floatArrayView = new Float32Array(buffer);
  52342. // Fill header.
  52343. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  52344. _this._size = intArrayView[1]; // CubeMap max mip face size.
  52345. // Update Texture Information.
  52346. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  52347. // Fill polynomial information.
  52348. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  52349. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  52350. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  52351. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  52352. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  52353. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  52354. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  52355. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  52356. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  52357. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  52358. // Fill pixel data.
  52359. mipLevels = intArrayView[29]; // Number of mip levels.
  52360. var startIndex = 30;
  52361. var data = [];
  52362. var faceSize = Math.pow(_this._size, 2) * 3;
  52363. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52364. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  52365. startIndex += faceSize;
  52366. }
  52367. var results = [];
  52368. var byteArray = null;
  52369. // Push each faces.
  52370. for (var k = 0; k < 6; k++) {
  52371. var dataFace = null;
  52372. // If special cases.
  52373. if (!mipmapGenerator) {
  52374. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  52375. dataFace = data[j];
  52376. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52377. // 3 channels of 1 bytes per pixel in bytes.
  52378. var byteBuffer = new ArrayBuffer(faceSize);
  52379. byteArray = new Uint8Array(byteBuffer);
  52380. }
  52381. for (var i = 0; i < _this._size * _this._size; i++) {
  52382. // Put in gamma space if requested.
  52383. if (_this._useInGammaSpace) {
  52384. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52385. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52386. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52387. }
  52388. // Convert to int texture for fallback.
  52389. if (byteArray) {
  52390. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52391. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52392. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52393. // May use luminance instead if the result is not accurate.
  52394. var max = Math.max(Math.max(r, g), b);
  52395. if (max > 255) {
  52396. var scale = 255 / max;
  52397. r *= scale;
  52398. g *= scale;
  52399. b *= scale;
  52400. }
  52401. byteArray[(i * 3) + 0] = r;
  52402. byteArray[(i * 3) + 1] = g;
  52403. byteArray[(i * 3) + 2] = b;
  52404. }
  52405. }
  52406. }
  52407. else {
  52408. dataFace = data[k];
  52409. }
  52410. // Fill the array accordingly.
  52411. if (byteArray) {
  52412. results.push(byteArray);
  52413. }
  52414. else {
  52415. results.push(dataFace);
  52416. }
  52417. }
  52418. return results;
  52419. };
  52420. this._texture = this.getScene().getEngine().createRawCubeTexture(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);
  52421. };
  52422. /**
  52423. * Occurs when the file is raw .hdr file.
  52424. */
  52425. HDRCubeTexture.prototype.loadHDRTexture = function () {
  52426. var _this = this;
  52427. var callback = function (buffer) {
  52428. // Extract the raw linear data.
  52429. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  52430. // Generate harmonics if needed.
  52431. if (_this._generateHarmonics) {
  52432. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  52433. }
  52434. var results = [];
  52435. var byteArray = null;
  52436. // Push each faces.
  52437. for (var j = 0; j < 6; j++) {
  52438. // Create uintarray fallback.
  52439. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52440. // 3 channels of 1 bytes per pixel in bytes.
  52441. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  52442. byteArray = new Uint8Array(byteBuffer);
  52443. }
  52444. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  52445. // If special cases.
  52446. if (_this._useInGammaSpace || byteArray) {
  52447. for (var i = 0; i < _this._size * _this._size; i++) {
  52448. // Put in gamma space if requested.
  52449. if (_this._useInGammaSpace) {
  52450. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52451. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52452. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52453. }
  52454. // Convert to int texture for fallback.
  52455. if (byteArray) {
  52456. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52457. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52458. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52459. // May use luminance instead if the result is not accurate.
  52460. var max = Math.max(Math.max(r, g), b);
  52461. if (max > 255) {
  52462. var scale = 255 / max;
  52463. r *= scale;
  52464. g *= scale;
  52465. b *= scale;
  52466. }
  52467. byteArray[(i * 3) + 0] = r;
  52468. byteArray[(i * 3) + 1] = g;
  52469. byteArray[(i * 3) + 2] = b;
  52470. }
  52471. }
  52472. }
  52473. if (byteArray) {
  52474. results.push(byteArray);
  52475. }
  52476. else {
  52477. results.push(dataFace);
  52478. }
  52479. }
  52480. return results;
  52481. };
  52482. var mipmapGenerator = null;
  52483. if (!this._noMipmap &&
  52484. this._usePMREMGenerator) {
  52485. mipmapGenerator = function (data) {
  52486. // Custom setup of the generator matching with the PBR shader values.
  52487. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  52488. return generator.filterCubeMap();
  52489. };
  52490. }
  52491. this._texture = this.getScene().getEngine().createRawCubeTexture(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);
  52492. };
  52493. /**
  52494. * Starts the loading process of the texture.
  52495. */
  52496. HDRCubeTexture.prototype.loadTexture = function () {
  52497. if (this._isBABYLONPreprocessed) {
  52498. this.loadBabylonTexture();
  52499. }
  52500. else {
  52501. this.loadHDRTexture();
  52502. }
  52503. };
  52504. HDRCubeTexture.prototype.clone = function () {
  52505. var size = this._isBABYLONPreprocessed ? null : this._size;
  52506. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  52507. // Base texture
  52508. newTexture.level = this.level;
  52509. newTexture.wrapU = this.wrapU;
  52510. newTexture.wrapV = this.wrapV;
  52511. newTexture.coordinatesIndex = this.coordinatesIndex;
  52512. newTexture.coordinatesMode = this.coordinatesMode;
  52513. return newTexture;
  52514. };
  52515. // Methods
  52516. HDRCubeTexture.prototype.delayLoad = function () {
  52517. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52518. return;
  52519. }
  52520. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52521. this._texture = this._getFromCache(this.url, this._noMipmap);
  52522. if (!this._texture) {
  52523. this.loadTexture();
  52524. }
  52525. };
  52526. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  52527. return this._textureMatrix;
  52528. };
  52529. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52530. var texture = null;
  52531. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52532. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  52533. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  52534. texture.name = parsedTexture.name;
  52535. texture.hasAlpha = parsedTexture.hasAlpha;
  52536. texture.level = parsedTexture.level;
  52537. texture.coordinatesMode = parsedTexture.coordinatesMode;
  52538. }
  52539. return texture;
  52540. };
  52541. HDRCubeTexture.prototype.serialize = function () {
  52542. if (!this.name) {
  52543. return null;
  52544. }
  52545. var serializationObject = {};
  52546. serializationObject.name = this.name;
  52547. serializationObject.hasAlpha = this.hasAlpha;
  52548. serializationObject.isCube = true;
  52549. serializationObject.level = this.level;
  52550. serializationObject.size = this._size;
  52551. serializationObject.coordinatesMode = this.coordinatesMode;
  52552. serializationObject.useInGammaSpace = this._useInGammaSpace;
  52553. serializationObject.generateHarmonics = this._generateHarmonics;
  52554. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  52555. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  52556. serializationObject.customType = "BABYLON.HDRCubeTexture";
  52557. serializationObject.noMipmap = this._noMipmap;
  52558. return serializationObject;
  52559. };
  52560. /**
  52561. * Saves as a file the data contained in the texture in a binary format.
  52562. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52563. * as the spherical used in the lighting.
  52564. * @param url The HDR file url.
  52565. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52566. * @param onError Method called if any error happens during download.
  52567. * @return The packed binary data.
  52568. */
  52569. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  52570. if (onError === void 0) { onError = null; }
  52571. var callback = function (buffer) {
  52572. var data = new Blob([buffer], { type: 'application/octet-stream' });
  52573. // Returns a URL you can use as a href.
  52574. var objUrl = window.URL.createObjectURL(data);
  52575. // Simulates a link to it and click to dowload.
  52576. var a = document.createElement("a");
  52577. document.body.appendChild(a);
  52578. a.style.display = "none";
  52579. a.href = objUrl;
  52580. a.download = "envmap.babylon.hdr";
  52581. a.click();
  52582. };
  52583. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  52584. };
  52585. /**
  52586. * Serializes the data contained in the texture in a binary format.
  52587. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52588. * as the spherical used in the lighting.
  52589. * @param url The HDR file url.
  52590. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52591. * @param onError Method called if any error happens during download.
  52592. * @return The packed binary data.
  52593. */
  52594. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  52595. if (onError === void 0) { onError = null; }
  52596. // Needs the url tho create the texture.
  52597. if (!url) {
  52598. return null;
  52599. }
  52600. // Check Power of two size.
  52601. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  52602. return null;
  52603. }
  52604. var getDataCallback = function (dataBuffer) {
  52605. // Extract the raw linear data.
  52606. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  52607. // Generate harmonics if needed.
  52608. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  52609. // Generate seamless faces
  52610. var mipGeneratorArray = [];
  52611. // Data are known to be in +X +Y +Z -X -Y -Z
  52612. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  52613. mipGeneratorArray.push(cubeData.right); // +X
  52614. mipGeneratorArray.push(cubeData.left); // -X
  52615. mipGeneratorArray.push(cubeData.up); // +Y
  52616. mipGeneratorArray.push(cubeData.down); // -Y
  52617. mipGeneratorArray.push(cubeData.front); // +Z
  52618. mipGeneratorArray.push(cubeData.back); // -Z
  52619. // Custom setup of the generator matching with the PBR shader values.
  52620. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  52621. var mippedData = generator.filterCubeMap();
  52622. // Compute required byte length.
  52623. var byteLength = 1 * 4; // Raw Data Version int32.
  52624. byteLength += 4; // CubeMap max mip face size int32.
  52625. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  52626. // Add data size.
  52627. byteLength += 4; // Number of mip levels int32.
  52628. for (var level = 0; level < mippedData.length; level++) {
  52629. var mipSize = size >> level;
  52630. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  52631. }
  52632. // Prepare binary structure.
  52633. var buffer = new ArrayBuffer(byteLength);
  52634. var intArrayView = new Int32Array(buffer);
  52635. var floatArrayView = new Float32Array(buffer);
  52636. // Fill header.
  52637. intArrayView[0] = 1; // Version 1.
  52638. intArrayView[1] = size; // CubeMap max mip face size.
  52639. // Fill polynomial information.
  52640. sphericalPolynomial.x.toArray(floatArrayView, 2);
  52641. sphericalPolynomial.y.toArray(floatArrayView, 5);
  52642. sphericalPolynomial.z.toArray(floatArrayView, 8);
  52643. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  52644. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  52645. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  52646. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  52647. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  52648. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  52649. // Fill pixel data.
  52650. intArrayView[29] = mippedData.length; // Number of mip levels.
  52651. var startIndex = 30;
  52652. for (var level = 0; level < mippedData.length; level++) {
  52653. // Fill each pixel of the mip level.
  52654. var faceSize = Math.pow(size >> level, 2) * 3;
  52655. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52656. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  52657. startIndex += faceSize;
  52658. }
  52659. }
  52660. // Callback.
  52661. callback(buffer);
  52662. };
  52663. // Download and process.
  52664. BABYLON.Tools.LoadFile(url, function (data) {
  52665. getDataCallback(data);
  52666. }, null, null, true, onError);
  52667. };
  52668. return HDRCubeTexture;
  52669. }(BABYLON.BaseTexture));
  52670. HDRCubeTexture._facesMapping = [
  52671. "right",
  52672. "up",
  52673. "front",
  52674. "left",
  52675. "down",
  52676. "back"
  52677. ];
  52678. BABYLON.HDRCubeTexture = HDRCubeTexture;
  52679. })(BABYLON || (BABYLON = {}));
  52680. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  52681. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  52682. // Huge respect for a such great lib.
  52683. // Earcut license:
  52684. // Copyright (c) 2016, Mapbox
  52685. //
  52686. // Permission to use, copy, modify, and/or distribute this software for any purpose
  52687. // with or without fee is hereby granted, provided that the above copyright notice
  52688. // and this permission notice appear in all copies.
  52689. //
  52690. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  52691. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  52692. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  52693. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  52694. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  52695. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  52696. // THIS SOFTWARE.
  52697. var Earcut;
  52698. (function (Earcut) {
  52699. /**
  52700. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  52701. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  52702. * @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).
  52703. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  52704. */
  52705. function earcut(data, holeIndices, dim) {
  52706. dim = dim || 2;
  52707. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  52708. if (!outerNode)
  52709. return triangles;
  52710. var minX, minY, maxX, maxY, x, y, size;
  52711. if (hasHoles)
  52712. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  52713. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  52714. if (data.length > 80 * dim) {
  52715. minX = maxX = data[0];
  52716. minY = maxY = data[1];
  52717. for (var i = dim; i < outerLen; i += dim) {
  52718. x = data[i];
  52719. y = data[i + 1];
  52720. if (x < minX)
  52721. minX = x;
  52722. if (y < minY)
  52723. minY = y;
  52724. if (x > maxX)
  52725. maxX = x;
  52726. if (y > maxY)
  52727. maxY = y;
  52728. }
  52729. // minX, minY and size are later used to transform coords into integers for z-order calculation
  52730. size = Math.max(maxX - minX, maxY - minY);
  52731. }
  52732. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  52733. return triangles;
  52734. }
  52735. Earcut.earcut = earcut;
  52736. // create a circular doubly linked list from polygon points in the specified winding order
  52737. function linkedList(data, start, end, dim, clockwise) {
  52738. var i, last;
  52739. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  52740. for (i = start; i < end; i += dim)
  52741. last = insertNode(i, data[i], data[i + 1], last);
  52742. }
  52743. else {
  52744. for (i = end - dim; i >= start; i -= dim)
  52745. last = insertNode(i, data[i], data[i + 1], last);
  52746. }
  52747. if (last && equals(last, last.next)) {
  52748. removeNode(last);
  52749. last = last.next;
  52750. }
  52751. return last;
  52752. }
  52753. // eliminate colinear or duplicate points
  52754. function filterPoints(start, end) {
  52755. if (!start)
  52756. return start;
  52757. if (!end)
  52758. end = start;
  52759. var p = start, again;
  52760. do {
  52761. again = false;
  52762. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  52763. removeNode(p);
  52764. p = end = p.prev;
  52765. if (p === p.next)
  52766. return null;
  52767. again = true;
  52768. }
  52769. else {
  52770. p = p.next;
  52771. }
  52772. } while (again || p !== end);
  52773. return end;
  52774. }
  52775. // main ear slicing loop which triangulates a polygon (given as a linked list)
  52776. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  52777. if (!ear)
  52778. return;
  52779. // interlink polygon nodes in z-order
  52780. if (!pass && size)
  52781. indexCurve(ear, minX, minY, size);
  52782. var stop = ear, prev, next;
  52783. // iterate through ears, slicing them one by one
  52784. while (ear.prev !== ear.next) {
  52785. prev = ear.prev;
  52786. next = ear.next;
  52787. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  52788. // cut off the triangle
  52789. triangles.push(prev.i / dim);
  52790. triangles.push(ear.i / dim);
  52791. triangles.push(next.i / dim);
  52792. removeNode(ear);
  52793. // skipping the next vertice leads to less sliver triangles
  52794. ear = next.next;
  52795. stop = next.next;
  52796. continue;
  52797. }
  52798. ear = next;
  52799. // if we looped through the whole remaining polygon and can't find any more ears
  52800. if (ear === stop) {
  52801. // try filtering points and slicing again
  52802. if (!pass) {
  52803. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  52804. // if this didn't work, try curing all small self-intersections locally
  52805. }
  52806. else if (pass === 1) {
  52807. ear = cureLocalIntersections(ear, triangles, dim);
  52808. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  52809. // as a last resort, try splitting the remaining polygon into two
  52810. }
  52811. else if (pass === 2) {
  52812. splitEarcut(ear, triangles, dim, minX, minY, size);
  52813. }
  52814. break;
  52815. }
  52816. }
  52817. }
  52818. // check whether a polygon node forms a valid ear with adjacent nodes
  52819. function isEar(ear) {
  52820. var a = ear.prev, b = ear, c = ear.next;
  52821. if (area(a, b, c) >= 0)
  52822. return false; // reflex, can't be an ear
  52823. // now make sure we don't have other points inside the potential ear
  52824. var p = ear.next.next;
  52825. while (p !== ear.prev) {
  52826. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  52827. area(p.prev, p, p.next) >= 0)
  52828. return false;
  52829. p = p.next;
  52830. }
  52831. return true;
  52832. }
  52833. function isEarHashed(ear, minX, minY, size) {
  52834. var a = ear.prev, b = ear, c = ear.next;
  52835. if (area(a, b, c) >= 0)
  52836. return false; // reflex, can't be an ear
  52837. // triangle bbox; min & max are calculated like this for speed
  52838. 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);
  52839. // z-order range for the current triangle bbox;
  52840. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  52841. // first look for points inside the triangle in increasing z-order
  52842. var p = ear.nextZ;
  52843. while (p && p.z <= maxZ) {
  52844. if (p !== ear.prev &&
  52845. p !== ear.next &&
  52846. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  52847. area(p.prev, p, p.next) >= 0)
  52848. return false;
  52849. p = p.nextZ;
  52850. }
  52851. // then look for points in decreasing z-order
  52852. p = ear.prevZ;
  52853. while (p && p.z >= minZ) {
  52854. if (p !== ear.prev &&
  52855. p !== ear.next &&
  52856. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  52857. area(p.prev, p, p.next) >= 0)
  52858. return false;
  52859. p = p.prevZ;
  52860. }
  52861. return true;
  52862. }
  52863. // go through all polygon nodes and cure small local self-intersections
  52864. function cureLocalIntersections(start, triangles, dim) {
  52865. var p = start;
  52866. do {
  52867. var a = p.prev, b = p.next.next;
  52868. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  52869. triangles.push(a.i / dim);
  52870. triangles.push(p.i / dim);
  52871. triangles.push(b.i / dim);
  52872. // remove two nodes involved
  52873. removeNode(p);
  52874. removeNode(p.next);
  52875. p = start = b;
  52876. }
  52877. p = p.next;
  52878. } while (p !== start);
  52879. return p;
  52880. }
  52881. // try splitting polygon into two and triangulate them independently
  52882. function splitEarcut(start, triangles, dim, minX, minY, size) {
  52883. // look for a valid diagonal that divides the polygon into two
  52884. var a = start;
  52885. do {
  52886. var b = a.next.next;
  52887. while (b !== a.prev) {
  52888. if (a.i !== b.i && isValidDiagonal(a, b)) {
  52889. // split the polygon in two by the diagonal
  52890. var c = splitPolygon(a, b);
  52891. // filter colinear points around the cuts
  52892. a = filterPoints(a, a.next);
  52893. c = filterPoints(c, c.next);
  52894. // run earcut on each half
  52895. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  52896. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  52897. return;
  52898. }
  52899. b = b.next;
  52900. }
  52901. a = a.next;
  52902. } while (a !== start);
  52903. }
  52904. // link every hole into the outer loop, producing a single-ring polygon without holes
  52905. function eliminateHoles(data, holeIndices, outerNode, dim) {
  52906. var queue = [], i, len, start, end, list;
  52907. for (i = 0, len = holeIndices.length; i < len; i++) {
  52908. start = holeIndices[i] * dim;
  52909. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  52910. list = linkedList(data, start, end, dim, false);
  52911. if (list === list.next)
  52912. list.steiner = true;
  52913. queue.push(getLeftmost(list));
  52914. }
  52915. queue.sort(compareX);
  52916. // process holes from left to right
  52917. for (i = 0; i < queue.length; i++) {
  52918. eliminateHole(queue[i], outerNode);
  52919. outerNode = filterPoints(outerNode, outerNode.next);
  52920. }
  52921. return outerNode;
  52922. }
  52923. function compareX(a, b) {
  52924. return a.x - b.x;
  52925. }
  52926. // find a bridge between vertices that connects hole with an outer ring and and link it
  52927. function eliminateHole(hole, outerNode) {
  52928. outerNode = findHoleBridge(hole, outerNode);
  52929. if (outerNode) {
  52930. var b = splitPolygon(outerNode, hole);
  52931. filterPoints(b, b.next);
  52932. }
  52933. }
  52934. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  52935. function findHoleBridge(hole, outerNode) {
  52936. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  52937. // find a segment intersected by a ray from the hole's leftmost point to the left;
  52938. // segment's endpoint with lesser x will be potential connection point
  52939. do {
  52940. if (hy <= p.y && hy >= p.next.y) {
  52941. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  52942. if (x <= hx && x > qx) {
  52943. qx = x;
  52944. if (x === hx) {
  52945. if (hy === p.y)
  52946. return p;
  52947. if (hy === p.next.y)
  52948. return p.next;
  52949. }
  52950. m = p.x < p.next.x ? p : p.next;
  52951. }
  52952. }
  52953. p = p.next;
  52954. } while (p !== outerNode);
  52955. if (!m)
  52956. return null;
  52957. if (hx === qx)
  52958. return m.prev; // hole touches outer segment; pick lower endpoint
  52959. // look for points inside the triangle of hole point, segment intersection and endpoint;
  52960. // if there are no points found, we have a valid connection;
  52961. // otherwise choose the point of the minimum angle with the ray as connection point
  52962. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  52963. p = m.next;
  52964. while (p !== stop) {
  52965. if (hx >= p.x &&
  52966. p.x >= mx &&
  52967. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  52968. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  52969. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  52970. m = p;
  52971. tanMin = tan;
  52972. }
  52973. }
  52974. p = p.next;
  52975. }
  52976. return m;
  52977. }
  52978. // interlink polygon nodes in z-order
  52979. function indexCurve(start, minX, minY, size) {
  52980. var p = start;
  52981. do {
  52982. if (p.z === null)
  52983. p.z = zOrder(p.x, p.y, minX, minY, size);
  52984. p.prevZ = p.prev;
  52985. p.nextZ = p.next;
  52986. p = p.next;
  52987. } while (p !== start);
  52988. p.prevZ.nextZ = null;
  52989. p.prevZ = null;
  52990. sortLinked(p);
  52991. }
  52992. // Simon Tatham's linked list merge sort algorithm
  52993. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  52994. function sortLinked(list) {
  52995. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  52996. do {
  52997. p = list;
  52998. list = null;
  52999. tail = null;
  53000. numMerges = 0;
  53001. while (p) {
  53002. numMerges++;
  53003. q = p;
  53004. pSize = 0;
  53005. for (i = 0; i < inSize; i++) {
  53006. pSize++;
  53007. q = q.nextZ;
  53008. if (!q)
  53009. break;
  53010. }
  53011. qSize = inSize;
  53012. while (pSize > 0 || (qSize > 0 && q)) {
  53013. if (pSize === 0) {
  53014. e = q;
  53015. q = q.nextZ;
  53016. qSize--;
  53017. }
  53018. else if (qSize === 0 || !q) {
  53019. e = p;
  53020. p = p.nextZ;
  53021. pSize--;
  53022. }
  53023. else if (p.z <= q.z) {
  53024. e = p;
  53025. p = p.nextZ;
  53026. pSize--;
  53027. }
  53028. else {
  53029. e = q;
  53030. q = q.nextZ;
  53031. qSize--;
  53032. }
  53033. if (tail)
  53034. tail.nextZ = e;
  53035. else
  53036. list = e;
  53037. e.prevZ = tail;
  53038. tail = e;
  53039. }
  53040. p = q;
  53041. }
  53042. tail.nextZ = null;
  53043. inSize *= 2;
  53044. } while (numMerges > 1);
  53045. return list;
  53046. }
  53047. // z-order of a point given coords and size of the data bounding box
  53048. function zOrder(x, y, minX, minY, size) {
  53049. // coords are transformed into non-negative 15-bit integer range
  53050. x = 32767 * (x - minX) / size;
  53051. y = 32767 * (y - minY) / size;
  53052. x = (x | (x << 8)) & 0x00FF00FF;
  53053. x = (x | (x << 4)) & 0x0F0F0F0F;
  53054. x = (x | (x << 2)) & 0x33333333;
  53055. x = (x | (x << 1)) & 0x55555555;
  53056. y = (y | (y << 8)) & 0x00FF00FF;
  53057. y = (y | (y << 4)) & 0x0F0F0F0F;
  53058. y = (y | (y << 2)) & 0x33333333;
  53059. y = (y | (y << 1)) & 0x55555555;
  53060. return x | (y << 1);
  53061. }
  53062. // find the leftmost node of a polygon ring
  53063. function getLeftmost(start) {
  53064. var p = start, leftmost = start;
  53065. do {
  53066. if (p.x < leftmost.x)
  53067. leftmost = p;
  53068. p = p.next;
  53069. } while (p !== start);
  53070. return leftmost;
  53071. }
  53072. // check if a point lies within a convex triangle
  53073. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  53074. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  53075. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  53076. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  53077. }
  53078. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  53079. function isValidDiagonal(a, b) {
  53080. return a.next.i !== b.i &&
  53081. a.prev.i !== b.i &&
  53082. !intersectsPolygon(a, b) &&
  53083. locallyInside(a, b) &&
  53084. locallyInside(b, a) &&
  53085. middleInside(a, b);
  53086. }
  53087. // signed area of a triangle
  53088. function area(p, q, r) {
  53089. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  53090. }
  53091. // check if two points are equal
  53092. function equals(p1, p2) {
  53093. return p1.x === p2.x && p1.y === p2.y;
  53094. }
  53095. // check if two segments intersect
  53096. function intersects(p1, q1, p2, q2) {
  53097. if ((equals(p1, q1) && equals(p2, q2)) ||
  53098. (equals(p1, q2) && equals(p2, q1)))
  53099. return true;
  53100. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  53101. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  53102. }
  53103. // check if a polygon diagonal intersects any polygon segments
  53104. function intersectsPolygon(a, b) {
  53105. var p = a;
  53106. do {
  53107. if (p.i !== a.i &&
  53108. p.next.i !== a.i &&
  53109. p.i !== b.i &&
  53110. p.next.i !== b.i &&
  53111. intersects(p, p.next, a, b))
  53112. return true;
  53113. p = p.next;
  53114. } while (p !== a);
  53115. return false;
  53116. }
  53117. // check if a polygon diagonal is locally inside the polygon
  53118. function locallyInside(a, b) {
  53119. return area(a.prev, a, a.next) < 0
  53120. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  53121. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  53122. }
  53123. // check if the middle point of a polygon diagonal is inside the polygon
  53124. function middleInside(a, b) {
  53125. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  53126. do {
  53127. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  53128. inside = !inside;
  53129. p = p.next;
  53130. } while (p !== a);
  53131. return inside;
  53132. }
  53133. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  53134. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  53135. function splitPolygon(a, b) {
  53136. 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;
  53137. a.next = b;
  53138. b.prev = a;
  53139. a2.next = an;
  53140. an.prev = a2;
  53141. b2.next = a2;
  53142. a2.prev = b2;
  53143. bp.next = b2;
  53144. b2.prev = bp;
  53145. return b2;
  53146. }
  53147. // create a node and optionally link it with previous one (in a circular doubly linked list)
  53148. function insertNode(i, x, y, last) {
  53149. var p = new Node(i, x, y);
  53150. if (!last) {
  53151. p.prev = p;
  53152. p.next = p;
  53153. }
  53154. else {
  53155. p.next = last.next;
  53156. p.prev = last;
  53157. last.next.prev = p;
  53158. last.next = p;
  53159. }
  53160. return p;
  53161. }
  53162. function removeNode(p) {
  53163. p.next.prev = p.prev;
  53164. p.prev.next = p.next;
  53165. if (p.prevZ)
  53166. p.prevZ.nextZ = p.nextZ;
  53167. if (p.nextZ)
  53168. p.nextZ.prevZ = p.prevZ;
  53169. }
  53170. function Node(i, x, y) {
  53171. // vertice index in coordinates array
  53172. this.i = i;
  53173. // vertex coordinates
  53174. this.x = x;
  53175. this.y = y;
  53176. // previous and next vertice nodes in a polygon ring
  53177. this.prev = null;
  53178. this.next = null;
  53179. // z-order curve value
  53180. this.z = null;
  53181. // previous and next nodes in z-order
  53182. this.prevZ = null;
  53183. this.nextZ = null;
  53184. // indicates whether this is a steiner point
  53185. this.steiner = false;
  53186. }
  53187. /**
  53188. * return a percentage difference between the polygon area and its triangulation area;
  53189. * used to verify correctness of triangulation
  53190. */
  53191. function deviation(data, holeIndices, dim, triangles) {
  53192. var hasHoles = holeIndices && holeIndices.length;
  53193. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  53194. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  53195. if (hasHoles) {
  53196. for (var i = 0, len = holeIndices.length; i < len; i++) {
  53197. var start = holeIndices[i] * dim;
  53198. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  53199. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  53200. }
  53201. }
  53202. var trianglesArea = 0;
  53203. for (i = 0; i < triangles.length; i += 3) {
  53204. var a = triangles[i] * dim;
  53205. var b = triangles[i + 1] * dim;
  53206. var c = triangles[i + 2] * dim;
  53207. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  53208. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  53209. }
  53210. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  53211. }
  53212. Earcut.deviation = deviation;
  53213. ;
  53214. function signedArea(data, start, end, dim) {
  53215. var sum = 0;
  53216. for (var i = start, j = end - dim; i < end; i += dim) {
  53217. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  53218. j = i;
  53219. }
  53220. return sum;
  53221. }
  53222. /**
  53223. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  53224. */
  53225. function flatten(data) {
  53226. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  53227. for (var i = 0; i < data.length; i++) {
  53228. for (var j = 0; j < data[i].length; j++) {
  53229. for (var d = 0; d < dim; d++)
  53230. result.vertices.push(data[i][j][d]);
  53231. }
  53232. if (i > 0) {
  53233. holeIndex += data[i - 1].length;
  53234. result.holes.push(holeIndex);
  53235. }
  53236. }
  53237. return result;
  53238. }
  53239. Earcut.flatten = flatten;
  53240. ;
  53241. })(Earcut || (Earcut = {}));
  53242. //# sourceMappingURL=babylon.earcut.js.map
  53243. /// <reference path="..\Math\babylon.math.ts" />
  53244. var BABYLON;
  53245. (function (BABYLON) {
  53246. var IndexedVector2 = (function (_super) {
  53247. __extends(IndexedVector2, _super);
  53248. function IndexedVector2(original, index) {
  53249. var _this = _super.call(this, original.x, original.y) || this;
  53250. _this.index = index;
  53251. return _this;
  53252. }
  53253. return IndexedVector2;
  53254. }(BABYLON.Vector2));
  53255. var PolygonPoints = (function () {
  53256. function PolygonPoints() {
  53257. this.elements = new Array();
  53258. }
  53259. PolygonPoints.prototype.add = function (originalPoints) {
  53260. var _this = this;
  53261. var result = new Array();
  53262. originalPoints.forEach(function (point) {
  53263. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  53264. var newPoint = new IndexedVector2(point, _this.elements.length);
  53265. result.push(newPoint);
  53266. _this.elements.push(newPoint);
  53267. }
  53268. });
  53269. return result;
  53270. };
  53271. PolygonPoints.prototype.computeBounds = function () {
  53272. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53273. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53274. this.elements.forEach(function (point) {
  53275. // x
  53276. if (point.x < lmin.x) {
  53277. lmin.x = point.x;
  53278. }
  53279. else if (point.x > lmax.x) {
  53280. lmax.x = point.x;
  53281. }
  53282. // y
  53283. if (point.y < lmin.y) {
  53284. lmin.y = point.y;
  53285. }
  53286. else if (point.y > lmax.y) {
  53287. lmax.y = point.y;
  53288. }
  53289. });
  53290. return {
  53291. min: lmin,
  53292. max: lmax,
  53293. width: lmax.x - lmin.x,
  53294. height: lmax.y - lmin.y
  53295. };
  53296. };
  53297. return PolygonPoints;
  53298. }());
  53299. var Polygon = (function () {
  53300. function Polygon() {
  53301. }
  53302. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  53303. return [
  53304. new BABYLON.Vector2(xmin, ymin),
  53305. new BABYLON.Vector2(xmax, ymin),
  53306. new BABYLON.Vector2(xmax, ymax),
  53307. new BABYLON.Vector2(xmin, ymax)
  53308. ];
  53309. };
  53310. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  53311. if (cx === void 0) { cx = 0; }
  53312. if (cy === void 0) { cy = 0; }
  53313. if (numberOfSides === void 0) { numberOfSides = 32; }
  53314. var result = new Array();
  53315. var angle = 0;
  53316. var increment = (Math.PI * 2) / numberOfSides;
  53317. for (var i = 0; i < numberOfSides; i++) {
  53318. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  53319. angle -= increment;
  53320. }
  53321. return result;
  53322. };
  53323. Polygon.Parse = function (input) {
  53324. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  53325. var i, result = [];
  53326. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  53327. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  53328. }
  53329. return result;
  53330. };
  53331. Polygon.StartingAt = function (x, y) {
  53332. return BABYLON.Path2.StartingAt(x, y);
  53333. };
  53334. return Polygon;
  53335. }());
  53336. BABYLON.Polygon = Polygon;
  53337. var PolygonMeshBuilder = (function () {
  53338. function PolygonMeshBuilder(name, contours, scene) {
  53339. this._points = new PolygonPoints();
  53340. this._outlinepoints = new PolygonPoints();
  53341. this._holes = [];
  53342. this._epoints = new Array();
  53343. this._eholes = new Array();
  53344. this._name = name;
  53345. this._scene = scene;
  53346. var points;
  53347. if (contours instanceof BABYLON.Path2) {
  53348. points = contours.getPoints();
  53349. }
  53350. else {
  53351. points = contours;
  53352. }
  53353. this._addToepoint(points);
  53354. this._points.add(points);
  53355. this._outlinepoints.add(points);
  53356. }
  53357. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  53358. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  53359. var p = points_1[_i];
  53360. this._epoints.push(p.x, p.y);
  53361. }
  53362. };
  53363. PolygonMeshBuilder.prototype.addHole = function (hole) {
  53364. this._points.add(hole);
  53365. var holepoints = new PolygonPoints();
  53366. holepoints.add(hole);
  53367. this._holes.push(holepoints);
  53368. this._eholes.push(this._epoints.length / 2);
  53369. this._addToepoint(hole);
  53370. return this;
  53371. };
  53372. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  53373. var _this = this;
  53374. if (updatable === void 0) { updatable = false; }
  53375. var result = new BABYLON.Mesh(this._name, this._scene);
  53376. var normals = [];
  53377. var positions = [];
  53378. var uvs = [];
  53379. var bounds = this._points.computeBounds();
  53380. this._points.elements.forEach(function (p) {
  53381. normals.push(0, 1.0, 0);
  53382. positions.push(p.x, 0, p.y);
  53383. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  53384. });
  53385. var indices = [];
  53386. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  53387. for (var i = 0; i < res.length; i++) {
  53388. indices.push(res[i]);
  53389. }
  53390. if (depth > 0) {
  53391. var positionscount = (positions.length / 3); //get the current pointcount
  53392. this._points.elements.forEach(function (p) {
  53393. normals.push(0, -1.0, 0);
  53394. positions.push(p.x, -depth, p.y);
  53395. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  53396. });
  53397. var totalCount = indices.length;
  53398. for (var i = 0; i < totalCount; i += 3) {
  53399. var i0 = indices[i + 0];
  53400. var i1 = indices[i + 1];
  53401. var i2 = indices[i + 2];
  53402. indices.push(i2 + positionscount);
  53403. indices.push(i1 + positionscount);
  53404. indices.push(i0 + positionscount);
  53405. }
  53406. //Add the sides
  53407. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  53408. this._holes.forEach(function (hole) {
  53409. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  53410. });
  53411. }
  53412. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  53413. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  53414. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  53415. result.setIndices(indices);
  53416. return result;
  53417. };
  53418. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  53419. var StartIndex = positions.length / 3;
  53420. var ulength = 0;
  53421. for (var i = 0; i < points.elements.length; i++) {
  53422. var p = points.elements[i];
  53423. var p1;
  53424. if ((i + 1) > points.elements.length - 1) {
  53425. p1 = points.elements[0];
  53426. }
  53427. else {
  53428. p1 = points.elements[i + 1];
  53429. }
  53430. positions.push(p.x, 0, p.y);
  53431. positions.push(p.x, -depth, p.y);
  53432. positions.push(p1.x, 0, p1.y);
  53433. positions.push(p1.x, -depth, p1.y);
  53434. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  53435. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  53436. var v3 = v2.subtract(v1);
  53437. var v4 = new BABYLON.Vector3(0, 1, 0);
  53438. var vn = BABYLON.Vector3.Cross(v3, v4);
  53439. vn = vn.normalize();
  53440. uvs.push(ulength / bounds.width, 0);
  53441. uvs.push(ulength / bounds.width, 1);
  53442. ulength += v3.length();
  53443. uvs.push((ulength / bounds.width), 0);
  53444. uvs.push((ulength / bounds.width), 1);
  53445. if (!flip) {
  53446. normals.push(-vn.x, -vn.y, -vn.z);
  53447. normals.push(-vn.x, -vn.y, -vn.z);
  53448. normals.push(-vn.x, -vn.y, -vn.z);
  53449. normals.push(-vn.x, -vn.y, -vn.z);
  53450. indices.push(StartIndex);
  53451. indices.push(StartIndex + 1);
  53452. indices.push(StartIndex + 2);
  53453. indices.push(StartIndex + 1);
  53454. indices.push(StartIndex + 3);
  53455. indices.push(StartIndex + 2);
  53456. }
  53457. else {
  53458. normals.push(vn.x, vn.y, vn.z);
  53459. normals.push(vn.x, vn.y, vn.z);
  53460. normals.push(vn.x, vn.y, vn.z);
  53461. normals.push(vn.x, vn.y, vn.z);
  53462. indices.push(StartIndex);
  53463. indices.push(StartIndex + 2);
  53464. indices.push(StartIndex + 1);
  53465. indices.push(StartIndex + 1);
  53466. indices.push(StartIndex + 2);
  53467. indices.push(StartIndex + 3);
  53468. }
  53469. StartIndex += 4;
  53470. }
  53471. ;
  53472. };
  53473. return PolygonMeshBuilder;
  53474. }());
  53475. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  53476. })(BABYLON || (BABYLON = {}));
  53477. //# sourceMappingURL=babylon.polygonMesh.js.map
  53478. var BABYLON;
  53479. (function (BABYLON) {
  53480. // Unique ID when we import meshes from Babylon to CSG
  53481. var currentCSGMeshId = 0;
  53482. // # class Vertex
  53483. // Represents a vertex of a polygon. Use your own vertex class instead of this
  53484. // one to provide additional features like texture coordinates and vertex
  53485. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  53486. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  53487. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  53488. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  53489. // is not used anywhere else.
  53490. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  53491. var Vertex = (function () {
  53492. function Vertex(pos, normal, uv) {
  53493. this.pos = pos;
  53494. this.normal = normal;
  53495. this.uv = uv;
  53496. }
  53497. Vertex.prototype.clone = function () {
  53498. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  53499. };
  53500. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  53501. // orientation of a polygon is flipped.
  53502. Vertex.prototype.flip = function () {
  53503. this.normal = this.normal.scale(-1);
  53504. };
  53505. // Create a new vertex between this vertex and `other` by linearly
  53506. // interpolating all properties using a parameter of `t`. Subclasses should
  53507. // override this to interpolate additional properties.
  53508. Vertex.prototype.interpolate = function (other, t) {
  53509. 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));
  53510. };
  53511. return Vertex;
  53512. }());
  53513. // # class Plane
  53514. // Represents a plane in 3D space.
  53515. var Plane = (function () {
  53516. function Plane(normal, w) {
  53517. this.normal = normal;
  53518. this.w = w;
  53519. }
  53520. Plane.FromPoints = function (a, b, c) {
  53521. var v0 = c.subtract(a);
  53522. var v1 = b.subtract(a);
  53523. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  53524. return null;
  53525. }
  53526. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  53527. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  53528. };
  53529. Plane.prototype.clone = function () {
  53530. return new Plane(this.normal.clone(), this.w);
  53531. };
  53532. Plane.prototype.flip = function () {
  53533. this.normal.scaleInPlace(-1);
  53534. this.w = -this.w;
  53535. };
  53536. // Split `polygon` by this plane if needed, then put the polygon or polygon
  53537. // fragments in the appropriate lists. Coplanar polygons go into either
  53538. // `coplanarFront` or `coplanarBack` depending on their orientation with
  53539. // respect to this plane. Polygons in front or in back of this plane go into
  53540. // either `front` or `back`.
  53541. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  53542. var COPLANAR = 0;
  53543. var FRONT = 1;
  53544. var BACK = 2;
  53545. var SPANNING = 3;
  53546. // Classify each point as well as the entire polygon into one of the above
  53547. // four classes.
  53548. var polygonType = 0;
  53549. var types = [];
  53550. var i;
  53551. var t;
  53552. for (i = 0; i < polygon.vertices.length; i++) {
  53553. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  53554. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  53555. polygonType |= type;
  53556. types.push(type);
  53557. }
  53558. // Put the polygon in the correct list, splitting it when necessary.
  53559. switch (polygonType) {
  53560. case COPLANAR:
  53561. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  53562. break;
  53563. case FRONT:
  53564. front.push(polygon);
  53565. break;
  53566. case BACK:
  53567. back.push(polygon);
  53568. break;
  53569. case SPANNING:
  53570. var f = [], b = [];
  53571. for (i = 0; i < polygon.vertices.length; i++) {
  53572. var j = (i + 1) % polygon.vertices.length;
  53573. var ti = types[i], tj = types[j];
  53574. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  53575. if (ti !== BACK)
  53576. f.push(vi);
  53577. if (ti !== FRONT)
  53578. b.push(ti !== BACK ? vi.clone() : vi);
  53579. if ((ti | tj) === SPANNING) {
  53580. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  53581. var v = vi.interpolate(vj, t);
  53582. f.push(v);
  53583. b.push(v.clone());
  53584. }
  53585. }
  53586. var poly;
  53587. if (f.length >= 3) {
  53588. poly = new Polygon(f, polygon.shared);
  53589. if (poly.plane)
  53590. front.push(poly);
  53591. }
  53592. if (b.length >= 3) {
  53593. poly = new Polygon(b, polygon.shared);
  53594. if (poly.plane)
  53595. back.push(poly);
  53596. }
  53597. break;
  53598. }
  53599. };
  53600. return Plane;
  53601. }());
  53602. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  53603. // point is on the plane.
  53604. Plane.EPSILON = 1e-5;
  53605. // # class Polygon
  53606. // Represents a convex polygon. The vertices used to initialize a polygon must
  53607. // be coplanar and form a convex loop.
  53608. //
  53609. // Each convex polygon has a `shared` property, which is shared between all
  53610. // polygons that are clones of each other or were split from the same polygon.
  53611. // This can be used to define per-polygon properties (such as surface color).
  53612. var Polygon = (function () {
  53613. function Polygon(vertices, shared) {
  53614. this.vertices = vertices;
  53615. this.shared = shared;
  53616. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  53617. }
  53618. Polygon.prototype.clone = function () {
  53619. var vertices = this.vertices.map(function (v) { return v.clone(); });
  53620. return new Polygon(vertices, this.shared);
  53621. };
  53622. Polygon.prototype.flip = function () {
  53623. this.vertices.reverse().map(function (v) { v.flip(); });
  53624. this.plane.flip();
  53625. };
  53626. return Polygon;
  53627. }());
  53628. // # class Node
  53629. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  53630. // by picking a polygon to split along. That polygon (and all other coplanar
  53631. // polygons) are added directly to that node and the other polygons are added to
  53632. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  53633. // no distinction between internal and leaf nodes.
  53634. var Node = (function () {
  53635. function Node(polygons) {
  53636. this.plane = null;
  53637. this.front = null;
  53638. this.back = null;
  53639. this.polygons = [];
  53640. if (polygons) {
  53641. this.build(polygons);
  53642. }
  53643. }
  53644. Node.prototype.clone = function () {
  53645. var node = new Node();
  53646. node.plane = this.plane && this.plane.clone();
  53647. node.front = this.front && this.front.clone();
  53648. node.back = this.back && this.back.clone();
  53649. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  53650. return node;
  53651. };
  53652. // Convert solid space to empty space and empty space to solid space.
  53653. Node.prototype.invert = function () {
  53654. for (var i = 0; i < this.polygons.length; i++) {
  53655. this.polygons[i].flip();
  53656. }
  53657. if (this.plane) {
  53658. this.plane.flip();
  53659. }
  53660. if (this.front) {
  53661. this.front.invert();
  53662. }
  53663. if (this.back) {
  53664. this.back.invert();
  53665. }
  53666. var temp = this.front;
  53667. this.front = this.back;
  53668. this.back = temp;
  53669. };
  53670. // Recursively remove all polygons in `polygons` that are inside this BSP
  53671. // tree.
  53672. Node.prototype.clipPolygons = function (polygons) {
  53673. if (!this.plane)
  53674. return polygons.slice();
  53675. var front = [], back = [];
  53676. for (var i = 0; i < polygons.length; i++) {
  53677. this.plane.splitPolygon(polygons[i], front, back, front, back);
  53678. }
  53679. if (this.front) {
  53680. front = this.front.clipPolygons(front);
  53681. }
  53682. if (this.back) {
  53683. back = this.back.clipPolygons(back);
  53684. }
  53685. else {
  53686. back = [];
  53687. }
  53688. return front.concat(back);
  53689. };
  53690. // Remove all polygons in this BSP tree that are inside the other BSP tree
  53691. // `bsp`.
  53692. Node.prototype.clipTo = function (bsp) {
  53693. this.polygons = bsp.clipPolygons(this.polygons);
  53694. if (this.front)
  53695. this.front.clipTo(bsp);
  53696. if (this.back)
  53697. this.back.clipTo(bsp);
  53698. };
  53699. // Return a list of all polygons in this BSP tree.
  53700. Node.prototype.allPolygons = function () {
  53701. var polygons = this.polygons.slice();
  53702. if (this.front)
  53703. polygons = polygons.concat(this.front.allPolygons());
  53704. if (this.back)
  53705. polygons = polygons.concat(this.back.allPolygons());
  53706. return polygons;
  53707. };
  53708. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  53709. // new polygons are filtered down to the bottom of the tree and become new
  53710. // nodes there. Each set of polygons is partitioned using the first polygon
  53711. // (no heuristic is used to pick a good split).
  53712. Node.prototype.build = function (polygons) {
  53713. if (!polygons.length)
  53714. return;
  53715. if (!this.plane)
  53716. this.plane = polygons[0].plane.clone();
  53717. var front = [], back = [];
  53718. for (var i = 0; i < polygons.length; i++) {
  53719. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  53720. }
  53721. if (front.length) {
  53722. if (!this.front)
  53723. this.front = new Node();
  53724. this.front.build(front);
  53725. }
  53726. if (back.length) {
  53727. if (!this.back)
  53728. this.back = new Node();
  53729. this.back.build(back);
  53730. }
  53731. };
  53732. return Node;
  53733. }());
  53734. var CSG = (function () {
  53735. function CSG() {
  53736. this.polygons = new Array();
  53737. }
  53738. // Convert BABYLON.Mesh to BABYLON.CSG
  53739. CSG.FromMesh = function (mesh) {
  53740. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  53741. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  53742. if (mesh instanceof BABYLON.Mesh) {
  53743. mesh.computeWorldMatrix(true);
  53744. matrix = mesh.getWorldMatrix();
  53745. meshPosition = mesh.position.clone();
  53746. meshRotation = mesh.rotation.clone();
  53747. if (mesh.rotationQuaternion) {
  53748. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  53749. }
  53750. meshScaling = mesh.scaling.clone();
  53751. }
  53752. else {
  53753. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  53754. }
  53755. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53756. var subMeshes = mesh.subMeshes;
  53757. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  53758. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  53759. vertices = [];
  53760. for (var j = 0; j < 3; j++) {
  53761. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  53762. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  53763. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  53764. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  53765. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  53766. vertex = new Vertex(position, normal, uv);
  53767. vertices.push(vertex);
  53768. }
  53769. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  53770. // To handle the case of degenerated triangle
  53771. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  53772. if (polygon.plane)
  53773. polygons.push(polygon);
  53774. }
  53775. }
  53776. var csg = CSG.FromPolygons(polygons);
  53777. csg.matrix = matrix;
  53778. csg.position = meshPosition;
  53779. csg.rotation = meshRotation;
  53780. csg.scaling = meshScaling;
  53781. csg.rotationQuaternion = meshRotationQuaternion;
  53782. currentCSGMeshId++;
  53783. return csg;
  53784. };
  53785. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  53786. CSG.FromPolygons = function (polygons) {
  53787. var csg = new CSG();
  53788. csg.polygons = polygons;
  53789. return csg;
  53790. };
  53791. CSG.prototype.clone = function () {
  53792. var csg = new CSG();
  53793. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  53794. csg.copyTransformAttributes(this);
  53795. return csg;
  53796. };
  53797. CSG.prototype.toPolygons = function () {
  53798. return this.polygons;
  53799. };
  53800. CSG.prototype.union = function (csg) {
  53801. var a = new Node(this.clone().polygons);
  53802. var b = new Node(csg.clone().polygons);
  53803. a.clipTo(b);
  53804. b.clipTo(a);
  53805. b.invert();
  53806. b.clipTo(a);
  53807. b.invert();
  53808. a.build(b.allPolygons());
  53809. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  53810. };
  53811. CSG.prototype.unionInPlace = function (csg) {
  53812. var a = new Node(this.polygons);
  53813. var b = new Node(csg.polygons);
  53814. a.clipTo(b);
  53815. b.clipTo(a);
  53816. b.invert();
  53817. b.clipTo(a);
  53818. b.invert();
  53819. a.build(b.allPolygons());
  53820. this.polygons = a.allPolygons();
  53821. };
  53822. CSG.prototype.subtract = function (csg) {
  53823. var a = new Node(this.clone().polygons);
  53824. var b = new Node(csg.clone().polygons);
  53825. a.invert();
  53826. a.clipTo(b);
  53827. b.clipTo(a);
  53828. b.invert();
  53829. b.clipTo(a);
  53830. b.invert();
  53831. a.build(b.allPolygons());
  53832. a.invert();
  53833. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  53834. };
  53835. CSG.prototype.subtractInPlace = function (csg) {
  53836. var a = new Node(this.polygons);
  53837. var b = new Node(csg.polygons);
  53838. a.invert();
  53839. a.clipTo(b);
  53840. b.clipTo(a);
  53841. b.invert();
  53842. b.clipTo(a);
  53843. b.invert();
  53844. a.build(b.allPolygons());
  53845. a.invert();
  53846. this.polygons = a.allPolygons();
  53847. };
  53848. CSG.prototype.intersect = function (csg) {
  53849. var a = new Node(this.clone().polygons);
  53850. var b = new Node(csg.clone().polygons);
  53851. a.invert();
  53852. b.clipTo(a);
  53853. b.invert();
  53854. a.clipTo(b);
  53855. b.clipTo(a);
  53856. a.build(b.allPolygons());
  53857. a.invert();
  53858. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  53859. };
  53860. CSG.prototype.intersectInPlace = function (csg) {
  53861. var a = new Node(this.polygons);
  53862. var b = new Node(csg.polygons);
  53863. a.invert();
  53864. b.clipTo(a);
  53865. b.invert();
  53866. a.clipTo(b);
  53867. b.clipTo(a);
  53868. a.build(b.allPolygons());
  53869. a.invert();
  53870. this.polygons = a.allPolygons();
  53871. };
  53872. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  53873. // not modified.
  53874. CSG.prototype.inverse = function () {
  53875. var csg = this.clone();
  53876. csg.inverseInPlace();
  53877. return csg;
  53878. };
  53879. CSG.prototype.inverseInPlace = function () {
  53880. this.polygons.map(function (p) { p.flip(); });
  53881. };
  53882. // This is used to keep meshes transformations so they can be restored
  53883. // when we build back a Babylon Mesh
  53884. // NB : All CSG operations are performed in world coordinates
  53885. CSG.prototype.copyTransformAttributes = function (csg) {
  53886. this.matrix = csg.matrix;
  53887. this.position = csg.position;
  53888. this.rotation = csg.rotation;
  53889. this.scaling = csg.scaling;
  53890. this.rotationQuaternion = csg.rotationQuaternion;
  53891. return this;
  53892. };
  53893. // Build Raw mesh from CSG
  53894. // Coordinates here are in world space
  53895. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  53896. var matrix = this.matrix.clone();
  53897. matrix.invert();
  53898. 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;
  53899. if (keepSubMeshes) {
  53900. // Sort Polygons, since subMeshes are indices range
  53901. polygons.sort(function (a, b) {
  53902. if (a.shared.meshId === b.shared.meshId) {
  53903. return a.shared.subMeshId - b.shared.subMeshId;
  53904. }
  53905. else {
  53906. return a.shared.meshId - b.shared.meshId;
  53907. }
  53908. });
  53909. }
  53910. for (var i = 0, il = polygons.length; i < il; i++) {
  53911. polygon = polygons[i];
  53912. // Building SubMeshes
  53913. if (!subMesh_dict[polygon.shared.meshId]) {
  53914. subMesh_dict[polygon.shared.meshId] = {};
  53915. }
  53916. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  53917. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  53918. indexStart: +Infinity,
  53919. indexEnd: -Infinity,
  53920. materialIndex: polygon.shared.materialIndex
  53921. };
  53922. }
  53923. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  53924. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  53925. polygonIndices[0] = 0;
  53926. polygonIndices[1] = j - 1;
  53927. polygonIndices[2] = j;
  53928. for (var k = 0; k < 3; k++) {
  53929. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  53930. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  53931. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  53932. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  53933. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  53934. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  53935. // Check if 2 points can be merged
  53936. if (!(typeof vertex_idx !== 'undefined' &&
  53937. normals[vertex_idx * 3] === localNormal.x &&
  53938. normals[vertex_idx * 3 + 1] === localNormal.y &&
  53939. normals[vertex_idx * 3 + 2] === localNormal.z &&
  53940. uvs[vertex_idx * 2] === uv.x &&
  53941. uvs[vertex_idx * 2 + 1] === uv.y)) {
  53942. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  53943. uvs.push(uv.x, uv.y);
  53944. normals.push(normal.x, normal.y, normal.z);
  53945. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  53946. }
  53947. indices.push(vertex_idx);
  53948. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  53949. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  53950. currentIndex++;
  53951. }
  53952. }
  53953. }
  53954. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  53955. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  53956. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  53957. mesh.setIndices(indices);
  53958. if (keepSubMeshes) {
  53959. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  53960. var materialIndexOffset = 0, materialMaxIndex;
  53961. mesh.subMeshes = new Array();
  53962. for (var m in subMesh_dict) {
  53963. materialMaxIndex = -1;
  53964. for (var sm in subMesh_dict[m]) {
  53965. subMesh_obj = subMesh_dict[m][sm];
  53966. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  53967. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  53968. }
  53969. materialIndexOffset += ++materialMaxIndex;
  53970. }
  53971. }
  53972. return mesh;
  53973. };
  53974. // Build Mesh from CSG taking material and transforms into account
  53975. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  53976. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  53977. mesh.material = material;
  53978. mesh.position.copyFrom(this.position);
  53979. mesh.rotation.copyFrom(this.rotation);
  53980. if (this.rotationQuaternion) {
  53981. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  53982. }
  53983. mesh.scaling.copyFrom(this.scaling);
  53984. mesh.computeWorldMatrix(true);
  53985. return mesh;
  53986. };
  53987. return CSG;
  53988. }());
  53989. BABYLON.CSG = CSG;
  53990. })(BABYLON || (BABYLON = {}));
  53991. //# sourceMappingURL=babylon.csg.js.map
  53992. var BABYLON;
  53993. (function (BABYLON) {
  53994. var LensFlare = (function () {
  53995. function LensFlare(size, position, color, imgUrl, system) {
  53996. this.size = size;
  53997. this.position = position;
  53998. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  53999. this.dispose = function () {
  54000. if (this.texture) {
  54001. this.texture.dispose();
  54002. }
  54003. // Remove from scene
  54004. var index = this._system.lensFlares.indexOf(this);
  54005. this._system.lensFlares.splice(index, 1);
  54006. };
  54007. this.color = color || new BABYLON.Color3(1, 1, 1);
  54008. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  54009. this._system = system;
  54010. system.lensFlares.push(this);
  54011. }
  54012. return LensFlare;
  54013. }());
  54014. BABYLON.LensFlare = LensFlare;
  54015. })(BABYLON || (BABYLON = {}));
  54016. //# sourceMappingURL=babylon.lensFlare.js.map
  54017. var BABYLON;
  54018. (function (BABYLON) {
  54019. var LensFlareSystem = (function () {
  54020. function LensFlareSystem(name, emitter, scene) {
  54021. this.name = name;
  54022. this.lensFlares = new Array();
  54023. this.borderLimit = 300;
  54024. this.viewportBorder = 0;
  54025. this.layerMask = 0x0FFFFFFF;
  54026. this._vertexBuffers = {};
  54027. this._isEnabled = true;
  54028. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  54029. this._emitter = emitter;
  54030. this.id = name;
  54031. scene.lensFlareSystems.push(this);
  54032. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  54033. var engine = scene.getEngine();
  54034. // VBO
  54035. var vertices = [];
  54036. vertices.push(1, 1);
  54037. vertices.push(-1, 1);
  54038. vertices.push(-1, -1);
  54039. vertices.push(1, -1);
  54040. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  54041. // Indices
  54042. var indices = [];
  54043. indices.push(0);
  54044. indices.push(1);
  54045. indices.push(2);
  54046. indices.push(0);
  54047. indices.push(2);
  54048. indices.push(3);
  54049. this._indexBuffer = engine.createIndexBuffer(indices);
  54050. // Effects
  54051. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  54052. }
  54053. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  54054. get: function () {
  54055. return this._isEnabled;
  54056. },
  54057. set: function (value) {
  54058. this._isEnabled = value;
  54059. },
  54060. enumerable: true,
  54061. configurable: true
  54062. });
  54063. LensFlareSystem.prototype.getScene = function () {
  54064. return this._scene;
  54065. };
  54066. LensFlareSystem.prototype.getEmitter = function () {
  54067. return this._emitter;
  54068. };
  54069. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  54070. this._emitter = newEmitter;
  54071. };
  54072. LensFlareSystem.prototype.getEmitterPosition = function () {
  54073. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  54074. };
  54075. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  54076. var position = this.getEmitterPosition();
  54077. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  54078. this._positionX = position.x;
  54079. this._positionY = position.y;
  54080. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  54081. if (this.viewportBorder > 0) {
  54082. globalViewport.x -= this.viewportBorder;
  54083. globalViewport.y -= this.viewportBorder;
  54084. globalViewport.width += this.viewportBorder * 2;
  54085. globalViewport.height += this.viewportBorder * 2;
  54086. position.x += this.viewportBorder;
  54087. position.y += this.viewportBorder;
  54088. this._positionX += this.viewportBorder;
  54089. this._positionY += this.viewportBorder;
  54090. }
  54091. if (position.z > 0) {
  54092. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  54093. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  54094. return true;
  54095. }
  54096. return true;
  54097. }
  54098. return false;
  54099. };
  54100. LensFlareSystem.prototype._isVisible = function () {
  54101. if (!this._isEnabled) {
  54102. return false;
  54103. }
  54104. var emitterPosition = this.getEmitterPosition();
  54105. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  54106. var distance = direction.length();
  54107. direction.normalize();
  54108. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  54109. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  54110. return !pickInfo.hit || pickInfo.distance > distance;
  54111. };
  54112. LensFlareSystem.prototype.render = function () {
  54113. if (!this._effect.isReady())
  54114. return false;
  54115. var engine = this._scene.getEngine();
  54116. var viewport = this._scene.activeCamera.viewport;
  54117. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  54118. // Position
  54119. if (!this.computeEffectivePosition(globalViewport)) {
  54120. return false;
  54121. }
  54122. // Visibility
  54123. if (!this._isVisible()) {
  54124. return false;
  54125. }
  54126. // Intensity
  54127. var awayX;
  54128. var awayY;
  54129. if (this._positionX < this.borderLimit + globalViewport.x) {
  54130. awayX = this.borderLimit + globalViewport.x - this._positionX;
  54131. }
  54132. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  54133. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  54134. }
  54135. else {
  54136. awayX = 0;
  54137. }
  54138. if (this._positionY < this.borderLimit + globalViewport.y) {
  54139. awayY = this.borderLimit + globalViewport.y - this._positionY;
  54140. }
  54141. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  54142. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  54143. }
  54144. else {
  54145. awayY = 0;
  54146. }
  54147. var away = (awayX > awayY) ? awayX : awayY;
  54148. away -= this.viewportBorder;
  54149. if (away > this.borderLimit) {
  54150. away = this.borderLimit;
  54151. }
  54152. var intensity = 1.0 - (away / this.borderLimit);
  54153. if (intensity < 0) {
  54154. return false;
  54155. }
  54156. if (intensity > 1.0) {
  54157. intensity = 1.0;
  54158. }
  54159. if (this.viewportBorder > 0) {
  54160. globalViewport.x += this.viewportBorder;
  54161. globalViewport.y += this.viewportBorder;
  54162. globalViewport.width -= this.viewportBorder * 2;
  54163. globalViewport.height -= this.viewportBorder * 2;
  54164. this._positionX -= this.viewportBorder;
  54165. this._positionY -= this.viewportBorder;
  54166. }
  54167. // Position
  54168. var centerX = globalViewport.x + globalViewport.width / 2;
  54169. var centerY = globalViewport.y + globalViewport.height / 2;
  54170. var distX = centerX - this._positionX;
  54171. var distY = centerY - this._positionY;
  54172. // Effects
  54173. engine.enableEffect(this._effect);
  54174. engine.setState(false);
  54175. engine.setDepthBuffer(false);
  54176. // VBOs
  54177. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54178. // Flares
  54179. for (var index = 0; index < this.lensFlares.length; index++) {
  54180. var flare = this.lensFlares[index];
  54181. engine.setAlphaMode(flare.alphaMode);
  54182. var x = centerX - (distX * flare.position);
  54183. var y = centerY - (distY * flare.position);
  54184. var cw = flare.size;
  54185. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  54186. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  54187. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  54188. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  54189. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  54190. // Texture
  54191. this._effect.setTexture("textureSampler", flare.texture);
  54192. // Color
  54193. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  54194. // Draw order
  54195. engine.draw(true, 0, 6);
  54196. }
  54197. engine.setDepthBuffer(true);
  54198. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54199. return true;
  54200. };
  54201. LensFlareSystem.prototype.dispose = function () {
  54202. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54203. if (vertexBuffer) {
  54204. vertexBuffer.dispose();
  54205. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54206. }
  54207. if (this._indexBuffer) {
  54208. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54209. this._indexBuffer = null;
  54210. }
  54211. while (this.lensFlares.length) {
  54212. this.lensFlares[0].dispose();
  54213. }
  54214. // Remove from scene
  54215. var index = this._scene.lensFlareSystems.indexOf(this);
  54216. this._scene.lensFlareSystems.splice(index, 1);
  54217. };
  54218. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  54219. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  54220. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  54221. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  54222. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  54223. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  54224. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  54225. var parsedFlare = parsedLensFlareSystem.flares[index];
  54226. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  54227. }
  54228. return lensFlareSystem;
  54229. };
  54230. LensFlareSystem.prototype.serialize = function () {
  54231. var serializationObject = {};
  54232. serializationObject.id = this.id;
  54233. serializationObject.name = this.name;
  54234. serializationObject.emitterId = this.getEmitter().id;
  54235. serializationObject.borderLimit = this.borderLimit;
  54236. serializationObject.flares = [];
  54237. for (var index = 0; index < this.lensFlares.length; index++) {
  54238. var flare = this.lensFlares[index];
  54239. serializationObject.flares.push({
  54240. size: flare.size,
  54241. position: flare.position,
  54242. color: flare.color.asArray(),
  54243. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  54244. });
  54245. }
  54246. return serializationObject;
  54247. };
  54248. return LensFlareSystem;
  54249. }());
  54250. BABYLON.LensFlareSystem = LensFlareSystem;
  54251. })(BABYLON || (BABYLON = {}));
  54252. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  54253. var BABYLON;
  54254. (function (BABYLON) {
  54255. /**
  54256. * This is a holder class for the physics joint created by the physics plugin.
  54257. * It holds a set of functions to control the underlying joint.
  54258. */
  54259. var PhysicsJoint = (function () {
  54260. function PhysicsJoint(type, jointData) {
  54261. this.type = type;
  54262. this.jointData = jointData;
  54263. jointData.nativeParams = jointData.nativeParams || {};
  54264. }
  54265. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  54266. get: function () {
  54267. return this._physicsJoint;
  54268. },
  54269. set: function (newJoint) {
  54270. if (this._physicsJoint) {
  54271. //remove from the wolrd
  54272. }
  54273. this._physicsJoint = newJoint;
  54274. },
  54275. enumerable: true,
  54276. configurable: true
  54277. });
  54278. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  54279. set: function (physicsPlugin) {
  54280. this._physicsPlugin = physicsPlugin;
  54281. },
  54282. enumerable: true,
  54283. configurable: true
  54284. });
  54285. /**
  54286. * Execute a function that is physics-plugin specific.
  54287. * @param {Function} func the function that will be executed.
  54288. * It accepts two parameters: the physics world and the physics joint.
  54289. */
  54290. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  54291. func(this._physicsPlugin.world, this._physicsJoint);
  54292. };
  54293. return PhysicsJoint;
  54294. }());
  54295. //TODO check if the native joints are the same
  54296. //Joint Types
  54297. PhysicsJoint.DistanceJoint = 0;
  54298. PhysicsJoint.HingeJoint = 1;
  54299. PhysicsJoint.BallAndSocketJoint = 2;
  54300. PhysicsJoint.WheelJoint = 3;
  54301. PhysicsJoint.SliderJoint = 4;
  54302. //OIMO
  54303. PhysicsJoint.PrismaticJoint = 5;
  54304. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  54305. PhysicsJoint.UniversalJoint = 6;
  54306. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  54307. //Cannon
  54308. //Similar to a Ball-Joint. Different in params
  54309. PhysicsJoint.PointToPointJoint = 8;
  54310. //Cannon only at the moment
  54311. PhysicsJoint.SpringJoint = 9;
  54312. PhysicsJoint.LockJoint = 10;
  54313. BABYLON.PhysicsJoint = PhysicsJoint;
  54314. /**
  54315. * A class representing a physics distance joint.
  54316. */
  54317. var DistanceJoint = (function (_super) {
  54318. __extends(DistanceJoint, _super);
  54319. function DistanceJoint(jointData) {
  54320. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  54321. }
  54322. /**
  54323. * Update the predefined distance.
  54324. */
  54325. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  54326. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  54327. };
  54328. return DistanceJoint;
  54329. }(PhysicsJoint));
  54330. BABYLON.DistanceJoint = DistanceJoint;
  54331. var MotorEnabledJoint = (function (_super) {
  54332. __extends(MotorEnabledJoint, _super);
  54333. function MotorEnabledJoint(type, jointData) {
  54334. return _super.call(this, type, jointData) || this;
  54335. }
  54336. /**
  54337. * Set the motor values.
  54338. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54339. * @param {number} force the force to apply
  54340. * @param {number} maxForce max force for this motor.
  54341. */
  54342. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  54343. this._physicsPlugin.setMotor(this, force, maxForce);
  54344. };
  54345. /**
  54346. * Set the motor's limits.
  54347. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54348. */
  54349. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  54350. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  54351. };
  54352. return MotorEnabledJoint;
  54353. }(PhysicsJoint));
  54354. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  54355. /**
  54356. * This class represents a single hinge physics joint
  54357. */
  54358. var HingeJoint = (function (_super) {
  54359. __extends(HingeJoint, _super);
  54360. function HingeJoint(jointData) {
  54361. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  54362. }
  54363. /**
  54364. * Set the motor values.
  54365. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54366. * @param {number} force the force to apply
  54367. * @param {number} maxForce max force for this motor.
  54368. */
  54369. HingeJoint.prototype.setMotor = function (force, maxForce) {
  54370. this._physicsPlugin.setMotor(this, force, maxForce);
  54371. };
  54372. /**
  54373. * Set the motor's limits.
  54374. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54375. */
  54376. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  54377. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  54378. };
  54379. return HingeJoint;
  54380. }(MotorEnabledJoint));
  54381. BABYLON.HingeJoint = HingeJoint;
  54382. /**
  54383. * This class represents a dual hinge physics joint (same as wheel joint)
  54384. */
  54385. var Hinge2Joint = (function (_super) {
  54386. __extends(Hinge2Joint, _super);
  54387. function Hinge2Joint(jointData) {
  54388. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  54389. }
  54390. /**
  54391. * Set the motor values.
  54392. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54393. * @param {number} force the force to apply
  54394. * @param {number} maxForce max force for this motor.
  54395. * @param {motorIndex} the motor's index, 0 or 1.
  54396. */
  54397. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  54398. if (motorIndex === void 0) { motorIndex = 0; }
  54399. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  54400. };
  54401. /**
  54402. * Set the motor limits.
  54403. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54404. * @param {number} upperLimit the upper limit
  54405. * @param {number} lowerLimit lower limit
  54406. * @param {motorIndex} the motor's index, 0 or 1.
  54407. */
  54408. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  54409. if (motorIndex === void 0) { motorIndex = 0; }
  54410. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  54411. };
  54412. return Hinge2Joint;
  54413. }(MotorEnabledJoint));
  54414. BABYLON.Hinge2Joint = Hinge2Joint;
  54415. })(BABYLON || (BABYLON = {}));
  54416. //# sourceMappingURL=babylon.physicsJoint.js.map
  54417. var BABYLON;
  54418. (function (BABYLON) {
  54419. var PhysicsImpostor = (function () {
  54420. function PhysicsImpostor(object, type, _options, _scene) {
  54421. if (_options === void 0) { _options = { mass: 0 }; }
  54422. var _this = this;
  54423. this.object = object;
  54424. this.type = type;
  54425. this._options = _options;
  54426. this._scene = _scene;
  54427. this._bodyUpdateRequired = false;
  54428. this._onBeforePhysicsStepCallbacks = new Array();
  54429. this._onAfterPhysicsStepCallbacks = new Array();
  54430. this._onPhysicsCollideCallbacks = [];
  54431. this._deltaPosition = BABYLON.Vector3.Zero();
  54432. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  54433. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  54434. /**
  54435. * this function is executed by the physics engine.
  54436. */
  54437. this.beforeStep = function () {
  54438. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  54439. //conjugate deltaRotation
  54440. if (_this._deltaRotationConjugated) {
  54441. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  54442. }
  54443. else {
  54444. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  54445. }
  54446. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  54447. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  54448. func(_this);
  54449. });
  54450. };
  54451. /**
  54452. * this function is executed by the physics engine.
  54453. */
  54454. this.afterStep = function () {
  54455. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  54456. func(_this);
  54457. });
  54458. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  54459. _this.object.position.addInPlace(_this._deltaPosition);
  54460. if (_this._deltaRotation) {
  54461. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  54462. }
  54463. };
  54464. /**
  54465. * Legacy collision detection event support
  54466. */
  54467. this.onCollideEvent = null;
  54468. //event and body object due to cannon's event-based architecture.
  54469. this.onCollide = function (e) {
  54470. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  54471. return;
  54472. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  54473. if (otherImpostor) {
  54474. // Legacy collision detection event support
  54475. if (_this.onCollideEvent) {
  54476. _this.onCollideEvent(_this, otherImpostor);
  54477. }
  54478. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  54479. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  54480. }).forEach(function (obj) {
  54481. obj.callback(_this, otherImpostor);
  54482. });
  54483. }
  54484. };
  54485. //sanity check!
  54486. if (!this.object) {
  54487. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  54488. return;
  54489. }
  54490. //legacy support for old syntax.
  54491. if (!this._scene && object.getScene) {
  54492. this._scene = object.getScene();
  54493. }
  54494. this._physicsEngine = this._scene.getPhysicsEngine();
  54495. if (!this._physicsEngine) {
  54496. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  54497. }
  54498. else {
  54499. //set the object's quaternion, if not set
  54500. if (!this.object.rotationQuaternion) {
  54501. if (this.object.rotation) {
  54502. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  54503. }
  54504. else {
  54505. this.object.rotationQuaternion = new BABYLON.Quaternion();
  54506. }
  54507. }
  54508. //default options params
  54509. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  54510. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  54511. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  54512. this._joints = [];
  54513. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  54514. if (!this.object.parent) {
  54515. this._init();
  54516. }
  54517. }
  54518. }
  54519. /**
  54520. * This function will completly initialize this impostor.
  54521. * It will create a new body - but only if this mesh has no parent.
  54522. * If it has, this impostor will not be used other than to define the impostor
  54523. * of the child mesh.
  54524. */
  54525. PhysicsImpostor.prototype._init = function () {
  54526. this._physicsEngine.removeImpostor(this);
  54527. this.physicsBody = null;
  54528. this._parent = this._parent || this._getPhysicsParent();
  54529. if (!this.parent) {
  54530. this._physicsEngine.addImpostor(this);
  54531. }
  54532. };
  54533. PhysicsImpostor.prototype._getPhysicsParent = function () {
  54534. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  54535. var parentMesh = this.object.parent;
  54536. return parentMesh.physicsImpostor;
  54537. }
  54538. return;
  54539. };
  54540. /**
  54541. * Should a new body be generated.
  54542. */
  54543. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  54544. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  54545. };
  54546. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  54547. this.forceUpdate();
  54548. };
  54549. /**
  54550. * Force a regeneration of this or the parent's impostor's body.
  54551. * Use under cautious - This will remove all joints already implemented.
  54552. */
  54553. PhysicsImpostor.prototype.forceUpdate = function () {
  54554. this._init();
  54555. if (this.parent) {
  54556. this.parent.forceUpdate();
  54557. }
  54558. };
  54559. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  54560. /*public get mesh(): AbstractMesh {
  54561. return this._mesh;
  54562. }*/
  54563. /**
  54564. * Gets the body that holds this impostor. Either its own, or its parent.
  54565. */
  54566. get: function () {
  54567. return this._parent ? this._parent.physicsBody : this._physicsBody;
  54568. },
  54569. /**
  54570. * Set the physics body. Used mainly by the physics engine/plugin
  54571. */
  54572. set: function (physicsBody) {
  54573. if (this._physicsBody) {
  54574. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  54575. }
  54576. this._physicsBody = physicsBody;
  54577. this.resetUpdateFlags();
  54578. },
  54579. enumerable: true,
  54580. configurable: true
  54581. });
  54582. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  54583. get: function () {
  54584. return this._parent;
  54585. },
  54586. set: function (value) {
  54587. this._parent = value;
  54588. },
  54589. enumerable: true,
  54590. configurable: true
  54591. });
  54592. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  54593. this._bodyUpdateRequired = false;
  54594. };
  54595. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  54596. if (this.object.getBoundingInfo) {
  54597. var q = this.object.rotationQuaternion;
  54598. //reset rotation
  54599. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  54600. //calculate the world matrix with no rotation
  54601. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  54602. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  54603. //bring back the rotation
  54604. this.object.rotationQuaternion = q;
  54605. //calculate the world matrix with the new rotation
  54606. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  54607. return size;
  54608. }
  54609. else {
  54610. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  54611. }
  54612. };
  54613. PhysicsImpostor.prototype.getObjectCenter = function () {
  54614. if (this.object.getBoundingInfo) {
  54615. return this.object.getBoundingInfo().boundingBox.centerWorld;
  54616. }
  54617. else {
  54618. return this.object.position;
  54619. }
  54620. };
  54621. /**
  54622. * Get a specific parametes from the options parameter.
  54623. */
  54624. PhysicsImpostor.prototype.getParam = function (paramName) {
  54625. return this._options[paramName];
  54626. };
  54627. /**
  54628. * Sets a specific parameter in the options given to the physics plugin
  54629. */
  54630. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  54631. this._options[paramName] = value;
  54632. this._bodyUpdateRequired = true;
  54633. };
  54634. /**
  54635. * Specifically change the body's mass option. Won't recreate the physics body object
  54636. */
  54637. PhysicsImpostor.prototype.setMass = function (mass) {
  54638. if (this.getParam("mass") !== mass) {
  54639. this.setParam("mass", mass);
  54640. }
  54641. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  54642. };
  54643. PhysicsImpostor.prototype.getLinearVelocity = function () {
  54644. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  54645. };
  54646. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  54647. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  54648. };
  54649. PhysicsImpostor.prototype.getAngularVelocity = function () {
  54650. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  54651. };
  54652. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  54653. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  54654. };
  54655. /**
  54656. * Execute a function with the physics plugin native code.
  54657. * Provide a function the will have two variables - the world object and the physics body object.
  54658. */
  54659. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  54660. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  54661. };
  54662. /**
  54663. * Register a function that will be executed before the physics world is stepping forward.
  54664. */
  54665. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  54666. this._onBeforePhysicsStepCallbacks.push(func);
  54667. };
  54668. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  54669. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  54670. if (index > -1) {
  54671. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  54672. }
  54673. else {
  54674. BABYLON.Tools.Warn("Function to remove was not found");
  54675. }
  54676. };
  54677. /**
  54678. * Register a function that will be executed after the physics step
  54679. */
  54680. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  54681. this._onAfterPhysicsStepCallbacks.push(func);
  54682. };
  54683. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  54684. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  54685. if (index > -1) {
  54686. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  54687. }
  54688. else {
  54689. BABYLON.Tools.Warn("Function to remove was not found");
  54690. }
  54691. };
  54692. /**
  54693. * register a function that will be executed when this impostor collides against a different body.
  54694. */
  54695. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  54696. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  54697. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  54698. };
  54699. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  54700. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  54701. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  54702. if (index > -1) {
  54703. this._onPhysicsCollideCallbacks.splice(index, 1);
  54704. }
  54705. else {
  54706. BABYLON.Tools.Warn("Function to remove was not found");
  54707. }
  54708. };
  54709. /**
  54710. * Apply a force
  54711. */
  54712. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  54713. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  54714. };
  54715. /**
  54716. * Apply an impulse
  54717. */
  54718. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  54719. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  54720. };
  54721. /**
  54722. * A help function to create a joint.
  54723. */
  54724. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  54725. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  54726. this.addJoint(otherImpostor, joint);
  54727. };
  54728. /**
  54729. * Add a joint to this impostor with a different impostor.
  54730. */
  54731. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  54732. this._joints.push({
  54733. otherImpostor: otherImpostor,
  54734. joint: joint
  54735. });
  54736. this._physicsEngine.addJoint(this, otherImpostor, joint);
  54737. };
  54738. /**
  54739. * Will keep this body still, in a sleep mode.
  54740. */
  54741. PhysicsImpostor.prototype.sleep = function () {
  54742. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  54743. };
  54744. /**
  54745. * Wake the body up.
  54746. */
  54747. PhysicsImpostor.prototype.wakeUp = function () {
  54748. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  54749. };
  54750. PhysicsImpostor.prototype.clone = function (newObject) {
  54751. if (!newObject)
  54752. return null;
  54753. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  54754. };
  54755. PhysicsImpostor.prototype.dispose = function () {
  54756. var _this = this;
  54757. //no dispose if no physics engine is available.
  54758. if (!this._physicsEngine) {
  54759. return;
  54760. }
  54761. this._joints.forEach(function (j) {
  54762. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  54763. });
  54764. //dispose the physics body
  54765. this._physicsEngine.removeImpostor(this);
  54766. if (this.parent) {
  54767. this.parent.forceUpdate();
  54768. }
  54769. else {
  54770. /*this._object.getChildMeshes().forEach(function(mesh) {
  54771. if (mesh.physicsImpostor) {
  54772. if (disposeChildren) {
  54773. mesh.physicsImpostor.dispose();
  54774. mesh.physicsImpostor = null;
  54775. }
  54776. }
  54777. })*/
  54778. }
  54779. };
  54780. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  54781. this._deltaPosition.copyFrom(position);
  54782. };
  54783. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  54784. if (!this._deltaRotation) {
  54785. this._deltaRotation = new BABYLON.Quaternion();
  54786. }
  54787. this._deltaRotation.copyFrom(rotation);
  54788. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  54789. };
  54790. return PhysicsImpostor;
  54791. }());
  54792. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  54793. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  54794. //Impostor types
  54795. PhysicsImpostor.NoImpostor = 0;
  54796. PhysicsImpostor.SphereImpostor = 1;
  54797. PhysicsImpostor.BoxImpostor = 2;
  54798. PhysicsImpostor.PlaneImpostor = 3;
  54799. PhysicsImpostor.MeshImpostor = 4;
  54800. PhysicsImpostor.CylinderImpostor = 7;
  54801. PhysicsImpostor.ParticleImpostor = 8;
  54802. PhysicsImpostor.HeightmapImpostor = 9;
  54803. BABYLON.PhysicsImpostor = PhysicsImpostor;
  54804. })(BABYLON || (BABYLON = {}));
  54805. //# sourceMappingURL=babylon.physicsImpostor.js.map
  54806. var BABYLON;
  54807. (function (BABYLON) {
  54808. var PhysicsEngine = (function () {
  54809. function PhysicsEngine(gravity, _physicsPlugin) {
  54810. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  54811. this._physicsPlugin = _physicsPlugin;
  54812. //new methods and parameters
  54813. this._impostors = [];
  54814. this._joints = [];
  54815. if (!this._physicsPlugin.isSupported()) {
  54816. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  54817. + "Please make sure it is included.");
  54818. }
  54819. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  54820. this.setGravity(gravity);
  54821. this.setTimeStep();
  54822. }
  54823. PhysicsEngine.prototype.setGravity = function (gravity) {
  54824. this.gravity = gravity;
  54825. this._physicsPlugin.setGravity(this.gravity);
  54826. };
  54827. /**
  54828. * Set the time step of the physics engine.
  54829. * default is 1/60.
  54830. * To slow it down, enter 1/600 for example.
  54831. * To speed it up, 1/30
  54832. * @param {number} newTimeStep the new timestep to apply to this world.
  54833. */
  54834. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  54835. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  54836. this._physicsPlugin.setTimeStep(newTimeStep);
  54837. };
  54838. PhysicsEngine.prototype.dispose = function () {
  54839. this._impostors.forEach(function (impostor) {
  54840. impostor.dispose();
  54841. });
  54842. this._physicsPlugin.dispose();
  54843. };
  54844. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  54845. return this._physicsPlugin.name;
  54846. };
  54847. /**
  54848. * Adding a new impostor for the impostor tracking.
  54849. * This will be done by the impostor itself.
  54850. * @param {PhysicsImpostor} impostor the impostor to add
  54851. */
  54852. PhysicsEngine.prototype.addImpostor = function (impostor) {
  54853. impostor.uniqueId = this._impostors.push(impostor);
  54854. //if no parent, generate the body
  54855. if (!impostor.parent) {
  54856. this._physicsPlugin.generatePhysicsBody(impostor);
  54857. }
  54858. };
  54859. /**
  54860. * Remove an impostor from the engine.
  54861. * This impostor and its mesh will not longer be updated by the physics engine.
  54862. * @param {PhysicsImpostor} impostor the impostor to remove
  54863. */
  54864. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  54865. var index = this._impostors.indexOf(impostor);
  54866. if (index > -1) {
  54867. var removed = this._impostors.splice(index, 1);
  54868. //Is it needed?
  54869. if (removed.length) {
  54870. //this will also remove it from the world.
  54871. removed[0].physicsBody = null;
  54872. }
  54873. }
  54874. };
  54875. /**
  54876. * Add a joint to the physics engine
  54877. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  54878. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  54879. * @param {PhysicsJoint} the joint that will connect both impostors.
  54880. */
  54881. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  54882. var impostorJoint = {
  54883. mainImpostor: mainImpostor,
  54884. connectedImpostor: connectedImpostor,
  54885. joint: joint
  54886. };
  54887. joint.physicsPlugin = this._physicsPlugin;
  54888. this._joints.push(impostorJoint);
  54889. this._physicsPlugin.generateJoint(impostorJoint);
  54890. };
  54891. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  54892. var matchingJoints = this._joints.filter(function (impostorJoint) {
  54893. return (impostorJoint.connectedImpostor === connectedImpostor
  54894. && impostorJoint.joint === joint
  54895. && impostorJoint.mainImpostor === mainImpostor);
  54896. });
  54897. if (matchingJoints.length) {
  54898. this._physicsPlugin.removeJoint(matchingJoints[0]);
  54899. //TODO remove it from the list as well
  54900. }
  54901. };
  54902. /**
  54903. * Called by the scene. no need to call it.
  54904. */
  54905. PhysicsEngine.prototype._step = function (delta) {
  54906. var _this = this;
  54907. //check if any mesh has no body / requires an update
  54908. this._impostors.forEach(function (impostor) {
  54909. if (impostor.isBodyInitRequired()) {
  54910. _this._physicsPlugin.generatePhysicsBody(impostor);
  54911. }
  54912. });
  54913. if (delta > 0.1) {
  54914. delta = 0.1;
  54915. }
  54916. else if (delta <= 0) {
  54917. delta = 1.0 / 60.0;
  54918. }
  54919. this._physicsPlugin.executeStep(delta, this._impostors);
  54920. };
  54921. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  54922. return this._physicsPlugin;
  54923. };
  54924. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  54925. for (var i = 0; i < this._impostors.length; ++i) {
  54926. if (this._impostors[i].object === object) {
  54927. return this._impostors[i];
  54928. }
  54929. }
  54930. };
  54931. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  54932. for (var i = 0; i < this._impostors.length; ++i) {
  54933. if (this._impostors[i].physicsBody === body) {
  54934. return this._impostors[i];
  54935. }
  54936. }
  54937. };
  54938. return PhysicsEngine;
  54939. }());
  54940. // Statics
  54941. PhysicsEngine.Epsilon = 0.001;
  54942. BABYLON.PhysicsEngine = PhysicsEngine;
  54943. })(BABYLON || (BABYLON = {}));
  54944. //# sourceMappingURL=babylon.physicsEngine.js.map
  54945. var BABYLON;
  54946. (function (BABYLON) {
  54947. var CannonJSPlugin = (function () {
  54948. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  54949. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  54950. if (iterations === void 0) { iterations = 10; }
  54951. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  54952. this.name = "CannonJSPlugin";
  54953. this._physicsMaterials = [];
  54954. this._fixedTimeStep = 1 / 60;
  54955. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  54956. this._currentCollisionGroup = 2;
  54957. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  54958. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  54959. this._tmpPosition = BABYLON.Vector3.Zero();
  54960. this._tmpQuaternion = new BABYLON.Quaternion();
  54961. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  54962. this._tmpDeltaRotation = new BABYLON.Quaternion();
  54963. this._tmpUnityRotation = new BABYLON.Quaternion();
  54964. if (!this.isSupported()) {
  54965. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  54966. return;
  54967. }
  54968. this.world = new CANNON.World();
  54969. this.world.broadphase = new CANNON.NaiveBroadphase();
  54970. this.world.solver.iterations = iterations;
  54971. }
  54972. CannonJSPlugin.prototype.setGravity = function (gravity) {
  54973. this.world.gravity.copy(gravity);
  54974. };
  54975. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  54976. this._fixedTimeStep = timeStep;
  54977. };
  54978. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  54979. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  54980. };
  54981. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  54982. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  54983. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  54984. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  54985. };
  54986. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  54987. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  54988. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  54989. impostor.physicsBody.applyForce(impulse, worldPoint);
  54990. };
  54991. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  54992. //parent-child relationship. Does this impostor has a parent impostor?
  54993. if (impostor.parent) {
  54994. if (impostor.physicsBody) {
  54995. this.removePhysicsBody(impostor);
  54996. //TODO is that needed?
  54997. impostor.forceUpdate();
  54998. }
  54999. return;
  55000. }
  55001. //should a new body be created for this impostor?
  55002. if (impostor.isBodyInitRequired()) {
  55003. var shape = this._createShape(impostor);
  55004. //unregister events, if body is being changed
  55005. var oldBody = impostor.physicsBody;
  55006. if (oldBody) {
  55007. this.removePhysicsBody(impostor);
  55008. }
  55009. //create the body and material
  55010. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  55011. var bodyCreationObject = {
  55012. mass: impostor.getParam("mass"),
  55013. material: material
  55014. };
  55015. // A simple extend, in case native options were used.
  55016. var nativeOptions = impostor.getParam("nativeOptions");
  55017. for (var key in nativeOptions) {
  55018. if (nativeOptions.hasOwnProperty(key)) {
  55019. bodyCreationObject[key] = nativeOptions[key];
  55020. }
  55021. }
  55022. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  55023. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  55024. this.world.addEventListener("preStep", impostor.beforeStep);
  55025. this.world.addEventListener("postStep", impostor.afterStep);
  55026. impostor.physicsBody.addShape(shape);
  55027. this.world.add(impostor.physicsBody);
  55028. //try to keep the body moving in the right direction by taking old properties.
  55029. //Should be tested!
  55030. if (oldBody) {
  55031. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  55032. impostor.physicsBody[param].copy(oldBody[param]);
  55033. });
  55034. }
  55035. this._processChildMeshes(impostor);
  55036. }
  55037. //now update the body's transformation
  55038. this._updatePhysicsBodyTransformation(impostor);
  55039. };
  55040. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  55041. var _this = this;
  55042. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  55043. if (meshChildren.length) {
  55044. var processMesh = function (localPosition, mesh) {
  55045. var childImpostor = mesh.getPhysicsImpostor();
  55046. if (childImpostor) {
  55047. var parent = childImpostor.parent;
  55048. if (parent !== mainImpostor) {
  55049. var localPosition = mesh.position;
  55050. if (childImpostor.physicsBody) {
  55051. _this.removePhysicsBody(childImpostor);
  55052. childImpostor.physicsBody = null;
  55053. }
  55054. childImpostor.parent = mainImpostor;
  55055. childImpostor.resetUpdateFlags();
  55056. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  55057. //Add the mass of the children.
  55058. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  55059. }
  55060. }
  55061. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  55062. };
  55063. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  55064. }
  55065. };
  55066. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  55067. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  55068. this.world.removeEventListener("preStep", impostor.beforeStep);
  55069. this.world.removeEventListener("postStep", impostor.afterStep);
  55070. this.world.remove(impostor.physicsBody);
  55071. };
  55072. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  55073. var mainBody = impostorJoint.mainImpostor.physicsBody;
  55074. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  55075. if (!mainBody || !connectedBody) {
  55076. return;
  55077. }
  55078. var constraint;
  55079. var jointData = impostorJoint.joint.jointData;
  55080. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  55081. var constraintData = {
  55082. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  55083. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  55084. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  55085. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  55086. maxForce: jointData.nativeParams.maxForce,
  55087. collideConnected: !!jointData.collision
  55088. };
  55089. switch (impostorJoint.joint.type) {
  55090. case BABYLON.PhysicsJoint.HingeJoint:
  55091. case BABYLON.PhysicsJoint.Hinge2Joint:
  55092. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  55093. break;
  55094. case BABYLON.PhysicsJoint.DistanceJoint:
  55095. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  55096. break;
  55097. case BABYLON.PhysicsJoint.SpringJoint:
  55098. var springData = jointData;
  55099. constraint = new CANNON.Spring(mainBody, connectedBody, {
  55100. restLength: springData.length,
  55101. stiffness: springData.stiffness,
  55102. damping: springData.damping,
  55103. localAnchorA: constraintData.pivotA,
  55104. localAnchorB: constraintData.pivotB
  55105. });
  55106. break;
  55107. case BABYLON.PhysicsJoint.LockJoint:
  55108. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  55109. break;
  55110. case BABYLON.PhysicsJoint.PointToPointJoint:
  55111. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  55112. default:
  55113. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  55114. break;
  55115. }
  55116. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  55117. constraint.collideConnected = !!jointData.collision;
  55118. impostorJoint.joint.physicsJoint = constraint;
  55119. //don't add spring as constraint, as it is not one.
  55120. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  55121. this.world.addConstraint(constraint);
  55122. }
  55123. else {
  55124. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  55125. constraint.applyForce();
  55126. });
  55127. }
  55128. };
  55129. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  55130. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  55131. };
  55132. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  55133. var index;
  55134. var mat;
  55135. for (index = 0; index < this._physicsMaterials.length; index++) {
  55136. mat = this._physicsMaterials[index];
  55137. if (mat.friction === friction && mat.restitution === restitution) {
  55138. return mat;
  55139. }
  55140. }
  55141. var currentMat = new CANNON.Material(name);
  55142. currentMat.friction = friction;
  55143. currentMat.restitution = restitution;
  55144. this._physicsMaterials.push(currentMat);
  55145. return currentMat;
  55146. };
  55147. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  55148. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  55149. };
  55150. CannonJSPlugin.prototype._createShape = function (impostor) {
  55151. var object = impostor.object;
  55152. var returnValue;
  55153. var extendSize = impostor.getObjectExtendSize();
  55154. switch (impostor.type) {
  55155. case BABYLON.PhysicsImpostor.SphereImpostor:
  55156. var radiusX = extendSize.x;
  55157. var radiusY = extendSize.y;
  55158. var radiusZ = extendSize.z;
  55159. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  55160. break;
  55161. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  55162. case BABYLON.PhysicsImpostor.CylinderImpostor:
  55163. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  55164. break;
  55165. case BABYLON.PhysicsImpostor.BoxImpostor:
  55166. var box = extendSize.scale(0.5);
  55167. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  55168. break;
  55169. case BABYLON.PhysicsImpostor.PlaneImpostor:
  55170. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  55171. returnValue = new CANNON.Plane();
  55172. break;
  55173. case BABYLON.PhysicsImpostor.MeshImpostor:
  55174. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  55175. var rawFaces = object.getIndices ? object.getIndices() : [];
  55176. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  55177. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  55178. break;
  55179. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  55180. returnValue = this._createHeightmap(object);
  55181. break;
  55182. case BABYLON.PhysicsImpostor.ParticleImpostor:
  55183. returnValue = new CANNON.Particle();
  55184. break;
  55185. }
  55186. return returnValue;
  55187. };
  55188. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  55189. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55190. var matrix = [];
  55191. //For now pointDepth will not be used and will be automatically calculated.
  55192. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  55193. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  55194. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  55195. var elementSize = dim * 2 / arraySize;
  55196. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  55197. for (var i = 0; i < pos.length; i = i + 3) {
  55198. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  55199. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  55200. var y = pos[i + 1] + minY;
  55201. if (!matrix[x]) {
  55202. matrix[x] = [];
  55203. }
  55204. if (!matrix[x][z]) {
  55205. matrix[x][z] = y;
  55206. }
  55207. matrix[x][z] = Math.max(y, matrix[x][z]);
  55208. }
  55209. for (var x = 0; x <= arraySize; ++x) {
  55210. if (!matrix[x]) {
  55211. var loc = 1;
  55212. while (!matrix[(x + loc) % arraySize]) {
  55213. loc++;
  55214. }
  55215. matrix[x] = matrix[(x + loc) % arraySize].slice();
  55216. //console.log("missing x", x);
  55217. }
  55218. for (var z = 0; z <= arraySize; ++z) {
  55219. if (!matrix[x][z]) {
  55220. var loc = 1;
  55221. var newValue;
  55222. while (newValue === undefined) {
  55223. newValue = matrix[x][(z + loc++) % arraySize];
  55224. }
  55225. matrix[x][z] = newValue;
  55226. }
  55227. }
  55228. }
  55229. var shape = new CANNON.Heightfield(matrix, {
  55230. elementSize: elementSize
  55231. });
  55232. //For future reference, needed for body transformation
  55233. shape.minY = minY;
  55234. return shape;
  55235. };
  55236. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  55237. var object = impostor.object;
  55238. //make sure it is updated...
  55239. object.computeWorldMatrix && object.computeWorldMatrix(true);
  55240. // The delta between the mesh position and the mesh bounding box center
  55241. var center = impostor.getObjectCenter();
  55242. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  55243. this._tmpPosition.copyFrom(center);
  55244. var quaternion = object.rotationQuaternion;
  55245. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  55246. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  55247. //-90 DEG in X, precalculated
  55248. quaternion = quaternion.multiply(this._minus90X);
  55249. //Invert! (Precalculated, 90 deg in X)
  55250. //No need to clone. this will never change.
  55251. impostor.setDeltaRotation(this._plus90X);
  55252. }
  55253. //If it is a heightfield, if should be centered.
  55254. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  55255. var mesh = object;
  55256. //calculate the correct body position:
  55257. var rotationQuaternion = mesh.rotationQuaternion;
  55258. mesh.rotationQuaternion = this._tmpUnityRotation;
  55259. mesh.computeWorldMatrix(true);
  55260. //get original center with no rotation
  55261. var c = center.clone();
  55262. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  55263. //rotation is back
  55264. mesh.rotationQuaternion = rotationQuaternion;
  55265. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  55266. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  55267. mesh.setPivotMatrix(p);
  55268. mesh.computeWorldMatrix(true);
  55269. //calculate the translation
  55270. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  55271. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  55272. //add it inverted to the delta
  55273. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  55274. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  55275. mesh.setPivotMatrix(oldPivot);
  55276. mesh.computeWorldMatrix(true);
  55277. }
  55278. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  55279. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  55280. this._tmpPosition.copyFrom(object.position);
  55281. }
  55282. impostor.setDeltaPosition(this._tmpDeltaPosition);
  55283. //Now update the impostor object
  55284. impostor.physicsBody.position.copy(this._tmpPosition);
  55285. impostor.physicsBody.quaternion.copy(quaternion);
  55286. };
  55287. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  55288. impostor.object.position.copyFrom(impostor.physicsBody.position);
  55289. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  55290. };
  55291. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  55292. impostor.physicsBody.position.copy(newPosition);
  55293. impostor.physicsBody.quaternion.copy(newRotation);
  55294. };
  55295. CannonJSPlugin.prototype.isSupported = function () {
  55296. return window.CANNON !== undefined;
  55297. };
  55298. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  55299. impostor.physicsBody.velocity.copy(velocity);
  55300. };
  55301. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  55302. impostor.physicsBody.angularVelocity.copy(velocity);
  55303. };
  55304. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  55305. var v = impostor.physicsBody.velocity;
  55306. if (!v)
  55307. return null;
  55308. return new BABYLON.Vector3(v.x, v.y, v.z);
  55309. };
  55310. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  55311. var v = impostor.physicsBody.angularVelocity;
  55312. if (!v)
  55313. return null;
  55314. return new BABYLON.Vector3(v.x, v.y, v.z);
  55315. };
  55316. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  55317. impostor.physicsBody.mass = mass;
  55318. impostor.physicsBody.updateMassProperties();
  55319. };
  55320. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  55321. impostor.physicsBody.sleep();
  55322. };
  55323. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  55324. impostor.physicsBody.wakeUp();
  55325. };
  55326. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  55327. joint.physicsJoint.distance = maxDistance;
  55328. };
  55329. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  55330. if (!motorIndex) {
  55331. joint.physicsJoint.enableMotor();
  55332. }
  55333. };
  55334. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  55335. if (!motorIndex) {
  55336. joint.physicsJoint.disableMotor();
  55337. }
  55338. };
  55339. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  55340. if (!motorIndex) {
  55341. joint.physicsJoint.enableMotor();
  55342. joint.physicsJoint.setMotorSpeed(speed);
  55343. if (maxForce) {
  55344. this.setLimit(joint, maxForce);
  55345. }
  55346. }
  55347. };
  55348. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  55349. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  55350. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  55351. };
  55352. CannonJSPlugin.prototype.dispose = function () {
  55353. //nothing to do, actually.
  55354. };
  55355. return CannonJSPlugin;
  55356. }());
  55357. BABYLON.CannonJSPlugin = CannonJSPlugin;
  55358. })(BABYLON || (BABYLON = {}));
  55359. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  55360. var BABYLON;
  55361. (function (BABYLON) {
  55362. var OimoJSPlugin = (function () {
  55363. function OimoJSPlugin(iterations) {
  55364. this.name = "OimoJSPlugin";
  55365. this._tmpImpostorsArray = [];
  55366. this._tmpPositionVector = BABYLON.Vector3.Zero();
  55367. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  55368. this.world.worldscale(1);
  55369. this.world.clear();
  55370. //making sure no stats are calculated
  55371. this.world.isNoStat = true;
  55372. }
  55373. OimoJSPlugin.prototype.setGravity = function (gravity) {
  55374. this.world.gravity.copy(gravity);
  55375. };
  55376. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  55377. this.world.timeStep = timeStep;
  55378. };
  55379. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  55380. var _this = this;
  55381. impostors.forEach(function (impostor) {
  55382. impostor.beforeStep();
  55383. });
  55384. this.world.step();
  55385. impostors.forEach(function (impostor) {
  55386. impostor.afterStep();
  55387. //update the ordered impostors array
  55388. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  55389. });
  55390. //check for collisions
  55391. var contact = this.world.contacts;
  55392. while (contact !== null) {
  55393. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  55394. contact = contact.next;
  55395. continue;
  55396. }
  55397. //is this body colliding with any other? get the impostor
  55398. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  55399. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  55400. if (!mainImpostor || !collidingImpostor) {
  55401. contact = contact.next;
  55402. continue;
  55403. }
  55404. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  55405. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  55406. contact = contact.next;
  55407. }
  55408. };
  55409. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  55410. var mass = impostor.physicsBody.massInfo.mass;
  55411. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  55412. };
  55413. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  55414. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  55415. this.applyImpulse(impostor, force, contactPoint);
  55416. };
  55417. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  55418. var _this = this;
  55419. //parent-child relationship. Does this impostor has a parent impostor?
  55420. if (impostor.parent) {
  55421. if (impostor.physicsBody) {
  55422. this.removePhysicsBody(impostor);
  55423. //TODO is that needed?
  55424. impostor.forceUpdate();
  55425. }
  55426. return;
  55427. }
  55428. if (impostor.isBodyInitRequired()) {
  55429. var bodyConfig = {
  55430. name: impostor.uniqueId,
  55431. //Oimo must have mass, also for static objects.
  55432. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  55433. size: [],
  55434. type: [],
  55435. pos: [],
  55436. rot: [],
  55437. move: impostor.getParam("mass") !== 0,
  55438. //Supporting older versions of Oimo
  55439. world: this.world
  55440. };
  55441. var impostors = [impostor];
  55442. var addToArray = function (parent) {
  55443. if (!parent.getChildMeshes)
  55444. return;
  55445. parent.getChildMeshes().forEach(function (m) {
  55446. if (m.physicsImpostor) {
  55447. impostors.push(m.physicsImpostor);
  55448. m.physicsImpostor._init();
  55449. }
  55450. });
  55451. };
  55452. addToArray(impostor.object);
  55453. var checkWithEpsilon_1 = function (value) {
  55454. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  55455. };
  55456. impostors.forEach(function (i) {
  55457. //get the correct bounding box
  55458. var oldQuaternion = i.object.rotationQuaternion;
  55459. var rot = new OIMO.Euler().setFromQuaternion({
  55460. x: impostor.object.rotationQuaternion.x,
  55461. y: impostor.object.rotationQuaternion.y,
  55462. z: impostor.object.rotationQuaternion.z,
  55463. s: impostor.object.rotationQuaternion.w
  55464. });
  55465. var extendSize = i.getObjectExtendSize();
  55466. if (i === impostor) {
  55467. var center = impostor.getObjectCenter();
  55468. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  55469. //Can also use Array.prototype.push.apply
  55470. bodyConfig.pos.push(center.x);
  55471. bodyConfig.pos.push(center.y);
  55472. bodyConfig.pos.push(center.z);
  55473. //tmp solution
  55474. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  55475. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  55476. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  55477. }
  55478. else {
  55479. bodyConfig.pos.push(i.object.position.x);
  55480. bodyConfig.pos.push(i.object.position.y);
  55481. bodyConfig.pos.push(i.object.position.z);
  55482. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  55483. bodyConfig.rot.push(0);
  55484. bodyConfig.rot.push(0);
  55485. bodyConfig.rot.push(0);
  55486. }
  55487. // register mesh
  55488. switch (i.type) {
  55489. case BABYLON.PhysicsImpostor.ParticleImpostor:
  55490. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  55491. case BABYLON.PhysicsImpostor.SphereImpostor:
  55492. var radiusX = extendSize.x;
  55493. var radiusY = extendSize.y;
  55494. var radiusZ = extendSize.z;
  55495. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  55496. bodyConfig.type.push('sphere');
  55497. //due to the way oimo works with compounds, add 3 times
  55498. bodyConfig.size.push(size);
  55499. bodyConfig.size.push(size);
  55500. bodyConfig.size.push(size);
  55501. break;
  55502. case BABYLON.PhysicsImpostor.CylinderImpostor:
  55503. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  55504. var sizeY = checkWithEpsilon_1(extendSize.y);
  55505. bodyConfig.type.push('cylinder');
  55506. bodyConfig.size.push(sizeX);
  55507. bodyConfig.size.push(sizeY);
  55508. //due to the way oimo works with compounds, add one more value.
  55509. bodyConfig.size.push(sizeY);
  55510. break;
  55511. case BABYLON.PhysicsImpostor.PlaneImpostor:
  55512. case BABYLON.PhysicsImpostor.BoxImpostor:
  55513. default:
  55514. var sizeX = checkWithEpsilon_1(extendSize.x);
  55515. var sizeY = checkWithEpsilon_1(extendSize.y);
  55516. var sizeZ = checkWithEpsilon_1(extendSize.z);
  55517. bodyConfig.type.push('box');
  55518. bodyConfig.size.push(sizeX);
  55519. bodyConfig.size.push(sizeY);
  55520. bodyConfig.size.push(sizeZ);
  55521. break;
  55522. }
  55523. //actually not needed, but hey...
  55524. i.object.rotationQuaternion = oldQuaternion;
  55525. });
  55526. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  55527. }
  55528. else {
  55529. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  55530. }
  55531. impostor.setDeltaPosition(this._tmpPositionVector);
  55532. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  55533. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  55534. };
  55535. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  55536. //impostor.physicsBody.dispose();
  55537. //Same as : (older oimo versions)
  55538. this.world.removeRigidBody(impostor.physicsBody);
  55539. };
  55540. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  55541. var mainBody = impostorJoint.mainImpostor.physicsBody;
  55542. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  55543. if (!mainBody || !connectedBody) {
  55544. return;
  55545. }
  55546. var jointData = impostorJoint.joint.jointData;
  55547. var options = jointData.nativeParams || {};
  55548. var type;
  55549. var nativeJointData = {
  55550. body1: mainBody,
  55551. body2: connectedBody,
  55552. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  55553. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  55554. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  55555. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  55556. min: options.min,
  55557. max: options.max,
  55558. collision: options.collision || jointData.collision,
  55559. spring: options.spring,
  55560. //supporting older version of Oimo
  55561. world: this.world
  55562. };
  55563. switch (impostorJoint.joint.type) {
  55564. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  55565. type = "jointBall";
  55566. break;
  55567. case BABYLON.PhysicsJoint.SpringJoint:
  55568. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  55569. var springData = jointData;
  55570. nativeJointData.min = springData.length || nativeJointData.min;
  55571. //Max should also be set, just make sure it is at least min
  55572. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  55573. case BABYLON.PhysicsJoint.DistanceJoint:
  55574. type = "jointDistance";
  55575. nativeJointData.max = jointData.maxDistance;
  55576. break;
  55577. case BABYLON.PhysicsJoint.PrismaticJoint:
  55578. type = "jointPrisme";
  55579. break;
  55580. case BABYLON.PhysicsJoint.SliderJoint:
  55581. type = "jointSlide";
  55582. break;
  55583. case BABYLON.PhysicsJoint.WheelJoint:
  55584. type = "jointWheel";
  55585. break;
  55586. case BABYLON.PhysicsJoint.HingeJoint:
  55587. default:
  55588. type = "jointHinge";
  55589. break;
  55590. }
  55591. nativeJointData.type = type;
  55592. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  55593. };
  55594. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  55595. //Bug in Oimo prevents us from disposing a joint in the playground
  55596. //joint.joint.physicsJoint.dispose();
  55597. //So we will bruteforce it!
  55598. try {
  55599. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  55600. }
  55601. catch (e) {
  55602. BABYLON.Tools.Warn(e);
  55603. }
  55604. };
  55605. OimoJSPlugin.prototype.isSupported = function () {
  55606. return OIMO !== undefined;
  55607. };
  55608. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  55609. if (!impostor.physicsBody.sleeping) {
  55610. //TODO check that
  55611. if (impostor.physicsBody.shapes.next) {
  55612. var parentShape = this._getLastShape(impostor.physicsBody);
  55613. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  55614. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  55615. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  55616. }
  55617. else {
  55618. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  55619. }
  55620. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  55621. impostor.object.rotationQuaternion.normalize();
  55622. }
  55623. };
  55624. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  55625. var body = impostor.physicsBody;
  55626. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  55627. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  55628. body.syncShapes();
  55629. body.awake();
  55630. };
  55631. OimoJSPlugin.prototype._getLastShape = function (body) {
  55632. var lastShape = body.shapes;
  55633. while (lastShape.next) {
  55634. lastShape = lastShape.next;
  55635. }
  55636. return lastShape;
  55637. };
  55638. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  55639. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  55640. };
  55641. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  55642. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  55643. };
  55644. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  55645. var v = impostor.physicsBody.linearVelocity;
  55646. if (!v)
  55647. return null;
  55648. return new BABYLON.Vector3(v.x, v.y, v.z);
  55649. };
  55650. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  55651. var v = impostor.physicsBody.angularVelocity;
  55652. if (!v)
  55653. return null;
  55654. return new BABYLON.Vector3(v.x, v.y, v.z);
  55655. };
  55656. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  55657. var staticBody = mass === 0;
  55658. //this will actually set the body's density and not its mass.
  55659. //But this is how oimo treats the mass variable.
  55660. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  55661. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  55662. };
  55663. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  55664. impostor.physicsBody.sleep();
  55665. };
  55666. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  55667. impostor.physicsBody.awake();
  55668. };
  55669. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  55670. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  55671. if (minDistance !== void 0) {
  55672. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  55673. }
  55674. };
  55675. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  55676. //TODO separate rotational and transational motors.
  55677. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  55678. if (motor) {
  55679. motor.setMotor(speed, maxForce);
  55680. }
  55681. };
  55682. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  55683. //TODO separate rotational and transational motors.
  55684. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  55685. if (motor) {
  55686. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  55687. }
  55688. };
  55689. OimoJSPlugin.prototype.dispose = function () {
  55690. this.world.clear();
  55691. };
  55692. return OimoJSPlugin;
  55693. }());
  55694. BABYLON.OimoJSPlugin = OimoJSPlugin;
  55695. })(BABYLON || (BABYLON = {}));
  55696. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  55697. var BABYLON;
  55698. (function (BABYLON) {
  55699. var Internals;
  55700. (function (Internals) {
  55701. /*
  55702. * Based on jsTGALoader - Javascript loader for TGA file
  55703. * By Vincent Thibault
  55704. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  55705. */
  55706. var TGATools = (function () {
  55707. function TGATools() {
  55708. }
  55709. TGATools.GetTGAHeader = function (data) {
  55710. var offset = 0;
  55711. var header = {
  55712. id_length: data[offset++],
  55713. colormap_type: data[offset++],
  55714. image_type: data[offset++],
  55715. colormap_index: data[offset++] | data[offset++] << 8,
  55716. colormap_length: data[offset++] | data[offset++] << 8,
  55717. colormap_size: data[offset++],
  55718. origin: [
  55719. data[offset++] | data[offset++] << 8,
  55720. data[offset++] | data[offset++] << 8
  55721. ],
  55722. width: data[offset++] | data[offset++] << 8,
  55723. height: data[offset++] | data[offset++] << 8,
  55724. pixel_size: data[offset++],
  55725. flags: data[offset++]
  55726. };
  55727. return header;
  55728. };
  55729. TGATools.UploadContent = function (gl, data) {
  55730. // Not enough data to contain header ?
  55731. if (data.length < 19) {
  55732. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  55733. return;
  55734. }
  55735. // Read Header
  55736. var offset = 18;
  55737. var header = TGATools.GetTGAHeader(data);
  55738. // Assume it's a valid Targa file.
  55739. if (header.id_length + offset > data.length) {
  55740. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  55741. return;
  55742. }
  55743. // Skip not needed data
  55744. offset += header.id_length;
  55745. var use_rle = false;
  55746. var use_pal = false;
  55747. var use_rgb = false;
  55748. var use_grey = false;
  55749. // Get some informations.
  55750. switch (header.image_type) {
  55751. case TGATools._TYPE_RLE_INDEXED:
  55752. use_rle = true;
  55753. case TGATools._TYPE_INDEXED:
  55754. use_pal = true;
  55755. break;
  55756. case TGATools._TYPE_RLE_RGB:
  55757. use_rle = true;
  55758. case TGATools._TYPE_RGB:
  55759. use_rgb = true;
  55760. break;
  55761. case TGATools._TYPE_RLE_GREY:
  55762. use_rle = true;
  55763. case TGATools._TYPE_GREY:
  55764. use_grey = true;
  55765. break;
  55766. }
  55767. var pixel_data;
  55768. var numAlphaBits = header.flags & 0xf;
  55769. var pixel_size = header.pixel_size >> 3;
  55770. var pixel_total = header.width * header.height * pixel_size;
  55771. // Read palettes
  55772. var palettes;
  55773. if (use_pal) {
  55774. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  55775. }
  55776. // Read LRE
  55777. if (use_rle) {
  55778. pixel_data = new Uint8Array(pixel_total);
  55779. var c, count, i;
  55780. var localOffset = 0;
  55781. var pixels = new Uint8Array(pixel_size);
  55782. while (offset < pixel_total && localOffset < pixel_total) {
  55783. c = data[offset++];
  55784. count = (c & 0x7f) + 1;
  55785. // RLE pixels
  55786. if (c & 0x80) {
  55787. // Bind pixel tmp array
  55788. for (i = 0; i < pixel_size; ++i) {
  55789. pixels[i] = data[offset++];
  55790. }
  55791. // Copy pixel array
  55792. for (i = 0; i < count; ++i) {
  55793. pixel_data.set(pixels, localOffset + i * pixel_size);
  55794. }
  55795. localOffset += pixel_size * count;
  55796. }
  55797. else {
  55798. count *= pixel_size;
  55799. for (i = 0; i < count; ++i) {
  55800. pixel_data[localOffset + i] = data[offset++];
  55801. }
  55802. localOffset += count;
  55803. }
  55804. }
  55805. }
  55806. else {
  55807. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  55808. }
  55809. // Load to texture
  55810. var x_start, y_start, x_step, y_step, y_end, x_end;
  55811. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  55812. default:
  55813. case TGATools._ORIGIN_UL:
  55814. x_start = 0;
  55815. x_step = 1;
  55816. x_end = header.width;
  55817. y_start = 0;
  55818. y_step = 1;
  55819. y_end = header.height;
  55820. break;
  55821. case TGATools._ORIGIN_BL:
  55822. x_start = 0;
  55823. x_step = 1;
  55824. x_end = header.width;
  55825. y_start = header.height - 1;
  55826. y_step = -1;
  55827. y_end = -1;
  55828. break;
  55829. case TGATools._ORIGIN_UR:
  55830. x_start = header.width - 1;
  55831. x_step = -1;
  55832. x_end = -1;
  55833. y_start = 0;
  55834. y_step = 1;
  55835. y_end = header.height;
  55836. break;
  55837. case TGATools._ORIGIN_BR:
  55838. x_start = header.width - 1;
  55839. x_step = -1;
  55840. x_end = -1;
  55841. y_start = header.height - 1;
  55842. y_step = -1;
  55843. y_end = -1;
  55844. break;
  55845. }
  55846. // Load the specify method
  55847. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  55848. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  55849. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  55850. };
  55851. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55852. var image = pixel_data, colormap = palettes;
  55853. var width = header.width, height = header.height;
  55854. var color, i = 0, x, y;
  55855. var imageData = new Uint8Array(width * height * 4);
  55856. for (y = y_start; y !== y_end; y += y_step) {
  55857. for (x = x_start; x !== x_end; x += x_step, i++) {
  55858. color = image[i];
  55859. imageData[(x + width * y) * 4 + 3] = 255;
  55860. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  55861. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  55862. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  55863. }
  55864. }
  55865. return imageData;
  55866. };
  55867. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55868. var image = pixel_data;
  55869. var width = header.width, height = header.height;
  55870. var color, i = 0, x, y;
  55871. var imageData = new Uint8Array(width * height * 4);
  55872. for (y = y_start; y !== y_end; y += y_step) {
  55873. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  55874. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  55875. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  55876. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  55877. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  55878. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  55879. }
  55880. }
  55881. return imageData;
  55882. };
  55883. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55884. var image = pixel_data;
  55885. var width = header.width, height = header.height;
  55886. var i = 0, x, y;
  55887. var imageData = new Uint8Array(width * height * 4);
  55888. for (y = y_start; y !== y_end; y += y_step) {
  55889. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  55890. imageData[(x + width * y) * 4 + 3] = 255;
  55891. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  55892. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  55893. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  55894. }
  55895. }
  55896. return imageData;
  55897. };
  55898. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55899. var image = pixel_data;
  55900. var width = header.width, height = header.height;
  55901. var i = 0, x, y;
  55902. var imageData = new Uint8Array(width * height * 4);
  55903. for (y = y_start; y !== y_end; y += y_step) {
  55904. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  55905. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  55906. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  55907. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  55908. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  55909. }
  55910. }
  55911. return imageData;
  55912. };
  55913. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55914. var image = pixel_data;
  55915. var width = header.width, height = header.height;
  55916. var color, i = 0, x, y;
  55917. var imageData = new Uint8Array(width * height * 4);
  55918. for (y = y_start; y !== y_end; y += y_step) {
  55919. for (x = x_start; x !== x_end; x += x_step, i++) {
  55920. color = image[i];
  55921. imageData[(x + width * y) * 4 + 0] = color;
  55922. imageData[(x + width * y) * 4 + 1] = color;
  55923. imageData[(x + width * y) * 4 + 2] = color;
  55924. imageData[(x + width * y) * 4 + 3] = 255;
  55925. }
  55926. }
  55927. return imageData;
  55928. };
  55929. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55930. var image = pixel_data;
  55931. var width = header.width, height = header.height;
  55932. var i = 0, x, y;
  55933. var imageData = new Uint8Array(width * height * 4);
  55934. for (y = y_start; y !== y_end; y += y_step) {
  55935. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  55936. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  55937. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  55938. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  55939. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  55940. }
  55941. }
  55942. return imageData;
  55943. };
  55944. return TGATools;
  55945. }());
  55946. TGATools._TYPE_NO_DATA = 0;
  55947. TGATools._TYPE_INDEXED = 1;
  55948. TGATools._TYPE_RGB = 2;
  55949. TGATools._TYPE_GREY = 3;
  55950. TGATools._TYPE_RLE_INDEXED = 9;
  55951. TGATools._TYPE_RLE_RGB = 10;
  55952. TGATools._TYPE_RLE_GREY = 11;
  55953. TGATools._ORIGIN_MASK = 0x30;
  55954. TGATools._ORIGIN_SHIFT = 0x04;
  55955. TGATools._ORIGIN_BL = 0x00;
  55956. TGATools._ORIGIN_BR = 0x01;
  55957. TGATools._ORIGIN_UL = 0x02;
  55958. TGATools._ORIGIN_UR = 0x03;
  55959. Internals.TGATools = TGATools;
  55960. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55961. })(BABYLON || (BABYLON = {}));
  55962. //# sourceMappingURL=babylon.tga.js.map
  55963. var BABYLON;
  55964. (function (BABYLON) {
  55965. var Internals;
  55966. (function (Internals) {
  55967. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  55968. // All values and structures referenced from:
  55969. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  55970. var DDS_MAGIC = 0x20534444;
  55971. 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;
  55972. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  55973. 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;
  55974. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  55975. function FourCCToInt32(value) {
  55976. return value.charCodeAt(0) +
  55977. (value.charCodeAt(1) << 8) +
  55978. (value.charCodeAt(2) << 16) +
  55979. (value.charCodeAt(3) << 24);
  55980. }
  55981. function Int32ToFourCC(value) {
  55982. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  55983. }
  55984. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  55985. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  55986. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  55987. var headerLengthInt = 31; // The header length in 32 bit ints
  55988. // Offsets into the header array
  55989. var off_magic = 0;
  55990. var off_size = 1;
  55991. var off_flags = 2;
  55992. var off_height = 3;
  55993. var off_width = 4;
  55994. var off_mipmapCount = 7;
  55995. var off_pfFlags = 20;
  55996. var off_pfFourCC = 21;
  55997. var off_RGBbpp = 22;
  55998. var off_RMask = 23;
  55999. var off_GMask = 24;
  56000. var off_BMask = 25;
  56001. var off_AMask = 26;
  56002. var off_caps1 = 27;
  56003. var off_caps2 = 28;
  56004. ;
  56005. var DDSTools = (function () {
  56006. function DDSTools() {
  56007. }
  56008. DDSTools.GetDDSInfo = function (arrayBuffer) {
  56009. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  56010. var mipmapCount = 1;
  56011. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  56012. mipmapCount = Math.max(1, header[off_mipmapCount]);
  56013. }
  56014. return {
  56015. width: header[off_width],
  56016. height: header[off_height],
  56017. mipmapCount: mipmapCount,
  56018. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  56019. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  56020. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  56021. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  56022. };
  56023. };
  56024. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  56025. var byteArray = new Uint8Array(dataLength);
  56026. var srcData = new Uint8Array(arrayBuffer);
  56027. var index = 0;
  56028. for (var y = height - 1; y >= 0; y--) {
  56029. for (var x = 0; x < width; x++) {
  56030. var srcPos = dataOffset + (x + y * width) * 4;
  56031. byteArray[index + 2] = srcData[srcPos];
  56032. byteArray[index + 1] = srcData[srcPos + 1];
  56033. byteArray[index] = srcData[srcPos + 2];
  56034. byteArray[index + 3] = srcData[srcPos + 3];
  56035. index += 4;
  56036. }
  56037. }
  56038. return byteArray;
  56039. };
  56040. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  56041. var byteArray = new Uint8Array(dataLength);
  56042. var srcData = new Uint8Array(arrayBuffer);
  56043. var index = 0;
  56044. for (var y = height - 1; y >= 0; y--) {
  56045. for (var x = 0; x < width; x++) {
  56046. var srcPos = dataOffset + (x + y * width) * 3;
  56047. byteArray[index + 2] = srcData[srcPos];
  56048. byteArray[index + 1] = srcData[srcPos + 1];
  56049. byteArray[index] = srcData[srcPos + 2];
  56050. index += 3;
  56051. }
  56052. }
  56053. return byteArray;
  56054. };
  56055. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  56056. var byteArray = new Uint8Array(dataLength);
  56057. var srcData = new Uint8Array(arrayBuffer);
  56058. var index = 0;
  56059. for (var y = height - 1; y >= 0; y--) {
  56060. for (var x = 0; x < width; x++) {
  56061. var srcPos = dataOffset + (x + y * width);
  56062. byteArray[index] = srcData[srcPos];
  56063. index++;
  56064. }
  56065. }
  56066. return byteArray;
  56067. };
  56068. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  56069. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  56070. if (header[off_magic] != DDS_MAGIC) {
  56071. BABYLON.Tools.Error("Invalid magic number in DDS header");
  56072. return;
  56073. }
  56074. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  56075. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  56076. return;
  56077. }
  56078. if (info.isFourCC) {
  56079. fourCC = header[off_pfFourCC];
  56080. switch (fourCC) {
  56081. case FOURCC_DXT1:
  56082. blockBytes = 8;
  56083. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  56084. break;
  56085. case FOURCC_DXT3:
  56086. blockBytes = 16;
  56087. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  56088. break;
  56089. case FOURCC_DXT5:
  56090. blockBytes = 16;
  56091. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  56092. break;
  56093. default:
  56094. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  56095. return;
  56096. }
  56097. }
  56098. mipmapCount = 1;
  56099. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  56100. mipmapCount = Math.max(1, header[off_mipmapCount]);
  56101. }
  56102. var bpp = header[off_RGBbpp];
  56103. for (var face = 0; face < faces; face++) {
  56104. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  56105. width = header[off_width];
  56106. height = header[off_height];
  56107. dataOffset = header[off_size] + 4;
  56108. for (i = 0; i < mipmapCount; ++i) {
  56109. if (info.isRGB) {
  56110. if (bpp === 24) {
  56111. dataLength = width * height * 3;
  56112. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  56113. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  56114. }
  56115. else {
  56116. dataLength = width * height * 4;
  56117. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  56118. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  56119. }
  56120. }
  56121. else if (info.isLuminance) {
  56122. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  56123. var unpaddedRowSize = width;
  56124. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  56125. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  56126. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  56127. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  56128. }
  56129. else {
  56130. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  56131. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  56132. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  56133. }
  56134. dataOffset += dataLength;
  56135. width *= 0.5;
  56136. height *= 0.5;
  56137. width = Math.max(1.0, width);
  56138. height = Math.max(1.0, height);
  56139. }
  56140. }
  56141. };
  56142. return DDSTools;
  56143. }());
  56144. Internals.DDSTools = DDSTools;
  56145. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56146. })(BABYLON || (BABYLON = {}));
  56147. //# sourceMappingURL=babylon.dds.js.map
  56148. var BABYLON;
  56149. (function (BABYLON) {
  56150. var Internals;
  56151. (function (Internals) {
  56152. /**
  56153. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  56154. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  56155. */
  56156. var KhronosTextureContainer = (function () {
  56157. /**
  56158. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  56159. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  56160. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  56161. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  56162. */
  56163. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  56164. this.arrayBuffer = arrayBuffer;
  56165. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  56166. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  56167. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  56168. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  56169. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  56170. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  56171. BABYLON.Tools.Error("texture missing KTX identifier");
  56172. return;
  56173. }
  56174. // load the reset of the header in native 32 bit int
  56175. var header = new Int32Array(this.arrayBuffer, 12, 13);
  56176. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  56177. var oppositeEndianess = header[0] === 0x01020304;
  56178. // read all the header elements in order they exist in the file, without modification (sans endainness)
  56179. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  56180. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  56181. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  56182. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  56183. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  56184. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  56185. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  56186. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  56187. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  56188. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  56189. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  56190. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  56191. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  56192. if (this.glType !== 0) {
  56193. BABYLON.Tools.Error("only compressed formats currently supported");
  56194. return;
  56195. }
  56196. else {
  56197. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  56198. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  56199. }
  56200. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  56201. BABYLON.Tools.Error("only 2D textures currently supported");
  56202. return;
  56203. }
  56204. if (this.numberOfArrayElements !== 0) {
  56205. BABYLON.Tools.Error("texture arrays not currently supported");
  56206. return;
  56207. }
  56208. if (this.numberOfFaces !== facesExpected) {
  56209. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  56210. return;
  56211. }
  56212. // we now have a completely validated file, so could use existence of loadType as success
  56213. // would need to make this more elaborate & adjust checks above to support more than one load type
  56214. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  56215. }
  56216. // not as fast hardware based, but will probably never need to use
  56217. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  56218. return ((val & 0xFF) << 24)
  56219. | ((val & 0xFF00) << 8)
  56220. | ((val >> 8) & 0xFF00)
  56221. | ((val >> 24) & 0xFF);
  56222. };
  56223. /**
  56224. * It is assumed that the texture has already been created & is currently bound
  56225. */
  56226. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  56227. switch (this.loadType) {
  56228. case KhronosTextureContainer.COMPRESSED_2D:
  56229. this._upload2DCompressedLevels(gl, loadMipmaps);
  56230. break;
  56231. case KhronosTextureContainer.TEX_2D:
  56232. case KhronosTextureContainer.COMPRESSED_3D:
  56233. case KhronosTextureContainer.TEX_3D:
  56234. }
  56235. };
  56236. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  56237. // initialize width & height for level 1
  56238. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  56239. var width = this.pixelWidth;
  56240. var height = this.pixelHeight;
  56241. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  56242. for (var level = 0; level < mipmapCount; level++) {
  56243. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  56244. for (var face = 0; face < this.numberOfFaces; face++) {
  56245. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  56246. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  56247. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  56248. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  56249. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  56250. }
  56251. width = Math.max(1.0, width * 0.5);
  56252. height = Math.max(1.0, height * 0.5);
  56253. }
  56254. };
  56255. return KhronosTextureContainer;
  56256. }());
  56257. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  56258. // load types
  56259. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  56260. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  56261. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  56262. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  56263. Internals.KhronosTextureContainer = KhronosTextureContainer;
  56264. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  56265. })(BABYLON || (BABYLON = {}));
  56266. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  56267. var BABYLON;
  56268. (function (BABYLON) {
  56269. var Debug;
  56270. (function (Debug) {
  56271. /**
  56272. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  56273. */
  56274. var SkeletonViewer = (function () {
  56275. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  56276. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  56277. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  56278. this.skeleton = skeleton;
  56279. this.mesh = mesh;
  56280. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  56281. this.renderingGroupId = renderingGroupId;
  56282. this.color = BABYLON.Color3.White();
  56283. this._debugLines = [];
  56284. this._isEnabled = false;
  56285. this._scene = scene;
  56286. this.update();
  56287. this._renderFunction = this.update.bind(this);
  56288. }
  56289. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  56290. get: function () {
  56291. return this._isEnabled;
  56292. },
  56293. set: function (value) {
  56294. if (this._isEnabled === value) {
  56295. return;
  56296. }
  56297. this._isEnabled = value;
  56298. if (value) {
  56299. this._scene.registerBeforeRender(this._renderFunction);
  56300. }
  56301. else {
  56302. this._scene.unregisterBeforeRender(this._renderFunction);
  56303. }
  56304. },
  56305. enumerable: true,
  56306. configurable: true
  56307. });
  56308. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  56309. if (x === void 0) { x = 0; }
  56310. if (y === void 0) { y = 0; }
  56311. if (z === void 0) { z = 0; }
  56312. var tmat = BABYLON.Tmp.Matrix[0];
  56313. var parentBone = bone.getParent();
  56314. tmat.copyFrom(bone.getLocalMatrix());
  56315. if (x !== 0 || y !== 0 || z !== 0) {
  56316. var tmat2 = BABYLON.Tmp.Matrix[1];
  56317. BABYLON.Matrix.IdentityToRef(tmat2);
  56318. tmat2.m[12] = x;
  56319. tmat2.m[13] = y;
  56320. tmat2.m[14] = z;
  56321. tmat2.multiplyToRef(tmat, tmat);
  56322. }
  56323. if (parentBone) {
  56324. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  56325. }
  56326. tmat.multiplyToRef(meshMat, tmat);
  56327. position.x = tmat.m[12];
  56328. position.y = tmat.m[13];
  56329. position.z = tmat.m[14];
  56330. };
  56331. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  56332. var len = bones.length;
  56333. for (var i = 0; i < len; i++) {
  56334. var bone = bones[i];
  56335. var points = this._debugLines[i];
  56336. if (!points) {
  56337. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56338. this._debugLines[i] = points;
  56339. }
  56340. this._getBonePosition(points[0], bone, meshMat);
  56341. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  56342. }
  56343. };
  56344. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  56345. var len = bones.length;
  56346. var boneNum = 0;
  56347. for (var i = len - 1; i >= 0; i--) {
  56348. var childBone = bones[i];
  56349. var parentBone = childBone.getParent();
  56350. if (!parentBone) {
  56351. continue;
  56352. }
  56353. var points = this._debugLines[boneNum];
  56354. if (!points) {
  56355. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56356. this._debugLines[boneNum] = points;
  56357. }
  56358. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  56359. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  56360. boneNum++;
  56361. }
  56362. };
  56363. SkeletonViewer.prototype.update = function () {
  56364. if (this.autoUpdateBonesMatrices) {
  56365. this.skeleton.computeAbsoluteTransforms();
  56366. }
  56367. if (this.skeleton.bones[0].length === undefined) {
  56368. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56369. }
  56370. else {
  56371. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56372. }
  56373. if (!this._debugMesh) {
  56374. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  56375. this._debugMesh.renderingGroupId = this.renderingGroupId;
  56376. }
  56377. else {
  56378. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  56379. }
  56380. this._debugMesh.color = this.color;
  56381. };
  56382. SkeletonViewer.prototype.dispose = function () {
  56383. if (this._debugMesh) {
  56384. this.isEnabled = false;
  56385. this._debugMesh.dispose();
  56386. this._debugMesh = null;
  56387. }
  56388. };
  56389. return SkeletonViewer;
  56390. }());
  56391. Debug.SkeletonViewer = SkeletonViewer;
  56392. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56393. })(BABYLON || (BABYLON = {}));
  56394. //# sourceMappingURL=babylon.skeletonViewer.js.map
  56395. var BABYLON;
  56396. (function (BABYLON) {
  56397. var Debug;
  56398. (function (Debug) {
  56399. var AxesViewer = (function () {
  56400. function AxesViewer(scene, scaleLines) {
  56401. if (scaleLines === void 0) { scaleLines = 1; }
  56402. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56403. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56404. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56405. this.scaleLines = 1;
  56406. this.scaleLines = scaleLines;
  56407. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  56408. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  56409. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  56410. this._xmesh.renderingGroupId = 2;
  56411. this._ymesh.renderingGroupId = 2;
  56412. this._zmesh.renderingGroupId = 2;
  56413. this._xmesh.material.checkReadyOnlyOnce = true;
  56414. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  56415. this._ymesh.material.checkReadyOnlyOnce = true;
  56416. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  56417. this._zmesh.material.checkReadyOnlyOnce = true;
  56418. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  56419. this.scene = scene;
  56420. }
  56421. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  56422. var scaleLines = this.scaleLines;
  56423. var point1 = this._xline[0];
  56424. var point2 = this._xline[1];
  56425. point1.x = position.x;
  56426. point1.y = position.y;
  56427. point1.z = position.z;
  56428. point2.x = point1.x + xaxis.x * scaleLines;
  56429. point2.y = point1.y + xaxis.y * scaleLines;
  56430. point2.z = point1.z + xaxis.z * scaleLines;
  56431. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  56432. point1 = this._yline[0];
  56433. point2 = this._yline[1];
  56434. point1.x = position.x;
  56435. point1.y = position.y;
  56436. point1.z = position.z;
  56437. point2.x = point1.x + yaxis.x * scaleLines;
  56438. point2.y = point1.y + yaxis.y * scaleLines;
  56439. point2.z = point1.z + yaxis.z * scaleLines;
  56440. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  56441. point1 = this._zline[0];
  56442. point2 = this._zline[1];
  56443. point1.x = position.x;
  56444. point1.y = position.y;
  56445. point1.z = position.z;
  56446. point2.x = point1.x + zaxis.x * scaleLines;
  56447. point2.y = point1.y + zaxis.y * scaleLines;
  56448. point2.z = point1.z + zaxis.z * scaleLines;
  56449. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  56450. };
  56451. AxesViewer.prototype.dispose = function () {
  56452. if (this._xmesh) {
  56453. this._xmesh.dispose();
  56454. this._ymesh.dispose();
  56455. this._zmesh.dispose();
  56456. this._xmesh = null;
  56457. this._ymesh = null;
  56458. this._zmesh = null;
  56459. this._xline = null;
  56460. this._yline = null;
  56461. this._zline = null;
  56462. this.scene = null;
  56463. }
  56464. };
  56465. return AxesViewer;
  56466. }());
  56467. Debug.AxesViewer = AxesViewer;
  56468. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56469. })(BABYLON || (BABYLON = {}));
  56470. //# sourceMappingURL=babylon.axesViewer.js.map
  56471. var BABYLON;
  56472. (function (BABYLON) {
  56473. var Debug;
  56474. (function (Debug) {
  56475. var BoneAxesViewer = (function (_super) {
  56476. __extends(BoneAxesViewer, _super);
  56477. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  56478. if (scaleLines === void 0) { scaleLines = 1; }
  56479. var _this = _super.call(this, scene, scaleLines) || this;
  56480. _this.pos = BABYLON.Vector3.Zero();
  56481. _this.xaxis = BABYLON.Vector3.Zero();
  56482. _this.yaxis = BABYLON.Vector3.Zero();
  56483. _this.zaxis = BABYLON.Vector3.Zero();
  56484. _this.mesh = mesh;
  56485. _this.bone = bone;
  56486. return _this;
  56487. }
  56488. BoneAxesViewer.prototype.update = function () {
  56489. var bone = this.bone;
  56490. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  56491. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  56492. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  56493. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  56494. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  56495. };
  56496. BoneAxesViewer.prototype.dispose = function () {
  56497. if (this.pos) {
  56498. this.pos = null;
  56499. this.xaxis = null;
  56500. this.yaxis = null;
  56501. this.zaxis = null;
  56502. this.mesh = null;
  56503. this.bone = null;
  56504. _super.prototype.dispose.call(this);
  56505. }
  56506. };
  56507. return BoneAxesViewer;
  56508. }(Debug.AxesViewer));
  56509. Debug.BoneAxesViewer = BoneAxesViewer;
  56510. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56511. })(BABYLON || (BABYLON = {}));
  56512. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  56513. var BABYLON;
  56514. (function (BABYLON) {
  56515. var RayHelper = (function () {
  56516. function RayHelper(ray) {
  56517. this.ray = ray;
  56518. }
  56519. RayHelper.CreateAndShow = function (ray, scene, color) {
  56520. var helper = new RayHelper(ray);
  56521. helper.show(scene, color);
  56522. return helper;
  56523. };
  56524. RayHelper.prototype.show = function (scene, color) {
  56525. if (!this._renderFunction) {
  56526. var ray = this.ray;
  56527. this._renderFunction = this._render.bind(this);
  56528. this._scene = scene;
  56529. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  56530. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  56531. this._scene.registerBeforeRender(this._renderFunction);
  56532. }
  56533. if (color) {
  56534. this._renderLine.color.copyFrom(color);
  56535. }
  56536. };
  56537. RayHelper.prototype.hide = function () {
  56538. if (this._renderFunction) {
  56539. this._scene.unregisterBeforeRender(this._renderFunction);
  56540. this._scene = null;
  56541. this._renderFunction = null;
  56542. this._renderLine.dispose();
  56543. this._renderLine = null;
  56544. this._renderPoints = null;
  56545. }
  56546. };
  56547. RayHelper.prototype._render = function () {
  56548. var ray = this.ray;
  56549. var point = this._renderPoints[1];
  56550. var len = Math.min(ray.length, 1000000);
  56551. point.copyFrom(ray.direction);
  56552. point.scaleInPlace(len);
  56553. point.addInPlace(ray.origin);
  56554. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  56555. };
  56556. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  56557. this._attachedToMesh = mesh;
  56558. var ray = this.ray;
  56559. if (!ray.direction) {
  56560. ray.direction = BABYLON.Vector3.Zero();
  56561. }
  56562. if (!ray.origin) {
  56563. ray.origin = BABYLON.Vector3.Zero();
  56564. }
  56565. if (length) {
  56566. ray.length = length;
  56567. }
  56568. if (!meshSpaceOrigin) {
  56569. meshSpaceOrigin = BABYLON.Vector3.Zero();
  56570. }
  56571. if (!meshSpaceDirection) {
  56572. // -1 so that this will work with Mesh.lookAt
  56573. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  56574. }
  56575. if (!this._meshSpaceDirection) {
  56576. this._meshSpaceDirection = meshSpaceDirection.clone();
  56577. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  56578. }
  56579. else {
  56580. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  56581. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  56582. }
  56583. if (!this._updateToMeshFunction) {
  56584. this._updateToMeshFunction = this._updateToMesh.bind(this);
  56585. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  56586. }
  56587. this._updateToMesh();
  56588. };
  56589. RayHelper.prototype.detachFromMesh = function () {
  56590. if (this._attachedToMesh) {
  56591. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  56592. this._attachedToMesh = null;
  56593. this._updateToMeshFunction = null;
  56594. }
  56595. };
  56596. RayHelper.prototype._updateToMesh = function () {
  56597. var ray = this.ray;
  56598. if (this._attachedToMesh._isDisposed) {
  56599. this.detachFromMesh();
  56600. return;
  56601. }
  56602. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  56603. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  56604. };
  56605. RayHelper.prototype.dispose = function () {
  56606. this.hide();
  56607. this.detachFromMesh();
  56608. this.ray = null;
  56609. };
  56610. return RayHelper;
  56611. }());
  56612. BABYLON.RayHelper = RayHelper;
  56613. })(BABYLON || (BABYLON = {}));
  56614. //# sourceMappingURL=babylon.rayHelper.js.map
  56615. var BABYLON;
  56616. (function (BABYLON) {
  56617. var DebugLayer = (function () {
  56618. function DebugLayer(scene) {
  56619. this._scene = scene;
  56620. }
  56621. /** Creates the inspector window. */
  56622. DebugLayer.prototype._createInspector = function (config) {
  56623. if (config === void 0) { config = {}; }
  56624. var popup = config.popup || false;
  56625. var initialTab = config.initialTab || 0;
  56626. var parentElement = config.parentElement || null;
  56627. if (!this._inspector) {
  56628. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  56629. } // else nothing to do,; instance is already existing
  56630. };
  56631. DebugLayer.prototype.isVisible = function () {
  56632. if (!this._inspector) {
  56633. return false;
  56634. }
  56635. return true;
  56636. };
  56637. DebugLayer.prototype.hide = function () {
  56638. if (this._inspector) {
  56639. try {
  56640. this._inspector.dispose();
  56641. }
  56642. catch (e) {
  56643. // If the inspector has been removed directly from the inspector tool
  56644. }
  56645. this._inspector = null;
  56646. }
  56647. };
  56648. DebugLayer.prototype.show = function (config) {
  56649. if (config === void 0) { config = {}; }
  56650. if (typeof INSPECTOR == 'undefined') {
  56651. // Load inspector and add it to the DOM
  56652. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  56653. }
  56654. else {
  56655. // Otherwise creates the inspector
  56656. this._createInspector(config);
  56657. }
  56658. };
  56659. return DebugLayer;
  56660. }());
  56661. // Get protocol used - http or https
  56662. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//www.babylonjs.com/babylon.inspector.bundle.js';
  56663. BABYLON.DebugLayer = DebugLayer;
  56664. })(BABYLON || (BABYLON = {}));
  56665. //# sourceMappingURL=babylon.debugLayer.js.map
  56666. var BABYLON;
  56667. (function (BABYLON) {
  56668. var BoundingBoxRenderer = (function () {
  56669. function BoundingBoxRenderer(scene) {
  56670. this.frontColor = new BABYLON.Color3(1, 1, 1);
  56671. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  56672. this.showBackLines = true;
  56673. this.renderList = new BABYLON.SmartArray(32);
  56674. this._vertexBuffers = {};
  56675. this._scene = scene;
  56676. }
  56677. BoundingBoxRenderer.prototype._prepareRessources = function () {
  56678. if (this._colorShader) {
  56679. return;
  56680. }
  56681. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  56682. attributes: [BABYLON.VertexBuffer.PositionKind],
  56683. uniforms: ["world", "viewProjection", "color"]
  56684. });
  56685. var engine = this._scene.getEngine();
  56686. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  56687. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  56688. 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]);
  56689. };
  56690. BoundingBoxRenderer.prototype.reset = function () {
  56691. this.renderList.reset();
  56692. };
  56693. BoundingBoxRenderer.prototype.render = function () {
  56694. if (this.renderList.length === 0) {
  56695. return;
  56696. }
  56697. this._prepareRessources();
  56698. if (!this._colorShader.isReady()) {
  56699. return;
  56700. }
  56701. var engine = this._scene.getEngine();
  56702. engine.setDepthWrite(false);
  56703. this._colorShader._preBind();
  56704. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  56705. var boundingBox = this.renderList.data[boundingBoxIndex];
  56706. var min = boundingBox.minimum;
  56707. var max = boundingBox.maximum;
  56708. var diff = max.subtract(min);
  56709. var median = min.add(diff.scale(0.5));
  56710. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  56711. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  56712. .multiply(boundingBox.getWorldMatrix());
  56713. // VBOs
  56714. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  56715. if (this.showBackLines) {
  56716. // Back
  56717. engine.setDepthFunctionToGreaterOrEqual();
  56718. this._scene.resetCachedMaterial();
  56719. this._colorShader.setColor4("color", this.backColor.toColor4());
  56720. this._colorShader.bind(worldMatrix);
  56721. // Draw order
  56722. engine.draw(false, 0, 24);
  56723. }
  56724. // Front
  56725. engine.setDepthFunctionToLess();
  56726. this._scene.resetCachedMaterial();
  56727. this._colorShader.setColor4("color", this.frontColor.toColor4());
  56728. this._colorShader.bind(worldMatrix);
  56729. // Draw order
  56730. engine.draw(false, 0, 24);
  56731. }
  56732. this._colorShader.unbind();
  56733. engine.setDepthFunctionToLessOrEqual();
  56734. engine.setDepthWrite(true);
  56735. };
  56736. BoundingBoxRenderer.prototype.dispose = function () {
  56737. if (!this._colorShader) {
  56738. return;
  56739. }
  56740. this.renderList.dispose();
  56741. this._colorShader.dispose();
  56742. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  56743. if (buffer) {
  56744. buffer.dispose();
  56745. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  56746. }
  56747. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56748. };
  56749. return BoundingBoxRenderer;
  56750. }());
  56751. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  56752. })(BABYLON || (BABYLON = {}));
  56753. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  56754. var BABYLON;
  56755. (function (BABYLON) {
  56756. var MorphTarget = (function () {
  56757. function MorphTarget(name, influence) {
  56758. if (influence === void 0) { influence = 0; }
  56759. this.name = name;
  56760. this.onInfluenceChanged = new BABYLON.Observable();
  56761. this.influence = influence;
  56762. }
  56763. Object.defineProperty(MorphTarget.prototype, "influence", {
  56764. get: function () {
  56765. return this._influence;
  56766. },
  56767. set: function (influence) {
  56768. if (this._influence === influence) {
  56769. return;
  56770. }
  56771. var previous = this._influence;
  56772. this._influence = influence;
  56773. if (this.onInfluenceChanged.hasObservers) {
  56774. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  56775. }
  56776. },
  56777. enumerable: true,
  56778. configurable: true
  56779. });
  56780. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  56781. get: function () {
  56782. return this._normals !== undefined;
  56783. },
  56784. enumerable: true,
  56785. configurable: true
  56786. });
  56787. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  56788. get: function () {
  56789. return this._tangents !== undefined;
  56790. },
  56791. enumerable: true,
  56792. configurable: true
  56793. });
  56794. MorphTarget.prototype.setPositions = function (data) {
  56795. this._positions = new Float32Array(data);
  56796. };
  56797. MorphTarget.prototype.getPositions = function () {
  56798. return this._positions;
  56799. };
  56800. MorphTarget.prototype.setNormals = function (data) {
  56801. this._normals = new Float32Array(data);
  56802. };
  56803. MorphTarget.prototype.getNormals = function () {
  56804. return this._normals;
  56805. };
  56806. MorphTarget.prototype.setTangents = function (data) {
  56807. this._tangents = new Float32Array(data);
  56808. };
  56809. MorphTarget.prototype.getTangents = function () {
  56810. return this._tangents;
  56811. };
  56812. /**
  56813. * Serializes the current target into a Serialization object.
  56814. * Returns the serialized object.
  56815. */
  56816. MorphTarget.prototype.serialize = function () {
  56817. var serializationObject = {};
  56818. serializationObject.name = this.name;
  56819. serializationObject.influence = this.influence;
  56820. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  56821. if (this.hasNormals) {
  56822. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  56823. }
  56824. if (this.hasTangents) {
  56825. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  56826. }
  56827. return serializationObject;
  56828. };
  56829. // Statics
  56830. MorphTarget.Parse = function (serializationObject) {
  56831. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  56832. result.setPositions(serializationObject.positions);
  56833. if (serializationObject.normals) {
  56834. result.setNormals(serializationObject.normals);
  56835. }
  56836. if (serializationObject.tangents) {
  56837. result.setTangents(serializationObject.tangents);
  56838. }
  56839. return result;
  56840. };
  56841. MorphTarget.FromMesh = function (mesh, name, influence) {
  56842. if (!name) {
  56843. name = mesh.name;
  56844. }
  56845. var result = new MorphTarget(name, influence);
  56846. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  56847. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  56848. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  56849. }
  56850. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  56851. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  56852. }
  56853. return result;
  56854. };
  56855. return MorphTarget;
  56856. }());
  56857. BABYLON.MorphTarget = MorphTarget;
  56858. })(BABYLON || (BABYLON = {}));
  56859. //# sourceMappingURL=babylon.morphTarget.js.map
  56860. var BABYLON;
  56861. (function (BABYLON) {
  56862. var MorphTargetManager = (function () {
  56863. function MorphTargetManager(scene) {
  56864. this._targets = new Array();
  56865. this._targetObservable = new Array();
  56866. this._activeTargets = new BABYLON.SmartArray(16);
  56867. this._supportsNormals = false;
  56868. this._supportsTangents = false;
  56869. this._vertexCount = 0;
  56870. this._uniqueId = 0;
  56871. if (!scene) {
  56872. scene = BABYLON.Engine.LastCreatedScene;
  56873. }
  56874. this._scene = scene;
  56875. this._scene.morphTargetManagers.push(this);
  56876. this._uniqueId = scene.getUniqueId();
  56877. }
  56878. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  56879. get: function () {
  56880. return this._uniqueId;
  56881. },
  56882. enumerable: true,
  56883. configurable: true
  56884. });
  56885. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  56886. get: function () {
  56887. return this._vertexCount;
  56888. },
  56889. enumerable: true,
  56890. configurable: true
  56891. });
  56892. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  56893. get: function () {
  56894. return this._supportsNormals;
  56895. },
  56896. enumerable: true,
  56897. configurable: true
  56898. });
  56899. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  56900. get: function () {
  56901. return this._supportsTangents;
  56902. },
  56903. enumerable: true,
  56904. configurable: true
  56905. });
  56906. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  56907. get: function () {
  56908. return this._targets.length;
  56909. },
  56910. enumerable: true,
  56911. configurable: true
  56912. });
  56913. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  56914. get: function () {
  56915. return this._activeTargets.length;
  56916. },
  56917. enumerable: true,
  56918. configurable: true
  56919. });
  56920. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  56921. get: function () {
  56922. return this._influences;
  56923. },
  56924. enumerable: true,
  56925. configurable: true
  56926. });
  56927. MorphTargetManager.prototype.getActiveTarget = function (index) {
  56928. return this._activeTargets.data[index];
  56929. };
  56930. MorphTargetManager.prototype.getTarget = function (index) {
  56931. return this._targets[index];
  56932. };
  56933. MorphTargetManager.prototype.addTarget = function (target) {
  56934. var _this = this;
  56935. if (this._vertexCount) {
  56936. if (this._vertexCount !== target.getPositions().length / 3) {
  56937. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  56938. return;
  56939. }
  56940. }
  56941. this._targets.push(target);
  56942. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  56943. _this._syncActiveTargets(needUpdate);
  56944. }));
  56945. this._syncActiveTargets(true);
  56946. };
  56947. MorphTargetManager.prototype.removeTarget = function (target) {
  56948. var index = this._targets.indexOf(target);
  56949. if (index >= 0) {
  56950. this._targets.splice(index, 1);
  56951. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  56952. this._vertexCount = 0;
  56953. this._syncActiveTargets(true);
  56954. }
  56955. };
  56956. /**
  56957. * Serializes the current manager into a Serialization object.
  56958. * Returns the serialized object.
  56959. */
  56960. MorphTargetManager.prototype.serialize = function () {
  56961. var serializationObject = {};
  56962. serializationObject.id = this.uniqueId;
  56963. serializationObject.targets = [];
  56964. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  56965. var target = _a[_i];
  56966. serializationObject.targets.push(target.serialize());
  56967. }
  56968. return serializationObject;
  56969. };
  56970. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  56971. this._syncActiveTargets(needUpdate);
  56972. };
  56973. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  56974. this._activeTargets.reset();
  56975. var tempInfluences = [];
  56976. this._supportsNormals = true;
  56977. this._supportsTangents = true;
  56978. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  56979. var target = _a[_i];
  56980. if (target.influence > 0) {
  56981. this._activeTargets.push(target);
  56982. tempInfluences.push(target.influence);
  56983. this._supportsNormals = this._supportsNormals && target.hasNormals;
  56984. this._supportsTangents = this._supportsTangents && target.hasTangents;
  56985. if (this._vertexCount === 0) {
  56986. this._vertexCount = target.getPositions().length / 3;
  56987. }
  56988. }
  56989. }
  56990. this._influences = new Float32Array(tempInfluences);
  56991. if (needUpdate) {
  56992. // Flag meshes as dirty to resync with the active targets
  56993. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  56994. var mesh = _c[_b];
  56995. if (mesh.morphTargetManager === this) {
  56996. mesh._syncGeometryWithMorphTargetManager();
  56997. }
  56998. }
  56999. }
  57000. };
  57001. // Statics
  57002. MorphTargetManager.Parse = function (serializationObject, scene) {
  57003. var result = new MorphTargetManager(scene);
  57004. result._uniqueId = serializationObject.id;
  57005. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  57006. var targetData = _a[_i];
  57007. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  57008. }
  57009. return result;
  57010. };
  57011. return MorphTargetManager;
  57012. }());
  57013. BABYLON.MorphTargetManager = MorphTargetManager;
  57014. })(BABYLON || (BABYLON = {}));
  57015. //# sourceMappingURL=babylon.morphTargetManager.js.map
  57016. var BABYLON;
  57017. (function (BABYLON) {
  57018. /**
  57019. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  57020. * It can help converting any input color in a desired output one. This can then be used to create effects
  57021. * from sepia, black and white to sixties or futuristic rendering...
  57022. *
  57023. * The only supported format is currently 3dl.
  57024. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  57025. */
  57026. var ColorGradingTexture = (function (_super) {
  57027. __extends(ColorGradingTexture, _super);
  57028. /**
  57029. * Instantiates a ColorGradingTexture from the following parameters.
  57030. *
  57031. * @param url The location of the color gradind data (currently only supporting 3dl)
  57032. * @param scene The scene the texture will be used in
  57033. */
  57034. function ColorGradingTexture(url, scene) {
  57035. var _this = _super.call(this, scene) || this;
  57036. if (!url) {
  57037. return _this;
  57038. }
  57039. _this._textureMatrix = BABYLON.Matrix.Identity();
  57040. _this.name = url;
  57041. _this.url = url;
  57042. _this.hasAlpha = false;
  57043. _this.isCube = false;
  57044. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57045. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57046. _this.anisotropicFilteringLevel = 1;
  57047. _this._texture = _this._getFromCache(url, true);
  57048. if (!_this._texture) {
  57049. if (!scene.useDelayedTextureLoading) {
  57050. _this.loadTexture();
  57051. }
  57052. else {
  57053. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57054. }
  57055. }
  57056. return _this;
  57057. }
  57058. /**
  57059. * Returns the texture matrix used in most of the material.
  57060. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  57061. */
  57062. ColorGradingTexture.prototype.getTextureMatrix = function () {
  57063. return this._textureMatrix;
  57064. };
  57065. /**
  57066. * Occurs when the file being loaded is a .3dl LUT file.
  57067. */
  57068. ColorGradingTexture.prototype.load3dlTexture = function () {
  57069. var _this = this;
  57070. var mipLevels = 0;
  57071. var floatArrayView = null;
  57072. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57073. this._texture = texture;
  57074. var callback = function (text) {
  57075. var data;
  57076. var tempData;
  57077. var line;
  57078. var lines = text.split('\n');
  57079. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  57080. var maxColor = 0;
  57081. for (var i = 0; i < lines.length; i++) {
  57082. line = lines[i];
  57083. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  57084. continue;
  57085. if (line.indexOf('#') === 0)
  57086. continue;
  57087. var words = line.split(" ");
  57088. if (size === 0) {
  57089. // Number of space + one
  57090. size = words.length;
  57091. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  57092. tempData = new Float32Array(size * size * size * 4);
  57093. continue;
  57094. }
  57095. if (size != 0) {
  57096. var r = Math.max(parseInt(words[0]), 0);
  57097. var g = Math.max(parseInt(words[1]), 0);
  57098. var b = Math.max(parseInt(words[2]), 0);
  57099. maxColor = Math.max(r, maxColor);
  57100. maxColor = Math.max(g, maxColor);
  57101. maxColor = Math.max(b, maxColor);
  57102. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  57103. tempData[pixelStorageIndex + 0] = r;
  57104. tempData[pixelStorageIndex + 1] = g;
  57105. tempData[pixelStorageIndex + 2] = b;
  57106. tempData[pixelStorageIndex + 3] = 0;
  57107. pixelIndexSlice++;
  57108. if (pixelIndexSlice % size == 0) {
  57109. pixelIndexH++;
  57110. pixelIndexSlice = 0;
  57111. if (pixelIndexH % size == 0) {
  57112. pixelIndexW++;
  57113. pixelIndexH = 0;
  57114. }
  57115. }
  57116. }
  57117. }
  57118. for (var i = 0; i < tempData.length; i++) {
  57119. var value = tempData[i];
  57120. data[i] = (value / maxColor * 255);
  57121. }
  57122. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  57123. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  57124. };
  57125. BABYLON.Tools.LoadFile(this.url, callback);
  57126. return this._texture;
  57127. };
  57128. /**
  57129. * Starts the loading process of the texture.
  57130. */
  57131. ColorGradingTexture.prototype.loadTexture = function () {
  57132. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  57133. this.load3dlTexture();
  57134. }
  57135. };
  57136. /**
  57137. * Clones the color gradind texture.
  57138. */
  57139. ColorGradingTexture.prototype.clone = function () {
  57140. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  57141. // Base texture
  57142. newTexture.level = this.level;
  57143. return newTexture;
  57144. };
  57145. /**
  57146. * Called during delayed load for textures.
  57147. */
  57148. ColorGradingTexture.prototype.delayLoad = function () {
  57149. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57150. return;
  57151. }
  57152. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57153. this._texture = this._getFromCache(this.url, true);
  57154. if (!this._texture) {
  57155. this.loadTexture();
  57156. }
  57157. };
  57158. /**
  57159. * Binds the color grading to the shader.
  57160. * @param colorGrading The texture to bind
  57161. * @param effect The effect to bind to
  57162. */
  57163. ColorGradingTexture.Bind = function (colorGrading, effect) {
  57164. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  57165. var x = colorGrading.level; // Texture Level
  57166. var y = colorGrading.getSize().height; // Texture Size example with 8
  57167. var z = y - 1.0; // SizeMinusOne 8 - 1
  57168. var w = 1 / y; // Space of 1 slice 1 / 8
  57169. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  57170. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  57171. var slicePixelSizeV = w; // Space of 1 pixel in V direction, e.g. 1/8 // Space of 1 pixel in V direction, e.g. 1/8
  57172. var x2 = z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
  57173. var y2 = z / y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
  57174. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  57175. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  57176. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  57177. };
  57178. /**
  57179. * Prepare the list of uniforms associated with the ColorGrading effects.
  57180. * @param uniformsList The list of uniforms used in the effect
  57181. * @param samplersList The list of samplers used in the effect
  57182. */
  57183. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  57184. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  57185. samplersList.push("cameraColorGrading2DSampler");
  57186. };
  57187. /**
  57188. * Parses a color grading texture serialized by Babylon.
  57189. * @param parsedTexture The texture information being parsedTexture
  57190. * @param scene The scene to load the texture in
  57191. * @param rootUrl The root url of the data assets to load
  57192. * @return A color gradind texture
  57193. */
  57194. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57195. var texture = null;
  57196. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  57197. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  57198. texture.name = parsedTexture.name;
  57199. texture.level = parsedTexture.level;
  57200. }
  57201. return texture;
  57202. };
  57203. /**
  57204. * Serializes the LUT texture to json format.
  57205. */
  57206. ColorGradingTexture.prototype.serialize = function () {
  57207. if (!this.name) {
  57208. return null;
  57209. }
  57210. var serializationObject = {};
  57211. serializationObject.name = this.name;
  57212. serializationObject.level = this.level;
  57213. serializationObject.customType = "BABYLON.ColorGradingTexture";
  57214. return serializationObject;
  57215. };
  57216. return ColorGradingTexture;
  57217. }(BABYLON.BaseTexture));
  57218. /**
  57219. * Empty line regex stored for GC.
  57220. */
  57221. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  57222. BABYLON.ColorGradingTexture = ColorGradingTexture;
  57223. })(BABYLON || (BABYLON = {}));
  57224. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  57225. var BABYLON;
  57226. (function (BABYLON) {
  57227. /**
  57228. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  57229. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  57230. * 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;
  57231. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  57232. */
  57233. var ColorCurves = (function () {
  57234. function ColorCurves() {
  57235. this._dirty = true;
  57236. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  57237. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  57238. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57239. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  57240. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  57241. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  57242. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  57243. this._globalHue = 30;
  57244. this._globalDensity = 0;
  57245. this._globalSaturation = 0;
  57246. this._globalExposure = 0;
  57247. this._highlightsHue = 30;
  57248. this._highlightsDensity = 0;
  57249. this._highlightsSaturation = 0;
  57250. this._highlightsExposure = 0;
  57251. this._midtonesHue = 30;
  57252. this._midtonesDensity = 0;
  57253. this._midtonesSaturation = 0;
  57254. this._midtonesExposure = 0;
  57255. this._shadowsHue = 30;
  57256. this._shadowsDensity = 0;
  57257. this._shadowsSaturation = 0;
  57258. this._shadowsExposure = 0;
  57259. }
  57260. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  57261. /**
  57262. * Gets the global Hue value.
  57263. * 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).
  57264. */
  57265. get: function () {
  57266. return this._globalHue;
  57267. },
  57268. /**
  57269. * Sets the global Hue value.
  57270. * 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).
  57271. */
  57272. set: function (value) {
  57273. this._globalHue = value;
  57274. this._dirty = true;
  57275. },
  57276. enumerable: true,
  57277. configurable: true
  57278. });
  57279. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  57280. /**
  57281. * Gets the global Density value.
  57282. * 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.
  57283. * Values less than zero provide a filter of opposite hue.
  57284. */
  57285. get: function () {
  57286. return this._globalDensity;
  57287. },
  57288. /**
  57289. * Sets the global Density value.
  57290. * 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.
  57291. * Values less than zero provide a filter of opposite hue.
  57292. */
  57293. set: function (value) {
  57294. this._globalDensity = value;
  57295. this._dirty = true;
  57296. },
  57297. enumerable: true,
  57298. configurable: true
  57299. });
  57300. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  57301. /**
  57302. * Gets the global Saturation value.
  57303. * 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.
  57304. */
  57305. get: function () {
  57306. return this._globalSaturation;
  57307. },
  57308. /**
  57309. * Sets the global Saturation value.
  57310. * 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.
  57311. */
  57312. set: function (value) {
  57313. this._globalSaturation = value;
  57314. this._dirty = true;
  57315. },
  57316. enumerable: true,
  57317. configurable: true
  57318. });
  57319. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  57320. /**
  57321. * Gets the highlights Hue value.
  57322. * 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).
  57323. */
  57324. get: function () {
  57325. return this._highlightsHue;
  57326. },
  57327. /**
  57328. * Sets the highlights Hue value.
  57329. * 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).
  57330. */
  57331. set: function (value) {
  57332. this._highlightsHue = value;
  57333. this._dirty = true;
  57334. },
  57335. enumerable: true,
  57336. configurable: true
  57337. });
  57338. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  57339. /**
  57340. * Gets the highlights Density value.
  57341. * 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.
  57342. * Values less than zero provide a filter of opposite hue.
  57343. */
  57344. get: function () {
  57345. return this._highlightsDensity;
  57346. },
  57347. /**
  57348. * Sets the highlights Density value.
  57349. * 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.
  57350. * Values less than zero provide a filter of opposite hue.
  57351. */
  57352. set: function (value) {
  57353. this._highlightsDensity = value;
  57354. this._dirty = true;
  57355. },
  57356. enumerable: true,
  57357. configurable: true
  57358. });
  57359. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  57360. /**
  57361. * Gets the highlights Saturation value.
  57362. * 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.
  57363. */
  57364. get: function () {
  57365. return this._highlightsSaturation;
  57366. },
  57367. /**
  57368. * Sets the highlights Saturation value.
  57369. * 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.
  57370. */
  57371. set: function (value) {
  57372. this._highlightsSaturation = value;
  57373. this._dirty = true;
  57374. },
  57375. enumerable: true,
  57376. configurable: true
  57377. });
  57378. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  57379. /**
  57380. * Gets the highlights Exposure value.
  57381. * 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.
  57382. */
  57383. get: function () {
  57384. return this._highlightsExposure;
  57385. },
  57386. /**
  57387. * Sets the highlights Exposure value.
  57388. * 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.
  57389. */
  57390. set: function (value) {
  57391. this._highlightsExposure = value;
  57392. this._dirty = true;
  57393. },
  57394. enumerable: true,
  57395. configurable: true
  57396. });
  57397. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  57398. /**
  57399. * Gets the midtones Hue value.
  57400. * 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).
  57401. */
  57402. get: function () {
  57403. return this._midtonesHue;
  57404. },
  57405. /**
  57406. * Sets the midtones Hue value.
  57407. * 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).
  57408. */
  57409. set: function (value) {
  57410. this._midtonesHue = value;
  57411. this._dirty = true;
  57412. },
  57413. enumerable: true,
  57414. configurable: true
  57415. });
  57416. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  57417. /**
  57418. * Gets the midtones Density value.
  57419. * 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.
  57420. * Values less than zero provide a filter of opposite hue.
  57421. */
  57422. get: function () {
  57423. return this._midtonesDensity;
  57424. },
  57425. /**
  57426. * Sets the midtones Density value.
  57427. * 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.
  57428. * Values less than zero provide a filter of opposite hue.
  57429. */
  57430. set: function (value) {
  57431. this._midtonesDensity = value;
  57432. this._dirty = true;
  57433. },
  57434. enumerable: true,
  57435. configurable: true
  57436. });
  57437. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  57438. /**
  57439. * Gets the midtones Saturation value.
  57440. * 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.
  57441. */
  57442. get: function () {
  57443. return this._midtonesSaturation;
  57444. },
  57445. /**
  57446. * Sets the midtones Saturation value.
  57447. * 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.
  57448. */
  57449. set: function (value) {
  57450. this._midtonesSaturation = value;
  57451. this._dirty = true;
  57452. },
  57453. enumerable: true,
  57454. configurable: true
  57455. });
  57456. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  57457. /**
  57458. * Gets the midtones Exposure value.
  57459. * 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.
  57460. */
  57461. get: function () {
  57462. return this._midtonesExposure;
  57463. },
  57464. /**
  57465. * Sets the midtones Exposure value.
  57466. * 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.
  57467. */
  57468. set: function (value) {
  57469. this._midtonesExposure = value;
  57470. this._dirty = true;
  57471. },
  57472. enumerable: true,
  57473. configurable: true
  57474. });
  57475. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  57476. /**
  57477. * Gets the shadows Hue value.
  57478. * 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).
  57479. */
  57480. get: function () {
  57481. return this._shadowsHue;
  57482. },
  57483. /**
  57484. * Sets the shadows Hue value.
  57485. * 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).
  57486. */
  57487. set: function (value) {
  57488. this._shadowsHue = value;
  57489. this._dirty = true;
  57490. },
  57491. enumerable: true,
  57492. configurable: true
  57493. });
  57494. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  57495. /**
  57496. * Gets the shadows Density value.
  57497. * 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.
  57498. * Values less than zero provide a filter of opposite hue.
  57499. */
  57500. get: function () {
  57501. return this._shadowsDensity;
  57502. },
  57503. /**
  57504. * Sets the shadows Density value.
  57505. * 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.
  57506. * Values less than zero provide a filter of opposite hue.
  57507. */
  57508. set: function (value) {
  57509. this._shadowsDensity = value;
  57510. this._dirty = true;
  57511. },
  57512. enumerable: true,
  57513. configurable: true
  57514. });
  57515. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  57516. /**
  57517. * Gets the shadows Saturation value.
  57518. * 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.
  57519. */
  57520. get: function () {
  57521. return this._shadowsSaturation;
  57522. },
  57523. /**
  57524. * Sets the shadows Saturation value.
  57525. * 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.
  57526. */
  57527. set: function (value) {
  57528. this._shadowsSaturation = value;
  57529. this._dirty = true;
  57530. },
  57531. enumerable: true,
  57532. configurable: true
  57533. });
  57534. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  57535. /**
  57536. * Gets the shadows Exposure value.
  57537. * 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.
  57538. */
  57539. get: function () {
  57540. return this._shadowsExposure;
  57541. },
  57542. /**
  57543. * Sets the shadows Exposure value.
  57544. * 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.
  57545. */
  57546. set: function (value) {
  57547. this._shadowsExposure = value;
  57548. this._dirty = true;
  57549. },
  57550. enumerable: true,
  57551. configurable: true
  57552. });
  57553. /**
  57554. * Binds the color curves to the shader.
  57555. * @param colorCurves The color curve to bind
  57556. * @param effect The effect to bind to
  57557. */
  57558. ColorCurves.Bind = function (colorCurves, effect) {
  57559. if (colorCurves._dirty) {
  57560. colorCurves._dirty = false;
  57561. // Fill in global info.
  57562. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  57563. // Compute highlights info.
  57564. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  57565. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  57566. // Compute midtones info.
  57567. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  57568. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  57569. // Compute shadows info.
  57570. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  57571. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  57572. // Compute deltas (neutral is midtones).
  57573. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  57574. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  57575. }
  57576. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  57577. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  57578. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  57579. };
  57580. /**
  57581. * Prepare the list of uniforms associated with the ColorCurves effects.
  57582. * @param uniformsList The list of uniforms used in the effect
  57583. */
  57584. ColorCurves.PrepareUniforms = function (uniformsList) {
  57585. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  57586. };
  57587. /**
  57588. * Returns color grading data based on a hue, density, saturation and exposure value.
  57589. * @param filterHue The hue of the color filter.
  57590. * @param filterDensity The density of the color filter.
  57591. * @param saturation The saturation.
  57592. * @param exposure The exposure.
  57593. * @param result The result data container.
  57594. */
  57595. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  57596. if (hue == null) {
  57597. return;
  57598. }
  57599. hue = ColorCurves.clamp(hue, 0, 360);
  57600. density = ColorCurves.clamp(density, -100, 100);
  57601. saturation = ColorCurves.clamp(saturation, -100, 100);
  57602. exposure = ColorCurves.clamp(exposure, -100, 100);
  57603. // Remap the slider/config filter density with non-linear mapping and also scale by half
  57604. // so that the maximum filter density is only 50% control. This provides fine control
  57605. // for small values and reasonable range.
  57606. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  57607. density *= 0.5;
  57608. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  57609. if (density < 0) {
  57610. density *= -1;
  57611. hue = (hue + 180) % 360;
  57612. }
  57613. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  57614. result.scaleToRef(2, result);
  57615. result.a = 1 + 0.01 * saturation;
  57616. };
  57617. /**
  57618. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  57619. * @param value The input slider value in range [-100,100].
  57620. * @returns Adjusted value.
  57621. */
  57622. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  57623. value /= 100;
  57624. var x = Math.abs(value);
  57625. x = Math.pow(x, 2);
  57626. if (value < 0) {
  57627. x *= -1;
  57628. }
  57629. x *= 100;
  57630. return x;
  57631. };
  57632. /**
  57633. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  57634. * @param hue The hue (H) input.
  57635. * @param saturation The saturation (S) input.
  57636. * @param brightness The brightness (B) input.
  57637. * @result An RGBA color represented as Vector4.
  57638. */
  57639. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  57640. var h = ColorCurves.clamp(hue, 0, 360);
  57641. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  57642. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  57643. if (s === 0) {
  57644. result.r = v;
  57645. result.g = v;
  57646. result.b = v;
  57647. }
  57648. else {
  57649. // sector 0 to 5
  57650. h /= 60;
  57651. var i = Math.floor(h);
  57652. // fractional part of h
  57653. var f = h - i;
  57654. var p = v * (1 - s);
  57655. var q = v * (1 - s * f);
  57656. var t = v * (1 - s * (1 - f));
  57657. switch (i) {
  57658. case 0:
  57659. result.r = v;
  57660. result.g = t;
  57661. result.b = p;
  57662. break;
  57663. case 1:
  57664. result.r = q;
  57665. result.g = v;
  57666. result.b = p;
  57667. break;
  57668. case 2:
  57669. result.r = p;
  57670. result.g = v;
  57671. result.b = t;
  57672. break;
  57673. case 3:
  57674. result.r = p;
  57675. result.g = q;
  57676. result.b = v;
  57677. break;
  57678. case 4:
  57679. result.r = t;
  57680. result.g = p;
  57681. result.b = v;
  57682. break;
  57683. default:
  57684. result.r = v;
  57685. result.g = p;
  57686. result.b = q;
  57687. break;
  57688. }
  57689. }
  57690. result.a = 1;
  57691. };
  57692. /**
  57693. * Returns a value clamped between min and max
  57694. * @param value The value to clamp
  57695. * @param min The minimum of value
  57696. * @param max The maximum of value
  57697. * @returns The clamped value.
  57698. */
  57699. ColorCurves.clamp = function (value, min, max) {
  57700. return Math.min(Math.max(value, min), max);
  57701. };
  57702. /**
  57703. * Clones the current color curve instance.
  57704. * @return The cloned curves
  57705. */
  57706. ColorCurves.prototype.clone = function () {
  57707. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  57708. };
  57709. /**
  57710. * Serializes the current color curve instance to a json representation.
  57711. * @return a JSON representation
  57712. */
  57713. ColorCurves.prototype.serialize = function () {
  57714. return BABYLON.SerializationHelper.Serialize(this);
  57715. };
  57716. /**
  57717. * Parses the color curve from a json representation.
  57718. * @param source the JSON source to parse
  57719. * @return The parsed curves
  57720. */
  57721. ColorCurves.Parse = function (source) {
  57722. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  57723. };
  57724. return ColorCurves;
  57725. }());
  57726. __decorate([
  57727. BABYLON.serialize()
  57728. ], ColorCurves.prototype, "_globalHue", void 0);
  57729. __decorate([
  57730. BABYLON.serialize()
  57731. ], ColorCurves.prototype, "_globalDensity", void 0);
  57732. __decorate([
  57733. BABYLON.serialize()
  57734. ], ColorCurves.prototype, "_globalSaturation", void 0);
  57735. __decorate([
  57736. BABYLON.serialize()
  57737. ], ColorCurves.prototype, "_globalExposure", void 0);
  57738. __decorate([
  57739. BABYLON.serialize()
  57740. ], ColorCurves.prototype, "_highlightsHue", void 0);
  57741. __decorate([
  57742. BABYLON.serialize()
  57743. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  57744. __decorate([
  57745. BABYLON.serialize()
  57746. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  57747. __decorate([
  57748. BABYLON.serialize()
  57749. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  57750. __decorate([
  57751. BABYLON.serialize()
  57752. ], ColorCurves.prototype, "_midtonesHue", void 0);
  57753. __decorate([
  57754. BABYLON.serialize()
  57755. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  57756. __decorate([
  57757. BABYLON.serialize()
  57758. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  57759. __decorate([
  57760. BABYLON.serialize()
  57761. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  57762. BABYLON.ColorCurves = ColorCurves;
  57763. })(BABYLON || (BABYLON = {}));
  57764. //# sourceMappingURL=babylon.colorCurves.js.map
  57765. var BABYLON;
  57766. (function (BABYLON) {
  57767. var Octree = (function () {
  57768. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  57769. if (maxDepth === void 0) { maxDepth = 2; }
  57770. this.maxDepth = maxDepth;
  57771. this.dynamicContent = new Array();
  57772. this._maxBlockCapacity = maxBlockCapacity || 64;
  57773. this._selectionContent = new BABYLON.SmartArray(1024);
  57774. this._creationFunc = creationFunc;
  57775. }
  57776. // Methods
  57777. Octree.prototype.update = function (worldMin, worldMax, entries) {
  57778. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  57779. };
  57780. Octree.prototype.addMesh = function (entry) {
  57781. for (var index = 0; index < this.blocks.length; index++) {
  57782. var block = this.blocks[index];
  57783. block.addEntry(entry);
  57784. }
  57785. };
  57786. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  57787. this._selectionContent.reset();
  57788. for (var index = 0; index < this.blocks.length; index++) {
  57789. var block = this.blocks[index];
  57790. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  57791. }
  57792. if (allowDuplicate) {
  57793. this._selectionContent.concat(this.dynamicContent);
  57794. }
  57795. else {
  57796. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  57797. }
  57798. return this._selectionContent;
  57799. };
  57800. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  57801. this._selectionContent.reset();
  57802. for (var index = 0; index < this.blocks.length; index++) {
  57803. var block = this.blocks[index];
  57804. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  57805. }
  57806. if (allowDuplicate) {
  57807. this._selectionContent.concat(this.dynamicContent);
  57808. }
  57809. else {
  57810. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  57811. }
  57812. return this._selectionContent;
  57813. };
  57814. Octree.prototype.intersectsRay = function (ray) {
  57815. this._selectionContent.reset();
  57816. for (var index = 0; index < this.blocks.length; index++) {
  57817. var block = this.blocks[index];
  57818. block.intersectsRay(ray, this._selectionContent);
  57819. }
  57820. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  57821. return this._selectionContent;
  57822. };
  57823. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  57824. target.blocks = new Array();
  57825. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  57826. // Segmenting space
  57827. for (var x = 0; x < 2; x++) {
  57828. for (var y = 0; y < 2; y++) {
  57829. for (var z = 0; z < 2; z++) {
  57830. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  57831. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  57832. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  57833. block.addEntries(entries);
  57834. target.blocks.push(block);
  57835. }
  57836. }
  57837. }
  57838. };
  57839. return Octree;
  57840. }());
  57841. Octree.CreationFuncForMeshes = function (entry, block) {
  57842. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  57843. block.entries.push(entry);
  57844. }
  57845. };
  57846. Octree.CreationFuncForSubMeshes = function (entry, block) {
  57847. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  57848. block.entries.push(entry);
  57849. }
  57850. };
  57851. BABYLON.Octree = Octree;
  57852. })(BABYLON || (BABYLON = {}));
  57853. //# sourceMappingURL=babylon.octree.js.map
  57854. var BABYLON;
  57855. (function (BABYLON) {
  57856. var OctreeBlock = (function () {
  57857. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  57858. this.entries = new Array();
  57859. this._boundingVectors = new Array();
  57860. this._capacity = capacity;
  57861. this._depth = depth;
  57862. this._maxDepth = maxDepth;
  57863. this._creationFunc = creationFunc;
  57864. this._minPoint = minPoint;
  57865. this._maxPoint = maxPoint;
  57866. this._boundingVectors.push(minPoint.clone());
  57867. this._boundingVectors.push(maxPoint.clone());
  57868. this._boundingVectors.push(minPoint.clone());
  57869. this._boundingVectors[2].x = maxPoint.x;
  57870. this._boundingVectors.push(minPoint.clone());
  57871. this._boundingVectors[3].y = maxPoint.y;
  57872. this._boundingVectors.push(minPoint.clone());
  57873. this._boundingVectors[4].z = maxPoint.z;
  57874. this._boundingVectors.push(maxPoint.clone());
  57875. this._boundingVectors[5].z = minPoint.z;
  57876. this._boundingVectors.push(maxPoint.clone());
  57877. this._boundingVectors[6].x = minPoint.x;
  57878. this._boundingVectors.push(maxPoint.clone());
  57879. this._boundingVectors[7].y = minPoint.y;
  57880. }
  57881. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  57882. // Property
  57883. get: function () {
  57884. return this._capacity;
  57885. },
  57886. enumerable: true,
  57887. configurable: true
  57888. });
  57889. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  57890. get: function () {
  57891. return this._minPoint;
  57892. },
  57893. enumerable: true,
  57894. configurable: true
  57895. });
  57896. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  57897. get: function () {
  57898. return this._maxPoint;
  57899. },
  57900. enumerable: true,
  57901. configurable: true
  57902. });
  57903. // Methods
  57904. OctreeBlock.prototype.addEntry = function (entry) {
  57905. if (this.blocks) {
  57906. for (var index = 0; index < this.blocks.length; index++) {
  57907. var block = this.blocks[index];
  57908. block.addEntry(entry);
  57909. }
  57910. return;
  57911. }
  57912. this._creationFunc(entry, this);
  57913. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  57914. this.createInnerBlocks();
  57915. }
  57916. };
  57917. OctreeBlock.prototype.addEntries = function (entries) {
  57918. for (var index = 0; index < entries.length; index++) {
  57919. var mesh = entries[index];
  57920. this.addEntry(mesh);
  57921. }
  57922. };
  57923. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  57924. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  57925. if (this.blocks) {
  57926. for (var index = 0; index < this.blocks.length; index++) {
  57927. var block = this.blocks[index];
  57928. block.select(frustumPlanes, selection, allowDuplicate);
  57929. }
  57930. return;
  57931. }
  57932. if (allowDuplicate) {
  57933. selection.concat(this.entries);
  57934. }
  57935. else {
  57936. selection.concatWithNoDuplicate(this.entries);
  57937. }
  57938. }
  57939. };
  57940. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  57941. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  57942. if (this.blocks) {
  57943. for (var index = 0; index < this.blocks.length; index++) {
  57944. var block = this.blocks[index];
  57945. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  57946. }
  57947. return;
  57948. }
  57949. if (allowDuplicate) {
  57950. selection.concat(this.entries);
  57951. }
  57952. else {
  57953. selection.concatWithNoDuplicate(this.entries);
  57954. }
  57955. }
  57956. };
  57957. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  57958. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  57959. if (this.blocks) {
  57960. for (var index = 0; index < this.blocks.length; index++) {
  57961. var block = this.blocks[index];
  57962. block.intersectsRay(ray, selection);
  57963. }
  57964. return;
  57965. }
  57966. selection.concatWithNoDuplicate(this.entries);
  57967. }
  57968. };
  57969. OctreeBlock.prototype.createInnerBlocks = function () {
  57970. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  57971. };
  57972. return OctreeBlock;
  57973. }());
  57974. BABYLON.OctreeBlock = OctreeBlock;
  57975. })(BABYLON || (BABYLON = {}));
  57976. //# sourceMappingURL=babylon.octreeBlock.js.map
  57977. var BABYLON;
  57978. (function (BABYLON) {
  57979. var SIMDVector3 = (function () {
  57980. function SIMDVector3() {
  57981. }
  57982. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  57983. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  57984. };
  57985. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  57986. var m = transformation.m;
  57987. var m0 = SIMD.Float32x4.load(m, 0);
  57988. var m1 = SIMD.Float32x4.load(m, 4);
  57989. var m2 = SIMD.Float32x4.load(m, 8);
  57990. var m3 = SIMD.Float32x4.load(m, 12);
  57991. 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));
  57992. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  57993. result.x = SIMD.Float32x4.extractLane(r, 0);
  57994. result.y = SIMD.Float32x4.extractLane(r, 1);
  57995. result.z = SIMD.Float32x4.extractLane(r, 2);
  57996. };
  57997. return SIMDVector3;
  57998. }());
  57999. var SIMDMatrix = (function () {
  58000. function SIMDMatrix() {
  58001. }
  58002. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  58003. var tm = this.m;
  58004. var om = other.m;
  58005. var m0 = SIMD.Float32x4.load(om, 0);
  58006. var m1 = SIMD.Float32x4.load(om, 4);
  58007. var m2 = SIMD.Float32x4.load(om, 8);
  58008. var m3 = SIMD.Float32x4.load(om, 12);
  58009. for (var i = 0; i < 16; i += 4) {
  58010. 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)))));
  58011. }
  58012. return this;
  58013. };
  58014. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  58015. var src = this.m;
  58016. var dest = other.m;
  58017. // Load the 4 rows
  58018. var src0 = SIMD.Float32x4.load(src, 0);
  58019. var src1 = SIMD.Float32x4.load(src, 4);
  58020. var src2 = SIMD.Float32x4.load(src, 8);
  58021. var src3 = SIMD.Float32x4.load(src, 12);
  58022. // Transpose the source matrix. Sort of. Not a true transpose operation
  58023. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  58024. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  58025. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  58026. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  58027. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  58028. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  58029. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  58030. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  58031. // This is a true transposition, but it will lead to an incorrect result
  58032. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  58033. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  58034. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  58035. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  58036. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  58037. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  58038. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  58039. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  58040. // ----
  58041. tmp1 = SIMD.Float32x4.mul(row2, row3);
  58042. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58043. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  58044. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  58045. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58046. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  58047. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  58048. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  58049. // ----
  58050. tmp1 = SIMD.Float32x4.mul(row1, row2);
  58051. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58052. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  58053. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  58054. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58055. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  58056. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  58057. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  58058. // ----
  58059. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  58060. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58061. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  58062. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  58063. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  58064. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58065. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  58066. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  58067. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  58068. // ----
  58069. tmp1 = SIMD.Float32x4.mul(row0, row1);
  58070. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58071. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  58072. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  58073. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58074. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  58075. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  58076. // ----
  58077. tmp1 = SIMD.Float32x4.mul(row0, row3);
  58078. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58079. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  58080. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  58081. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58082. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  58083. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  58084. // ----
  58085. tmp1 = SIMD.Float32x4.mul(row0, row2);
  58086. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  58087. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  58088. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  58089. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  58090. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  58091. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  58092. // Compute determinant
  58093. var det = SIMD.Float32x4.mul(row0, minor0);
  58094. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  58095. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  58096. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  58097. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  58098. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  58099. // These shuffles aren't necessary if the faulty transposition is done
  58100. // up at the top of this function.
  58101. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  58102. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  58103. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  58104. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  58105. // Compute final values by multiplying with 1/det
  58106. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  58107. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  58108. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  58109. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  58110. return this;
  58111. };
  58112. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  58113. var out = result.m;
  58114. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  58115. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  58116. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  58117. // cc.kmVec3Subtract(f, pCenter, pEye);
  58118. var f = SIMD.Float32x4.sub(center, eye);
  58119. // cc.kmVec3Normalize(f, f);
  58120. var tmp = SIMD.Float32x4.mul(f, f);
  58121. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  58122. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  58123. // cc.kmVec3Assign(up, pUp);
  58124. // cc.kmVec3Normalize(up, up);
  58125. tmp = SIMD.Float32x4.mul(up, up);
  58126. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  58127. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  58128. // cc.kmVec3Cross(s, f, up);
  58129. 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)));
  58130. // cc.kmVec3Normalize(s, s);
  58131. tmp = SIMD.Float32x4.mul(s, s);
  58132. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  58133. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  58134. // cc.kmVec3Cross(u, s, f);
  58135. 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)));
  58136. // cc.kmVec3Normalize(s, s);
  58137. tmp = SIMD.Float32x4.mul(s, s);
  58138. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  58139. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  58140. var zero = SIMD.Float32x4.splat(0.0);
  58141. s = SIMD.Float32x4.neg(s);
  58142. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  58143. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  58144. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  58145. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  58146. 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);
  58147. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  58148. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  58149. 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)))));
  58150. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  58151. 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)))));
  58152. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  58153. 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)))));
  58154. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  58155. 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)))));
  58156. };
  58157. return SIMDMatrix;
  58158. }());
  58159. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  58160. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  58161. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  58162. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  58163. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  58164. var SIMDHelper = (function () {
  58165. function SIMDHelper() {
  58166. }
  58167. Object.defineProperty(SIMDHelper, "IsEnabled", {
  58168. get: function () {
  58169. return SIMDHelper._isEnabled;
  58170. },
  58171. enumerable: true,
  58172. configurable: true
  58173. });
  58174. SIMDHelper.DisableSIMD = function () {
  58175. // Replace functions
  58176. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  58177. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  58178. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  58179. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  58180. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  58181. SIMDHelper._isEnabled = false;
  58182. };
  58183. SIMDHelper.EnableSIMD = function () {
  58184. if (self.SIMD === undefined) {
  58185. return;
  58186. }
  58187. // check if polyfills needed
  58188. if (!self.Math.fround) {
  58189. self.Math.fround = (function (array) { return function (x) {
  58190. return array[0] = x, array[0];
  58191. }; })(new Float32Array(1));
  58192. }
  58193. if (!self.Math.imul) {
  58194. self.Math.imul = function (a, b) {
  58195. var ah = (a >>> 16) & 0xffff;
  58196. var al = a & 0xffff;
  58197. var bh = (b >>> 16) & 0xffff;
  58198. var bl = b & 0xffff;
  58199. // the shift by 0 fixes the sign on the high part
  58200. // the final |0 converts the unsigned value into a signed value
  58201. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  58202. };
  58203. }
  58204. // Replace functions
  58205. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  58206. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  58207. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  58208. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  58209. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  58210. SIMDHelper._isEnabled = true;
  58211. };
  58212. return SIMDHelper;
  58213. }());
  58214. SIMDHelper._isEnabled = false;
  58215. BABYLON.SIMDHelper = SIMDHelper;
  58216. })(BABYLON || (BABYLON = {}));
  58217. //# sourceMappingURL=babylon.math.SIMD.js.map
  58218. var BABYLON;
  58219. (function (BABYLON) {
  58220. var VRDistortionCorrectionPostProcess = (function (_super) {
  58221. __extends(VRDistortionCorrectionPostProcess, _super);
  58222. //ANY
  58223. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  58224. var _this = _super.call(this, name, "vrDistortionCorrection", [
  58225. 'LensCenter',
  58226. 'Scale',
  58227. 'ScaleIn',
  58228. 'HmdWarpParam'
  58229. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  58230. _this._isRightEye = isRightEye;
  58231. _this._distortionFactors = vrMetrics.distortionK;
  58232. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  58233. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  58234. _this.onSizeChangedObservable.add(function () {
  58235. _this.aspectRatio = _this.width * .5 / _this.height;
  58236. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  58237. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  58238. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  58239. });
  58240. _this.onApplyObservable.add(function (effect) {
  58241. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  58242. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  58243. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  58244. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  58245. });
  58246. return _this;
  58247. }
  58248. return VRDistortionCorrectionPostProcess;
  58249. }(BABYLON.PostProcess));
  58250. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  58251. })(BABYLON || (BABYLON = {}));
  58252. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  58253. var BABYLON;
  58254. (function (BABYLON) {
  58255. var AnaglyphPostProcess = (function (_super) {
  58256. __extends(AnaglyphPostProcess, _super);
  58257. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  58258. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  58259. _this._passedProcess = rigCameras[0]._rigPostProcess;
  58260. _this.onApplyObservable.add(function (effect) {
  58261. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  58262. });
  58263. return _this;
  58264. }
  58265. return AnaglyphPostProcess;
  58266. }(BABYLON.PostProcess));
  58267. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  58268. })(BABYLON || (BABYLON = {}));
  58269. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  58270. var BABYLON;
  58271. (function (BABYLON) {
  58272. var StereoscopicInterlacePostProcess = (function (_super) {
  58273. __extends(StereoscopicInterlacePostProcess, _super);
  58274. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  58275. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  58276. _this._passedProcess = rigCameras[0]._rigPostProcess;
  58277. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  58278. _this.onSizeChangedObservable.add(function () {
  58279. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  58280. });
  58281. _this.onApplyObservable.add(function (effect) {
  58282. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  58283. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  58284. });
  58285. return _this;
  58286. }
  58287. return StereoscopicInterlacePostProcess;
  58288. }(BABYLON.PostProcess));
  58289. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  58290. })(BABYLON || (BABYLON = {}));
  58291. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  58292. var BABYLON;
  58293. (function (BABYLON) {
  58294. var FreeCameraDeviceOrientationInput = (function () {
  58295. function FreeCameraDeviceOrientationInput() {
  58296. var _this = this;
  58297. this._screenOrientationAngle = 0;
  58298. this._screenQuaternion = new BABYLON.Quaternion();
  58299. this._alpha = 0;
  58300. this._beta = 0;
  58301. this._gamma = 0;
  58302. this._orientationChanged = function () {
  58303. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  58304. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  58305. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  58306. };
  58307. this._deviceOrientation = function (evt) {
  58308. _this._alpha = evt.alpha;
  58309. _this._beta = evt.beta;
  58310. _this._gamma = evt.gamma;
  58311. };
  58312. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  58313. this._orientationChanged();
  58314. }
  58315. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  58316. get: function () {
  58317. return this._camera;
  58318. },
  58319. set: function (camera) {
  58320. this._camera = camera;
  58321. if (!this._camera.rotationQuaternion)
  58322. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  58323. },
  58324. enumerable: true,
  58325. configurable: true
  58326. });
  58327. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  58328. window.addEventListener("orientationchange", this._orientationChanged);
  58329. window.addEventListener("deviceorientation", this._deviceOrientation);
  58330. //In certain cases, the attach control is called AFTER orientation was changed,
  58331. //So this is needed.
  58332. this._orientationChanged();
  58333. };
  58334. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  58335. window.removeEventListener("orientationchange", this._orientationChanged);
  58336. window.removeEventListener("deviceorientation", this._deviceOrientation);
  58337. };
  58338. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  58339. //if no device orientation provided, don't update the rotation.
  58340. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  58341. if (!this._alpha)
  58342. return;
  58343. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  58344. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  58345. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  58346. //Mirror on XY Plane
  58347. this._camera.rotationQuaternion.z *= -1;
  58348. this._camera.rotationQuaternion.w *= -1;
  58349. };
  58350. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  58351. return "FreeCameraDeviceOrientationInput";
  58352. };
  58353. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  58354. return "deviceOrientation";
  58355. };
  58356. return FreeCameraDeviceOrientationInput;
  58357. }());
  58358. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  58359. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  58360. })(BABYLON || (BABYLON = {}));
  58361. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  58362. var BABYLON;
  58363. (function (BABYLON) {
  58364. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  58365. function ArcRotateCameraVRDeviceOrientationInput() {
  58366. this.alphaCorrection = 1;
  58367. this.betaCorrection = 1;
  58368. this.gammaCorrection = 1;
  58369. this._alpha = 0;
  58370. this._beta = 0;
  58371. this._gamma = 0;
  58372. this._dirty = false;
  58373. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  58374. }
  58375. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  58376. this.camera.attachControl(element, noPreventDefault);
  58377. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  58378. };
  58379. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  58380. var camera = this.camera;
  58381. this._alpha = +evt.alpha | 0;
  58382. this._beta = +evt.beta | 0;
  58383. this._gamma = +evt.gamma | 0;
  58384. this._dirty = true;
  58385. };
  58386. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  58387. if (this._dirty) {
  58388. this._dirty = false;
  58389. if (this._gamma < 0) {
  58390. this._gamma = 180 + this._gamma;
  58391. }
  58392. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  58393. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  58394. }
  58395. };
  58396. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  58397. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  58398. };
  58399. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  58400. return "ArcRotateCameraVRDeviceOrientationInput";
  58401. };
  58402. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  58403. return "VRDeviceOrientation";
  58404. };
  58405. return ArcRotateCameraVRDeviceOrientationInput;
  58406. }());
  58407. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  58408. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  58409. })(BABYLON || (BABYLON = {}));
  58410. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  58411. var BABYLON;
  58412. (function (BABYLON) {
  58413. var VRCameraMetrics = (function () {
  58414. function VRCameraMetrics() {
  58415. this.compensateDistortion = true;
  58416. }
  58417. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  58418. get: function () {
  58419. return this.hResolution / (2 * this.vResolution);
  58420. },
  58421. enumerable: true,
  58422. configurable: true
  58423. });
  58424. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  58425. get: function () {
  58426. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  58427. },
  58428. enumerable: true,
  58429. configurable: true
  58430. });
  58431. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  58432. get: function () {
  58433. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  58434. var h = (4 * meters) / this.hScreenSize;
  58435. return BABYLON.Matrix.Translation(h, 0, 0);
  58436. },
  58437. enumerable: true,
  58438. configurable: true
  58439. });
  58440. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  58441. get: function () {
  58442. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  58443. var h = (4 * meters) / this.hScreenSize;
  58444. return BABYLON.Matrix.Translation(-h, 0, 0);
  58445. },
  58446. enumerable: true,
  58447. configurable: true
  58448. });
  58449. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  58450. get: function () {
  58451. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  58452. },
  58453. enumerable: true,
  58454. configurable: true
  58455. });
  58456. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  58457. get: function () {
  58458. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  58459. },
  58460. enumerable: true,
  58461. configurable: true
  58462. });
  58463. VRCameraMetrics.GetDefault = function () {
  58464. var result = new VRCameraMetrics();
  58465. result.hResolution = 1280;
  58466. result.vResolution = 800;
  58467. result.hScreenSize = 0.149759993;
  58468. result.vScreenSize = 0.0935999975;
  58469. result.vScreenCenter = 0.0467999987;
  58470. result.eyeToScreenDistance = 0.0410000011;
  58471. result.lensSeparationDistance = 0.0635000020;
  58472. result.interpupillaryDistance = 0.0640000030;
  58473. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  58474. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  58475. result.postProcessScaleFactor = 1.714605507808412;
  58476. result.lensCenterOffset = 0.151976421;
  58477. return result;
  58478. };
  58479. return VRCameraMetrics;
  58480. }());
  58481. BABYLON.VRCameraMetrics = VRCameraMetrics;
  58482. })(BABYLON || (BABYLON = {}));
  58483. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  58484. var BABYLON;
  58485. (function (BABYLON) {
  58486. var WebVRFreeCamera = (function (_super) {
  58487. __extends(WebVRFreeCamera, _super);
  58488. function WebVRFreeCamera(name, position, scene, webVROptions) {
  58489. if (webVROptions === void 0) { webVROptions = {}; }
  58490. var _this = _super.call(this, name, position, scene) || this;
  58491. _this.webVROptions = webVROptions;
  58492. _this._vrDevice = null;
  58493. _this.rawPose = null;
  58494. _this._vrEnabled = false;
  58495. _this._specsVersion = 1.1;
  58496. _this._attached = false;
  58497. _this._positionOffset = BABYLON.Vector3.Zero();
  58498. _this._descendants = [];
  58499. _this.devicePosition = BABYLON.Vector3.Zero();
  58500. _this.deviceScaleFactor = 1;
  58501. _this.controllers = [];
  58502. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  58503. //legacy support - the compensation boolean was removed.
  58504. if (arguments.length === 5) {
  58505. _this.webVROptions = arguments[4];
  58506. }
  58507. // default webVR options
  58508. if (_this.webVROptions.trackPosition == undefined) {
  58509. _this.webVROptions.trackPosition = true;
  58510. }
  58511. if (_this.webVROptions.controllerMeshes == undefined) {
  58512. _this.webVROptions.controllerMeshes = true;
  58513. }
  58514. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  58515. _this.webVROptions.defaultLightningOnControllers = true;
  58516. }
  58517. _this.rotationQuaternion = new BABYLON.Quaternion();
  58518. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  58519. if (_this.webVROptions && _this.webVROptions.positionScale) {
  58520. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  58521. }
  58522. //enable VR
  58523. _this.getEngine().initWebVR();
  58524. if (!_this.getEngine().vrDisplaysPromise) {
  58525. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  58526. }
  58527. else {
  58528. //check specs version
  58529. if (!window.VRFrameData) {
  58530. _this._specsVersion = 1.0;
  58531. _this._frameData = {};
  58532. }
  58533. else {
  58534. _this._frameData = new VRFrameData();
  58535. }
  58536. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  58537. if (devices.length > 0) {
  58538. _this._vrEnabled = true;
  58539. if (_this.webVROptions.displayName) {
  58540. var found = devices.some(function (device) {
  58541. if (device.displayName === _this.webVROptions.displayName) {
  58542. _this._vrDevice = device;
  58543. return true;
  58544. }
  58545. else {
  58546. return false;
  58547. }
  58548. });
  58549. if (!found) {
  58550. _this._vrDevice = devices[0];
  58551. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  58552. }
  58553. }
  58554. else {
  58555. //choose the first one
  58556. _this._vrDevice = devices[0];
  58557. }
  58558. //reset the rig parameters.
  58559. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  58560. if (_this._attached) {
  58561. _this.getEngine().enableVR(_this._vrDevice);
  58562. }
  58563. }
  58564. else {
  58565. BABYLON.Tools.Error("No WebVR devices found!");
  58566. }
  58567. });
  58568. }
  58569. // try to attach the controllers, if found.
  58570. _this.initControllers();
  58571. /**
  58572. * The idea behind the following lines:
  58573. * objects that have the camera as parent should actually have the rig cameras as a parent.
  58574. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  58575. * the second will not show it correctly.
  58576. *
  58577. * To solve this - each object that has the camera as parent will be added to a protected array.
  58578. * When the rig camera renders, it will take this array and set all of those to be its children.
  58579. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  58580. * Amazing!
  58581. */
  58582. scene.onBeforeCameraRenderObservable.add(function (camera) {
  58583. if (camera.parent === _this && _this.rigParenting) {
  58584. _this._descendants = _this.getDescendants(true, function (n) {
  58585. // don't take the cameras or the controllers!
  58586. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  58587. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  58588. return !isController && !isRigCamera;
  58589. });
  58590. _this._descendants.forEach(function (node) {
  58591. node.parent = camera;
  58592. });
  58593. }
  58594. });
  58595. scene.onAfterCameraRenderObservable.add(function (camera) {
  58596. if (camera.parent === _this && _this.rigParenting) {
  58597. _this._descendants.forEach(function (node) {
  58598. node.parent = _this;
  58599. });
  58600. }
  58601. });
  58602. return _this;
  58603. }
  58604. Object.defineProperty(WebVRFreeCamera.prototype, "onControllersAttached", {
  58605. set: function (callback) {
  58606. this._onControllersAttached = callback;
  58607. // after setting - if the controllers are already set, execute the callback.
  58608. if (this.controllers.length >= 2) {
  58609. callback(this.controllers);
  58610. }
  58611. },
  58612. enumerable: true,
  58613. configurable: true
  58614. });
  58615. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  58616. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  58617. var gp = _a[_i];
  58618. if (gp.hand === name) {
  58619. return gp;
  58620. }
  58621. }
  58622. return undefined;
  58623. };
  58624. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  58625. get: function () {
  58626. if (!this._leftController) {
  58627. this._leftController = this.getControllerByName("left");
  58628. }
  58629. return this._leftController;
  58630. },
  58631. enumerable: true,
  58632. configurable: true
  58633. });
  58634. ;
  58635. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  58636. get: function () {
  58637. if (!this._rightController) {
  58638. this._rightController = this.getControllerByName("right");
  58639. }
  58640. return this._rightController;
  58641. },
  58642. enumerable: true,
  58643. configurable: true
  58644. });
  58645. ;
  58646. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  58647. if (length === void 0) { length = 100; }
  58648. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  58649. };
  58650. WebVRFreeCamera.prototype._checkInputs = function () {
  58651. if (this._vrEnabled) {
  58652. if (this._specsVersion === 1.1) {
  58653. this._vrDevice.getFrameData(this._frameData);
  58654. }
  58655. else {
  58656. //backwards comp
  58657. var pose = this._vrDevice.getPose();
  58658. this._frameData.pose = pose;
  58659. // calculate view and projection matrix
  58660. }
  58661. this.updateFromDevice(this._frameData.pose);
  58662. }
  58663. _super.prototype._checkInputs.call(this);
  58664. };
  58665. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  58666. if (poseData && poseData.orientation) {
  58667. this.rawPose = poseData;
  58668. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  58669. if (this.getScene().useRightHandedSystem) {
  58670. this.deviceRotationQuaternion.z *= -1;
  58671. this.deviceRotationQuaternion.w *= -1;
  58672. }
  58673. if (this.webVROptions.trackPosition && this.rawPose.position) {
  58674. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  58675. if (this.getScene().useRightHandedSystem) {
  58676. this.devicePosition.z *= -1;
  58677. }
  58678. }
  58679. }
  58680. };
  58681. /**
  58682. * WebVR's attach control will start broadcasting frames to the device.
  58683. * Note that in certain browsers (chrome for example) this function must be called
  58684. * within a user-interaction callback. Example:
  58685. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  58686. *
  58687. * @param {HTMLElement} element
  58688. * @param {boolean} [noPreventDefault]
  58689. *
  58690. * @memberOf WebVRFreeCamera
  58691. */
  58692. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  58693. _super.prototype.attachControl.call(this, element, noPreventDefault);
  58694. this._attached = true;
  58695. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  58696. if (this._vrEnabled) {
  58697. this.getEngine().enableVR(this._vrDevice);
  58698. }
  58699. };
  58700. WebVRFreeCamera.prototype.detachControl = function (element) {
  58701. _super.prototype.detachControl.call(this, element);
  58702. this._vrEnabled = false;
  58703. this._attached = false;
  58704. this.getEngine().disableVR();
  58705. };
  58706. WebVRFreeCamera.prototype.getClassName = function () {
  58707. return "WebVRFreeCamera";
  58708. };
  58709. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  58710. //uses the vrDisplay's "resetPose()".
  58711. //pitch and roll won't be affected.
  58712. this._vrDevice.resetPose();
  58713. };
  58714. WebVRFreeCamera.prototype._updateRigCameras = function () {
  58715. var camLeft = this._rigCameras[0];
  58716. var camRight = this._rigCameras[1];
  58717. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  58718. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  58719. camLeft.position.copyFrom(this.devicePosition);
  58720. camRight.position.copyFrom(this.devicePosition);
  58721. };
  58722. /**
  58723. * This function is called by the two RIG cameras.
  58724. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  58725. */
  58726. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  58727. var _this = this;
  58728. //WebVR 1.0
  58729. if (this._cameraRigParams["specs"] === 1.0) {
  58730. this._updateCameraRotationMatrix();
  58731. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  58732. // Computing target and final matrix
  58733. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  58734. if (this.getScene().useRightHandedSystem) {
  58735. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  58736. }
  58737. else {
  58738. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  58739. }
  58740. //now move the eye in the right direction
  58741. var eyeParams = this._cameraRigParams["eyeParameters"];
  58742. var offset = eyeParams.offset;
  58743. // it will actually always be 0, but just in case
  58744. if (this.getScene().useRightHandedSystem) {
  58745. offset[2] *= -1;
  58746. }
  58747. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  58748. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  58749. }
  58750. else {
  58751. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  58752. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  58753. if (!this.getScene().useRightHandedSystem) {
  58754. [2, 6, 8, 9, 14].forEach(function (num) {
  58755. _this._webvrViewMatrix.m[num] *= -1;
  58756. });
  58757. }
  58758. // update the camera rotation matrix
  58759. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  58760. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  58761. // Computing target and final matrix
  58762. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  58763. }
  58764. var parentCamera = this._cameraRigParams["parentCamera"];
  58765. // should the view matrix be updated with scale and position offset?
  58766. if (parentCamera.deviceScaleFactor !== 1) {
  58767. this._webvrViewMatrix.invert();
  58768. // scale the position, if set
  58769. if (parentCamera.deviceScaleFactor) {
  58770. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  58771. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  58772. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  58773. }
  58774. this._webvrViewMatrix.invert();
  58775. }
  58776. return this._webvrViewMatrix;
  58777. };
  58778. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  58779. var _this = this;
  58780. if (this._cameraRigParams["specs"] === 1.0) {
  58781. var eyeParams = this._cameraRigParams["eyeParameters"];
  58782. // deprecated!!
  58783. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  58784. }
  58785. else {
  58786. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  58787. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  58788. //babylon compatible matrix
  58789. if (!this.getScene().useRightHandedSystem) {
  58790. [8, 9, 10, 11].forEach(function (num) {
  58791. _this._projectionMatrix.m[num] *= -1;
  58792. });
  58793. }
  58794. }
  58795. return this._projectionMatrix;
  58796. };
  58797. WebVRFreeCamera.prototype.initControllers = function () {
  58798. var _this = this;
  58799. this.controllers = [];
  58800. new BABYLON.Gamepads(function (gp) {
  58801. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  58802. var webVrController = gp;
  58803. if (_this.webVROptions.controllerMeshes) {
  58804. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  58805. if (_this.webVROptions.defaultLightningOnControllers) {
  58806. if (!_this._lightOnControllers) {
  58807. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  58808. }
  58809. loadedMesh.getChildren().forEach(function (mesh) {
  58810. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  58811. });
  58812. }
  58813. });
  58814. }
  58815. webVrController.attachToPoseControlledCamera(_this);
  58816. // since this is async - sanity check. Is the controller already stored?
  58817. if (_this.controllers.indexOf(webVrController) === -1) {
  58818. //add to the controllers array
  58819. _this.controllers.push(webVrController);
  58820. //did we find enough controllers? Great! let the developer know.
  58821. if (_this._onControllersAttached && _this.controllers.length >= 2) {
  58822. _this._onControllersAttached(_this.controllers);
  58823. }
  58824. }
  58825. }
  58826. });
  58827. };
  58828. return WebVRFreeCamera;
  58829. }(BABYLON.FreeCamera));
  58830. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  58831. })(BABYLON || (BABYLON = {}));
  58832. //# sourceMappingURL=babylon.webVRCamera.js.map
  58833. /// <reference path="babylon.freeCamera.ts" />
  58834. var BABYLON;
  58835. (function (BABYLON) {
  58836. // We're mainly based on the logic defined into the FreeCamera code
  58837. var DeviceOrientationCamera = (function (_super) {
  58838. __extends(DeviceOrientationCamera, _super);
  58839. function DeviceOrientationCamera(name, position, scene) {
  58840. var _this = _super.call(this, name, position, scene) || this;
  58841. _this._quaternionCache = new BABYLON.Quaternion();
  58842. _this.inputs.addDeviceOrientation();
  58843. return _this;
  58844. }
  58845. DeviceOrientationCamera.prototype.getClassName = function () {
  58846. return "DeviceOrientationCamera";
  58847. };
  58848. DeviceOrientationCamera.prototype._checkInputs = function () {
  58849. _super.prototype._checkInputs.call(this);
  58850. this._quaternionCache.copyFrom(this.rotationQuaternion);
  58851. if (this._initialQuaternion) {
  58852. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  58853. }
  58854. };
  58855. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  58856. var _this = this;
  58857. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  58858. //can only work if this camera has a rotation quaternion already.
  58859. if (!this.rotationQuaternion)
  58860. return;
  58861. if (!this._initialQuaternion) {
  58862. this._initialQuaternion = new BABYLON.Quaternion();
  58863. }
  58864. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  58865. ['x', 'y', 'z'].forEach(function (axisName) {
  58866. if (!axis[axisName]) {
  58867. _this._initialQuaternion[axisName] = 0;
  58868. }
  58869. else {
  58870. _this._initialQuaternion[axisName] *= -1;
  58871. }
  58872. });
  58873. this._initialQuaternion.normalize();
  58874. //force rotation update
  58875. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  58876. };
  58877. return DeviceOrientationCamera;
  58878. }(BABYLON.FreeCamera));
  58879. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  58880. })(BABYLON || (BABYLON = {}));
  58881. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  58882. var BABYLON;
  58883. (function (BABYLON) {
  58884. var VRDeviceOrientationFreeCamera = (function (_super) {
  58885. __extends(VRDeviceOrientationFreeCamera, _super);
  58886. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  58887. if (compensateDistortion === void 0) { compensateDistortion = true; }
  58888. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  58889. var _this = _super.call(this, name, position, scene) || this;
  58890. vrCameraMetrics.compensateDistortion = compensateDistortion;
  58891. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  58892. return _this;
  58893. }
  58894. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  58895. return "VRDeviceOrientationFreeCamera";
  58896. };
  58897. return VRDeviceOrientationFreeCamera;
  58898. }(BABYLON.DeviceOrientationCamera));
  58899. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  58900. var VRDeviceOrientationGamepadCamera = (function (_super) {
  58901. __extends(VRDeviceOrientationGamepadCamera, _super);
  58902. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  58903. if (compensateDistortion === void 0) { compensateDistortion = true; }
  58904. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  58905. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  58906. _this.inputs.addGamepad();
  58907. return _this;
  58908. }
  58909. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  58910. return "VRDeviceOrientationGamepadCamera";
  58911. };
  58912. return VRDeviceOrientationGamepadCamera;
  58913. }(VRDeviceOrientationFreeCamera));
  58914. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  58915. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  58916. __extends(VRDeviceOrientationArcRotateCamera, _super);
  58917. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  58918. if (compensateDistortion === void 0) { compensateDistortion = true; }
  58919. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  58920. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  58921. vrCameraMetrics.compensateDistortion = compensateDistortion;
  58922. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  58923. _this.inputs.addVRDeviceOrientation();
  58924. return _this;
  58925. }
  58926. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  58927. return "VRDeviceOrientationArcRotateCamera";
  58928. };
  58929. return VRDeviceOrientationArcRotateCamera;
  58930. }(BABYLON.ArcRotateCamera));
  58931. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  58932. })(BABYLON || (BABYLON = {}));
  58933. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  58934. /// <reference path="babylon.freeCamera.ts" />
  58935. /// <reference path="babylon.arcRotateCamera.ts" />
  58936. /// <reference path="babylon.gamepadCamera.ts" />
  58937. /// <reference path="babylon.universalCamera.ts" />
  58938. var BABYLON;
  58939. (function (BABYLON) {
  58940. var AnaglyphFreeCamera = (function (_super) {
  58941. __extends(AnaglyphFreeCamera, _super);
  58942. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  58943. var _this = _super.call(this, name, position, scene) || this;
  58944. _this.interaxialDistance = interaxialDistance;
  58945. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  58946. return _this;
  58947. }
  58948. AnaglyphFreeCamera.prototype.getClassName = function () {
  58949. return "AnaglyphFreeCamera";
  58950. };
  58951. return AnaglyphFreeCamera;
  58952. }(BABYLON.FreeCamera));
  58953. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  58954. var AnaglyphArcRotateCamera = (function (_super) {
  58955. __extends(AnaglyphArcRotateCamera, _super);
  58956. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  58957. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  58958. _this.interaxialDistance = interaxialDistance;
  58959. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  58960. return _this;
  58961. }
  58962. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  58963. return "AnaglyphArcRotateCamera";
  58964. };
  58965. return AnaglyphArcRotateCamera;
  58966. }(BABYLON.ArcRotateCamera));
  58967. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  58968. var AnaglyphGamepadCamera = (function (_super) {
  58969. __extends(AnaglyphGamepadCamera, _super);
  58970. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  58971. var _this = _super.call(this, name, position, scene) || this;
  58972. _this.interaxialDistance = interaxialDistance;
  58973. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  58974. return _this;
  58975. }
  58976. AnaglyphGamepadCamera.prototype.getClassName = function () {
  58977. return "AnaglyphGamepadCamera";
  58978. };
  58979. return AnaglyphGamepadCamera;
  58980. }(BABYLON.GamepadCamera));
  58981. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  58982. var AnaglyphUniversalCamera = (function (_super) {
  58983. __extends(AnaglyphUniversalCamera, _super);
  58984. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  58985. var _this = _super.call(this, name, position, scene) || this;
  58986. _this.interaxialDistance = interaxialDistance;
  58987. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  58988. return _this;
  58989. }
  58990. AnaglyphUniversalCamera.prototype.getClassName = function () {
  58991. return "AnaglyphUniversalCamera";
  58992. };
  58993. return AnaglyphUniversalCamera;
  58994. }(BABYLON.UniversalCamera));
  58995. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  58996. var StereoscopicFreeCamera = (function (_super) {
  58997. __extends(StereoscopicFreeCamera, _super);
  58998. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  58999. var _this = _super.call(this, name, position, scene) || this;
  59000. _this.interaxialDistance = interaxialDistance;
  59001. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  59002. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  59003. return _this;
  59004. }
  59005. StereoscopicFreeCamera.prototype.getClassName = function () {
  59006. return "StereoscopicFreeCamera";
  59007. };
  59008. return StereoscopicFreeCamera;
  59009. }(BABYLON.FreeCamera));
  59010. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  59011. var StereoscopicArcRotateCamera = (function (_super) {
  59012. __extends(StereoscopicArcRotateCamera, _super);
  59013. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  59014. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  59015. _this.interaxialDistance = interaxialDistance;
  59016. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  59017. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  59018. return _this;
  59019. }
  59020. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  59021. return "StereoscopicArcRotateCamera";
  59022. };
  59023. return StereoscopicArcRotateCamera;
  59024. }(BABYLON.ArcRotateCamera));
  59025. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  59026. var StereoscopicGamepadCamera = (function (_super) {
  59027. __extends(StereoscopicGamepadCamera, _super);
  59028. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  59029. var _this = _super.call(this, name, position, scene) || this;
  59030. _this.interaxialDistance = interaxialDistance;
  59031. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  59032. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  59033. return _this;
  59034. }
  59035. StereoscopicGamepadCamera.prototype.getClassName = function () {
  59036. return "StereoscopicGamepadCamera";
  59037. };
  59038. return StereoscopicGamepadCamera;
  59039. }(BABYLON.GamepadCamera));
  59040. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  59041. var StereoscopicUniversalCamera = (function (_super) {
  59042. __extends(StereoscopicUniversalCamera, _super);
  59043. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  59044. var _this = _super.call(this, name, position, scene) || this;
  59045. _this.interaxialDistance = interaxialDistance;
  59046. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  59047. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  59048. return _this;
  59049. }
  59050. StereoscopicUniversalCamera.prototype.getClassName = function () {
  59051. return "StereoscopicUniversalCamera";
  59052. };
  59053. return StereoscopicUniversalCamera;
  59054. }(BABYLON.UniversalCamera));
  59055. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  59056. })(BABYLON || (BABYLON = {}));
  59057. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  59058. // Mainly based on these 2 articles :
  59059. // 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
  59060. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  59061. var BABYLON;
  59062. (function (BABYLON) {
  59063. var JoystickAxis;
  59064. (function (JoystickAxis) {
  59065. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  59066. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  59067. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  59068. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  59069. var VirtualJoystick = (function () {
  59070. function VirtualJoystick(leftJoystick) {
  59071. var _this = this;
  59072. if (leftJoystick) {
  59073. this._leftJoystick = true;
  59074. }
  59075. else {
  59076. this._leftJoystick = false;
  59077. }
  59078. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  59079. VirtualJoystick._globalJoystickIndex++;
  59080. // By default left & right arrow keys are moving the X
  59081. // and up & down keys are moving the Y
  59082. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  59083. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  59084. this.reverseLeftRight = false;
  59085. this.reverseUpDown = false;
  59086. // collections of pointers
  59087. this._touches = new BABYLON.StringDictionary();
  59088. this.deltaPosition = BABYLON.Vector3.Zero();
  59089. this._joystickSensibility = 25;
  59090. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  59091. this._rotationSpeed = 25;
  59092. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  59093. this._rotateOnAxisRelativeToMesh = false;
  59094. this._onResize = function (evt) {
  59095. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  59096. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  59097. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  59098. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  59099. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  59100. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  59101. };
  59102. // injecting a canvas element on top of the canvas 3D game
  59103. if (!VirtualJoystick.vjCanvas) {
  59104. window.addEventListener("resize", this._onResize, false);
  59105. VirtualJoystick.vjCanvas = document.createElement("canvas");
  59106. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  59107. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  59108. VirtualJoystick.vjCanvas.width = window.innerWidth;
  59109. VirtualJoystick.vjCanvas.height = window.innerHeight;
  59110. VirtualJoystick.vjCanvas.style.width = "100%";
  59111. VirtualJoystick.vjCanvas.style.height = "100%";
  59112. VirtualJoystick.vjCanvas.style.position = "absolute";
  59113. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  59114. VirtualJoystick.vjCanvas.style.top = "0px";
  59115. VirtualJoystick.vjCanvas.style.left = "0px";
  59116. VirtualJoystick.vjCanvas.style.zIndex = "5";
  59117. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  59118. // Support for jQuery PEP polyfill
  59119. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  59120. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  59121. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  59122. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  59123. document.body.appendChild(VirtualJoystick.vjCanvas);
  59124. }
  59125. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  59126. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  59127. this.pressed = false;
  59128. // default joystick color
  59129. this._joystickColor = "cyan";
  59130. this._joystickPointerID = -1;
  59131. // current joystick position
  59132. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  59133. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  59134. // origin joystick position
  59135. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  59136. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  59137. this._onPointerDownHandlerRef = function (evt) {
  59138. _this._onPointerDown(evt);
  59139. };
  59140. this._onPointerMoveHandlerRef = function (evt) {
  59141. _this._onPointerMove(evt);
  59142. };
  59143. this._onPointerOutHandlerRef = function (evt) {
  59144. _this._onPointerUp(evt);
  59145. };
  59146. this._onPointerUpHandlerRef = function (evt) {
  59147. _this._onPointerUp(evt);
  59148. };
  59149. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  59150. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  59151. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  59152. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  59153. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  59154. evt.preventDefault(); // Disables system menu
  59155. }, false);
  59156. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  59157. }
  59158. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  59159. this._joystickSensibility = newJoystickSensibility;
  59160. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  59161. };
  59162. VirtualJoystick.prototype._onPointerDown = function (e) {
  59163. var positionOnScreenCondition;
  59164. e.preventDefault();
  59165. if (this._leftJoystick === true) {
  59166. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  59167. }
  59168. else {
  59169. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  59170. }
  59171. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  59172. // First contact will be dedicated to the virtual joystick
  59173. this._joystickPointerID = e.pointerId;
  59174. this._joystickPointerStartPos.x = e.clientX;
  59175. this._joystickPointerStartPos.y = e.clientY;
  59176. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  59177. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  59178. this._deltaJoystickVector.x = 0;
  59179. this._deltaJoystickVector.y = 0;
  59180. this.pressed = true;
  59181. this._touches.add(e.pointerId.toString(), e);
  59182. }
  59183. else {
  59184. // You can only trigger the action buttons with a joystick declared
  59185. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  59186. this._action();
  59187. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  59188. }
  59189. }
  59190. };
  59191. VirtualJoystick.prototype._onPointerMove = function (e) {
  59192. // If the current pointer is the one associated to the joystick (first touch contact)
  59193. if (this._joystickPointerID == e.pointerId) {
  59194. this._joystickPointerPos.x = e.clientX;
  59195. this._joystickPointerPos.y = e.clientY;
  59196. this._deltaJoystickVector = this._joystickPointerPos.clone();
  59197. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  59198. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  59199. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  59200. switch (this._axisTargetedByLeftAndRight) {
  59201. case JoystickAxis.X:
  59202. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  59203. break;
  59204. case JoystickAxis.Y:
  59205. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  59206. break;
  59207. case JoystickAxis.Z:
  59208. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  59209. break;
  59210. }
  59211. var directionUpDown = this.reverseUpDown ? 1 : -1;
  59212. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  59213. switch (this._axisTargetedByUpAndDown) {
  59214. case JoystickAxis.X:
  59215. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  59216. break;
  59217. case JoystickAxis.Y:
  59218. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  59219. break;
  59220. case JoystickAxis.Z:
  59221. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  59222. break;
  59223. }
  59224. }
  59225. else {
  59226. var data = this._touches.get(e.pointerId.toString());
  59227. if (data) {
  59228. data.x = e.clientX;
  59229. data.y = e.clientY;
  59230. }
  59231. }
  59232. };
  59233. VirtualJoystick.prototype._onPointerUp = function (e) {
  59234. if (this._joystickPointerID == e.pointerId) {
  59235. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  59236. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  59237. this._joystickPointerID = -1;
  59238. this.pressed = false;
  59239. }
  59240. else {
  59241. var touch = this._touches.get(e.pointerId.toString());
  59242. if (touch) {
  59243. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  59244. }
  59245. }
  59246. this._deltaJoystickVector.x = 0;
  59247. this._deltaJoystickVector.y = 0;
  59248. this._touches.remove(e.pointerId.toString());
  59249. };
  59250. /**
  59251. * Change the color of the virtual joystick
  59252. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  59253. */
  59254. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  59255. this._joystickColor = newColor;
  59256. };
  59257. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  59258. this._action = action;
  59259. };
  59260. // Define which axis you'd like to control for left & right
  59261. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  59262. switch (axis) {
  59263. case JoystickAxis.X:
  59264. case JoystickAxis.Y:
  59265. case JoystickAxis.Z:
  59266. this._axisTargetedByLeftAndRight = axis;
  59267. break;
  59268. default:
  59269. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  59270. break;
  59271. }
  59272. };
  59273. // Define which axis you'd like to control for up & down
  59274. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  59275. switch (axis) {
  59276. case JoystickAxis.X:
  59277. case JoystickAxis.Y:
  59278. case JoystickAxis.Z:
  59279. this._axisTargetedByUpAndDown = axis;
  59280. break;
  59281. default:
  59282. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  59283. break;
  59284. }
  59285. };
  59286. VirtualJoystick.prototype._clearCanvas = function () {
  59287. if (this._leftJoystick) {
  59288. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  59289. }
  59290. else {
  59291. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  59292. }
  59293. };
  59294. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  59295. var _this = this;
  59296. if (this.pressed) {
  59297. this._touches.forEach(function (key, touch) {
  59298. if (touch.pointerId === _this._joystickPointerID) {
  59299. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  59300. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  59301. VirtualJoystick.vjCanvasContext.beginPath();
  59302. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  59303. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  59304. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  59305. VirtualJoystick.vjCanvasContext.stroke();
  59306. VirtualJoystick.vjCanvasContext.closePath();
  59307. VirtualJoystick.vjCanvasContext.beginPath();
  59308. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  59309. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  59310. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  59311. VirtualJoystick.vjCanvasContext.stroke();
  59312. VirtualJoystick.vjCanvasContext.closePath();
  59313. VirtualJoystick.vjCanvasContext.beginPath();
  59314. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  59315. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  59316. VirtualJoystick.vjCanvasContext.stroke();
  59317. VirtualJoystick.vjCanvasContext.closePath();
  59318. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  59319. }
  59320. else {
  59321. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  59322. VirtualJoystick.vjCanvasContext.beginPath();
  59323. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  59324. VirtualJoystick.vjCanvasContext.beginPath();
  59325. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  59326. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  59327. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  59328. VirtualJoystick.vjCanvasContext.stroke();
  59329. VirtualJoystick.vjCanvasContext.closePath();
  59330. touch.prevX = touch.x;
  59331. touch.prevY = touch.y;
  59332. }
  59333. ;
  59334. });
  59335. }
  59336. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  59337. };
  59338. VirtualJoystick.prototype.releaseCanvas = function () {
  59339. if (VirtualJoystick.vjCanvas) {
  59340. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  59341. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  59342. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  59343. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  59344. window.removeEventListener("resize", this._onResize);
  59345. document.body.removeChild(VirtualJoystick.vjCanvas);
  59346. VirtualJoystick.vjCanvas = null;
  59347. }
  59348. };
  59349. return VirtualJoystick;
  59350. }());
  59351. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  59352. VirtualJoystick._globalJoystickIndex = 0;
  59353. BABYLON.VirtualJoystick = VirtualJoystick;
  59354. })(BABYLON || (BABYLON = {}));
  59355. //# sourceMappingURL=babylon.virtualJoystick.js.map
  59356. var BABYLON;
  59357. (function (BABYLON) {
  59358. // We're mainly based on the logic defined into the FreeCamera code
  59359. var VirtualJoysticksCamera = (function (_super) {
  59360. __extends(VirtualJoysticksCamera, _super);
  59361. function VirtualJoysticksCamera(name, position, scene) {
  59362. var _this = _super.call(this, name, position, scene) || this;
  59363. _this.inputs.addVirtualJoystick();
  59364. return _this;
  59365. }
  59366. VirtualJoysticksCamera.prototype.getClassName = function () {
  59367. return "VirtualJoysticksCamera";
  59368. };
  59369. return VirtualJoysticksCamera;
  59370. }(BABYLON.FreeCamera));
  59371. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  59372. })(BABYLON || (BABYLON = {}));
  59373. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  59374. var BABYLON;
  59375. (function (BABYLON) {
  59376. var FreeCameraVirtualJoystickInput = (function () {
  59377. function FreeCameraVirtualJoystickInput() {
  59378. }
  59379. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  59380. return this._leftjoystick;
  59381. };
  59382. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  59383. return this._rightjoystick;
  59384. };
  59385. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  59386. if (this._leftjoystick) {
  59387. var camera = this.camera;
  59388. var speed = camera._computeLocalCameraSpeed() * 50;
  59389. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  59390. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  59391. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  59392. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  59393. if (!this._leftjoystick.pressed) {
  59394. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  59395. }
  59396. if (!this._rightjoystick.pressed) {
  59397. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  59398. }
  59399. }
  59400. };
  59401. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  59402. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  59403. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  59404. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  59405. this._leftjoystick.setJoystickSensibility(0.15);
  59406. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  59407. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  59408. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  59409. this._rightjoystick.reverseUpDown = true;
  59410. this._rightjoystick.setJoystickSensibility(0.05);
  59411. this._rightjoystick.setJoystickColor("yellow");
  59412. };
  59413. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  59414. this._leftjoystick.releaseCanvas();
  59415. this._rightjoystick.releaseCanvas();
  59416. };
  59417. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  59418. return "FreeCameraVirtualJoystickInput";
  59419. };
  59420. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  59421. return "virtualJoystick";
  59422. };
  59423. return FreeCameraVirtualJoystickInput;
  59424. }());
  59425. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  59426. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  59427. })(BABYLON || (BABYLON = {}));
  59428. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  59429. var BABYLON;
  59430. (function (BABYLON) {
  59431. var SimplificationSettings = (function () {
  59432. function SimplificationSettings(quality, distance, optimizeMesh) {
  59433. this.quality = quality;
  59434. this.distance = distance;
  59435. this.optimizeMesh = optimizeMesh;
  59436. }
  59437. return SimplificationSettings;
  59438. }());
  59439. BABYLON.SimplificationSettings = SimplificationSettings;
  59440. var SimplificationQueue = (function () {
  59441. function SimplificationQueue() {
  59442. this.running = false;
  59443. this._simplificationArray = [];
  59444. }
  59445. SimplificationQueue.prototype.addTask = function (task) {
  59446. this._simplificationArray.push(task);
  59447. };
  59448. SimplificationQueue.prototype.executeNext = function () {
  59449. var task = this._simplificationArray.pop();
  59450. if (task) {
  59451. this.running = true;
  59452. this.runSimplification(task);
  59453. }
  59454. else {
  59455. this.running = false;
  59456. }
  59457. };
  59458. SimplificationQueue.prototype.runSimplification = function (task) {
  59459. var _this = this;
  59460. if (task.parallelProcessing) {
  59461. //parallel simplifier
  59462. task.settings.forEach(function (setting) {
  59463. var simplifier = _this.getSimplifier(task);
  59464. simplifier.simplify(setting, function (newMesh) {
  59465. task.mesh.addLODLevel(setting.distance, newMesh);
  59466. newMesh.isVisible = true;
  59467. //check if it is the last
  59468. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  59469. //all done, run the success callback.
  59470. task.successCallback();
  59471. }
  59472. _this.executeNext();
  59473. });
  59474. });
  59475. }
  59476. else {
  59477. //single simplifier.
  59478. var simplifier = this.getSimplifier(task);
  59479. var runDecimation = function (setting, callback) {
  59480. simplifier.simplify(setting, function (newMesh) {
  59481. task.mesh.addLODLevel(setting.distance, newMesh);
  59482. newMesh.isVisible = true;
  59483. //run the next quality level
  59484. callback();
  59485. });
  59486. };
  59487. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  59488. runDecimation(task.settings[loop.index], function () {
  59489. loop.executeNext();
  59490. });
  59491. }, function () {
  59492. //execution ended, run the success callback.
  59493. if (task.successCallback) {
  59494. task.successCallback();
  59495. }
  59496. _this.executeNext();
  59497. });
  59498. }
  59499. };
  59500. SimplificationQueue.prototype.getSimplifier = function (task) {
  59501. switch (task.simplificationType) {
  59502. case SimplificationType.QUADRATIC:
  59503. default:
  59504. return new QuadraticErrorSimplification(task.mesh);
  59505. }
  59506. };
  59507. return SimplificationQueue;
  59508. }());
  59509. BABYLON.SimplificationQueue = SimplificationQueue;
  59510. /**
  59511. * The implemented types of simplification.
  59512. * At the moment only Quadratic Error Decimation is implemented.
  59513. */
  59514. var SimplificationType;
  59515. (function (SimplificationType) {
  59516. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  59517. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  59518. var DecimationTriangle = (function () {
  59519. function DecimationTriangle(vertices) {
  59520. this.vertices = vertices;
  59521. this.error = new Array(4);
  59522. this.deleted = false;
  59523. this.isDirty = false;
  59524. this.deletePending = false;
  59525. this.borderFactor = 0;
  59526. }
  59527. return DecimationTriangle;
  59528. }());
  59529. BABYLON.DecimationTriangle = DecimationTriangle;
  59530. var DecimationVertex = (function () {
  59531. function DecimationVertex(position, id) {
  59532. this.position = position;
  59533. this.id = id;
  59534. this.isBorder = true;
  59535. this.q = new QuadraticMatrix();
  59536. this.triangleCount = 0;
  59537. this.triangleStart = 0;
  59538. this.originalOffsets = [];
  59539. }
  59540. DecimationVertex.prototype.updatePosition = function (newPosition) {
  59541. this.position.copyFrom(newPosition);
  59542. };
  59543. return DecimationVertex;
  59544. }());
  59545. BABYLON.DecimationVertex = DecimationVertex;
  59546. var QuadraticMatrix = (function () {
  59547. function QuadraticMatrix(data) {
  59548. this.data = new Array(10);
  59549. for (var i = 0; i < 10; ++i) {
  59550. if (data && data[i]) {
  59551. this.data[i] = data[i];
  59552. }
  59553. else {
  59554. this.data[i] = 0;
  59555. }
  59556. }
  59557. }
  59558. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  59559. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  59560. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  59561. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  59562. return det;
  59563. };
  59564. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  59565. for (var i = 0; i < 10; ++i) {
  59566. this.data[i] += matrix.data[i];
  59567. }
  59568. };
  59569. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  59570. for (var i = 0; i < 10; ++i) {
  59571. this.data[i] += data[i];
  59572. }
  59573. };
  59574. QuadraticMatrix.prototype.add = function (matrix) {
  59575. var m = new QuadraticMatrix();
  59576. for (var i = 0; i < 10; ++i) {
  59577. m.data[i] = this.data[i] + matrix.data[i];
  59578. }
  59579. return m;
  59580. };
  59581. QuadraticMatrix.FromData = function (a, b, c, d) {
  59582. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  59583. };
  59584. //returning an array to avoid garbage collection
  59585. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  59586. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  59587. };
  59588. return QuadraticMatrix;
  59589. }());
  59590. BABYLON.QuadraticMatrix = QuadraticMatrix;
  59591. var Reference = (function () {
  59592. function Reference(vertexId, triangleId) {
  59593. this.vertexId = vertexId;
  59594. this.triangleId = triangleId;
  59595. }
  59596. return Reference;
  59597. }());
  59598. BABYLON.Reference = Reference;
  59599. /**
  59600. * An implementation of the Quadratic Error simplification algorithm.
  59601. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  59602. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  59603. * @author RaananW
  59604. */
  59605. var QuadraticErrorSimplification = (function () {
  59606. function QuadraticErrorSimplification(_mesh) {
  59607. this._mesh = _mesh;
  59608. this.initialized = false;
  59609. this.syncIterations = 5000;
  59610. this.aggressiveness = 7;
  59611. this.decimationIterations = 100;
  59612. this.boundingBoxEpsilon = BABYLON.Epsilon;
  59613. }
  59614. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  59615. var _this = this;
  59616. this.initDecimatedMesh();
  59617. //iterating through the submeshes array, one after the other.
  59618. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  59619. _this.initWithMesh(loop.index, function () {
  59620. _this.runDecimation(settings, loop.index, function () {
  59621. loop.executeNext();
  59622. });
  59623. }, settings.optimizeMesh);
  59624. }, function () {
  59625. setTimeout(function () {
  59626. successCallback(_this._reconstructedMesh);
  59627. }, 0);
  59628. });
  59629. };
  59630. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  59631. var _this = this;
  59632. var gCount = 0;
  59633. triangle.vertices.forEach(function (vertex) {
  59634. var count = 0;
  59635. var vPos = vertex.position;
  59636. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  59637. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  59638. ++count;
  59639. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  59640. ++count;
  59641. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  59642. ++count;
  59643. if (count > 1) {
  59644. ++gCount;
  59645. }
  59646. ;
  59647. });
  59648. if (gCount > 1) {
  59649. console.log(triangle, gCount);
  59650. }
  59651. return gCount > 1;
  59652. };
  59653. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  59654. var _this = this;
  59655. var targetCount = ~~(this.triangles.length * settings.quality);
  59656. var deletedTriangles = 0;
  59657. var triangleCount = this.triangles.length;
  59658. var iterationFunction = function (iteration, callback) {
  59659. setTimeout(function () {
  59660. if (iteration % 5 === 0) {
  59661. _this.updateMesh(iteration === 0);
  59662. }
  59663. for (var i = 0; i < _this.triangles.length; ++i) {
  59664. _this.triangles[i].isDirty = false;
  59665. }
  59666. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  59667. var trianglesIterator = function (i) {
  59668. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  59669. var t = _this.triangles[tIdx];
  59670. if (!t)
  59671. return;
  59672. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  59673. return;
  59674. }
  59675. for (var j = 0; j < 3; ++j) {
  59676. if (t.error[j] < threshold) {
  59677. var deleted0 = [];
  59678. var deleted1 = [];
  59679. var v0 = t.vertices[j];
  59680. var v1 = t.vertices[(j + 1) % 3];
  59681. if (v0.isBorder || v1.isBorder)
  59682. continue;
  59683. var p = BABYLON.Vector3.Zero();
  59684. var n = BABYLON.Vector3.Zero();
  59685. var uv = BABYLON.Vector2.Zero();
  59686. var color = new BABYLON.Color4(0, 0, 0, 1);
  59687. _this.calculateError(v0, v1, p, n, uv, color);
  59688. var delTr = [];
  59689. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  59690. continue;
  59691. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  59692. continue;
  59693. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  59694. continue;
  59695. var uniqueArray = [];
  59696. delTr.forEach(function (deletedT) {
  59697. if (uniqueArray.indexOf(deletedT) === -1) {
  59698. deletedT.deletePending = true;
  59699. uniqueArray.push(deletedT);
  59700. }
  59701. });
  59702. if (uniqueArray.length % 2 !== 0) {
  59703. continue;
  59704. }
  59705. v0.q = v1.q.add(v0.q);
  59706. v0.updatePosition(p);
  59707. var tStart = _this.references.length;
  59708. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  59709. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  59710. var tCount = _this.references.length - tStart;
  59711. if (tCount <= v0.triangleCount) {
  59712. if (tCount) {
  59713. for (var c = 0; c < tCount; c++) {
  59714. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  59715. }
  59716. }
  59717. }
  59718. else {
  59719. v0.triangleStart = tStart;
  59720. }
  59721. v0.triangleCount = tCount;
  59722. break;
  59723. }
  59724. }
  59725. };
  59726. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  59727. }, 0);
  59728. };
  59729. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  59730. if (triangleCount - deletedTriangles <= targetCount)
  59731. loop.breakLoop();
  59732. else {
  59733. iterationFunction(loop.index, function () {
  59734. loop.executeNext();
  59735. });
  59736. }
  59737. }, function () {
  59738. setTimeout(function () {
  59739. //reconstruct this part of the mesh
  59740. _this.reconstructMesh(submeshIndex);
  59741. successCallback();
  59742. }, 0);
  59743. });
  59744. };
  59745. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  59746. var _this = this;
  59747. this.vertices = [];
  59748. this.triangles = [];
  59749. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59750. var indices = this._mesh.getIndices();
  59751. var submesh = this._mesh.subMeshes[submeshIndex];
  59752. var findInVertices = function (positionToSearch) {
  59753. if (optimizeMesh) {
  59754. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  59755. if (_this.vertices[ii].position.equals(positionToSearch)) {
  59756. return _this.vertices[ii];
  59757. }
  59758. }
  59759. }
  59760. return null;
  59761. };
  59762. var vertexReferences = [];
  59763. var vertexInit = function (i) {
  59764. var offset = i + submesh.verticesStart;
  59765. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  59766. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  59767. vertex.originalOffsets.push(offset);
  59768. if (vertex.id === _this.vertices.length) {
  59769. _this.vertices.push(vertex);
  59770. }
  59771. vertexReferences.push(vertex.id);
  59772. };
  59773. //var totalVertices = mesh.getTotalVertices();
  59774. var totalVertices = submesh.verticesCount;
  59775. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  59776. var indicesInit = function (i) {
  59777. var offset = (submesh.indexStart / 3) + i;
  59778. var pos = (offset * 3);
  59779. var i0 = indices[pos + 0];
  59780. var i1 = indices[pos + 1];
  59781. var i2 = indices[pos + 2];
  59782. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  59783. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  59784. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  59785. var triangle = new DecimationTriangle([v0, v1, v2]);
  59786. triangle.originalOffset = pos;
  59787. _this.triangles.push(triangle);
  59788. };
  59789. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  59790. _this.init(callback);
  59791. });
  59792. });
  59793. };
  59794. QuadraticErrorSimplification.prototype.init = function (callback) {
  59795. var _this = this;
  59796. var triangleInit1 = function (i) {
  59797. var t = _this.triangles[i];
  59798. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  59799. for (var j = 0; j < 3; j++) {
  59800. 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))));
  59801. }
  59802. };
  59803. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  59804. var triangleInit2 = function (i) {
  59805. var t = _this.triangles[i];
  59806. for (var j = 0; j < 3; ++j) {
  59807. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  59808. }
  59809. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  59810. };
  59811. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  59812. _this.initialized = true;
  59813. callback();
  59814. });
  59815. });
  59816. };
  59817. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  59818. var newTriangles = [];
  59819. var i;
  59820. for (i = 0; i < this.vertices.length; ++i) {
  59821. this.vertices[i].triangleCount = 0;
  59822. }
  59823. var t;
  59824. var j;
  59825. for (i = 0; i < this.triangles.length; ++i) {
  59826. if (!this.triangles[i].deleted) {
  59827. t = this.triangles[i];
  59828. for (j = 0; j < 3; ++j) {
  59829. t.vertices[j].triangleCount = 1;
  59830. }
  59831. newTriangles.push(t);
  59832. }
  59833. }
  59834. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  59835. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  59836. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  59837. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  59838. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59839. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59840. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59841. var vertexCount = 0;
  59842. for (i = 0; i < this.vertices.length; ++i) {
  59843. var vertex = this.vertices[i];
  59844. vertex.id = vertexCount;
  59845. if (vertex.triangleCount) {
  59846. vertex.originalOffsets.forEach(function (originalOffset) {
  59847. newPositionData.push(vertex.position.x);
  59848. newPositionData.push(vertex.position.y);
  59849. newPositionData.push(vertex.position.z);
  59850. newNormalData.push(normalData[originalOffset * 3]);
  59851. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  59852. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  59853. if (uvs && uvs.length) {
  59854. newUVsData.push(uvs[(originalOffset * 2)]);
  59855. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  59856. }
  59857. else if (colorsData && colorsData.length) {
  59858. newColorsData.push(colorsData[(originalOffset * 4)]);
  59859. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  59860. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  59861. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  59862. }
  59863. ++vertexCount;
  59864. });
  59865. }
  59866. }
  59867. var startingIndex = this._reconstructedMesh.getTotalIndices();
  59868. var startingVertex = this._reconstructedMesh.getTotalVertices();
  59869. var submeshesArray = this._reconstructedMesh.subMeshes;
  59870. this._reconstructedMesh.subMeshes = [];
  59871. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  59872. var originalIndices = this._mesh.getIndices();
  59873. for (i = 0; i < newTriangles.length; ++i) {
  59874. t = newTriangles[i]; //now get the new referencing point for each vertex
  59875. [0, 1, 2].forEach(function (idx) {
  59876. var id = originalIndices[t.originalOffset + idx];
  59877. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  59878. if (offset < 0)
  59879. offset = 0;
  59880. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  59881. });
  59882. }
  59883. //overwriting the old vertex buffers and indices.
  59884. this._reconstructedMesh.setIndices(newIndicesArray);
  59885. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  59886. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  59887. if (newUVsData.length > 0)
  59888. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  59889. if (newColorsData.length > 0)
  59890. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  59891. //create submesh
  59892. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  59893. if (submeshIndex > 0) {
  59894. this._reconstructedMesh.subMeshes = [];
  59895. submeshesArray.forEach(function (submesh) {
  59896. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  59897. });
  59898. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  59899. }
  59900. };
  59901. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  59902. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  59903. this._reconstructedMesh.material = this._mesh.material;
  59904. this._reconstructedMesh.parent = this._mesh.parent;
  59905. this._reconstructedMesh.isVisible = false;
  59906. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  59907. };
  59908. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  59909. for (var i = 0; i < vertex1.triangleCount; ++i) {
  59910. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  59911. if (t.deleted)
  59912. continue;
  59913. var s = this.references[vertex1.triangleStart + i].vertexId;
  59914. var v1 = t.vertices[(s + 1) % 3];
  59915. var v2 = t.vertices[(s + 2) % 3];
  59916. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  59917. deletedArray[i] = true;
  59918. delTr.push(t);
  59919. continue;
  59920. }
  59921. var d1 = v1.position.subtract(point);
  59922. d1 = d1.normalize();
  59923. var d2 = v2.position.subtract(point);
  59924. d2 = d2.normalize();
  59925. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  59926. return true;
  59927. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  59928. deletedArray[i] = false;
  59929. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  59930. return true;
  59931. }
  59932. return false;
  59933. };
  59934. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  59935. var newDeleted = deletedTriangles;
  59936. for (var i = 0; i < vertex.triangleCount; ++i) {
  59937. var ref = this.references[vertex.triangleStart + i];
  59938. var t = this.triangles[ref.triangleId];
  59939. if (t.deleted)
  59940. continue;
  59941. if (deletedArray[i] && t.deletePending) {
  59942. t.deleted = true;
  59943. newDeleted++;
  59944. continue;
  59945. }
  59946. t.vertices[ref.vertexId] = origVertex;
  59947. t.isDirty = true;
  59948. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  59949. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  59950. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  59951. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  59952. this.references.push(ref);
  59953. }
  59954. return newDeleted;
  59955. };
  59956. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  59957. for (var i = 0; i < this.vertices.length; ++i) {
  59958. var vCount = [];
  59959. var vId = [];
  59960. var v = this.vertices[i];
  59961. var j;
  59962. for (j = 0; j < v.triangleCount; ++j) {
  59963. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  59964. for (var ii = 0; ii < 3; ii++) {
  59965. var ofs = 0;
  59966. var vv = triangle.vertices[ii];
  59967. while (ofs < vCount.length) {
  59968. if (vId[ofs] === vv.id)
  59969. break;
  59970. ++ofs;
  59971. }
  59972. if (ofs === vCount.length) {
  59973. vCount.push(1);
  59974. vId.push(vv.id);
  59975. }
  59976. else {
  59977. vCount[ofs]++;
  59978. }
  59979. }
  59980. }
  59981. for (j = 0; j < vCount.length; ++j) {
  59982. if (vCount[j] === 1) {
  59983. this.vertices[vId[j]].isBorder = true;
  59984. }
  59985. else {
  59986. this.vertices[vId[j]].isBorder = false;
  59987. }
  59988. }
  59989. }
  59990. };
  59991. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  59992. if (identifyBorders === void 0) { identifyBorders = false; }
  59993. var i;
  59994. if (!identifyBorders) {
  59995. var newTrianglesVector = [];
  59996. for (i = 0; i < this.triangles.length; ++i) {
  59997. if (!this.triangles[i].deleted) {
  59998. newTrianglesVector.push(this.triangles[i]);
  59999. }
  60000. }
  60001. this.triangles = newTrianglesVector;
  60002. }
  60003. for (i = 0; i < this.vertices.length; ++i) {
  60004. this.vertices[i].triangleCount = 0;
  60005. this.vertices[i].triangleStart = 0;
  60006. }
  60007. var t;
  60008. var j;
  60009. var v;
  60010. for (i = 0; i < this.triangles.length; ++i) {
  60011. t = this.triangles[i];
  60012. for (j = 0; j < 3; ++j) {
  60013. v = t.vertices[j];
  60014. v.triangleCount++;
  60015. }
  60016. }
  60017. var tStart = 0;
  60018. for (i = 0; i < this.vertices.length; ++i) {
  60019. this.vertices[i].triangleStart = tStart;
  60020. tStart += this.vertices[i].triangleCount;
  60021. this.vertices[i].triangleCount = 0;
  60022. }
  60023. var newReferences = new Array(this.triangles.length * 3);
  60024. for (i = 0; i < this.triangles.length; ++i) {
  60025. t = this.triangles[i];
  60026. for (j = 0; j < 3; ++j) {
  60027. v = t.vertices[j];
  60028. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  60029. v.triangleCount++;
  60030. }
  60031. }
  60032. this.references = newReferences;
  60033. if (identifyBorders) {
  60034. this.identifyBorder();
  60035. }
  60036. };
  60037. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  60038. var x = point.x;
  60039. var y = point.y;
  60040. var z = point.z;
  60041. 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
  60042. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  60043. };
  60044. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  60045. var q = vertex1.q.add(vertex2.q);
  60046. var border = vertex1.isBorder && vertex2.isBorder;
  60047. var error = 0;
  60048. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  60049. if (qDet !== 0 && !border) {
  60050. if (!pointResult) {
  60051. pointResult = BABYLON.Vector3.Zero();
  60052. }
  60053. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  60054. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  60055. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  60056. error = this.vertexError(q, pointResult);
  60057. }
  60058. else {
  60059. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  60060. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  60061. var error1 = this.vertexError(q, vertex1.position);
  60062. var error2 = this.vertexError(q, vertex2.position);
  60063. var error3 = this.vertexError(q, p3);
  60064. error = Math.min(error1, error2, error3);
  60065. if (error === error1) {
  60066. if (pointResult) {
  60067. pointResult.copyFrom(vertex1.position);
  60068. }
  60069. }
  60070. else if (error === error2) {
  60071. if (pointResult) {
  60072. pointResult.copyFrom(vertex2.position);
  60073. }
  60074. }
  60075. else {
  60076. if (pointResult) {
  60077. pointResult.copyFrom(p3);
  60078. }
  60079. }
  60080. }
  60081. return error;
  60082. };
  60083. return QuadraticErrorSimplification;
  60084. }());
  60085. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  60086. })(BABYLON || (BABYLON = {}));
  60087. //# sourceMappingURL=babylon.meshSimplification.js.map
  60088. var BABYLON;
  60089. (function (BABYLON) {
  60090. var Internals;
  60091. (function (Internals) {
  60092. var MeshLODLevel = (function () {
  60093. function MeshLODLevel(distance, mesh) {
  60094. this.distance = distance;
  60095. this.mesh = mesh;
  60096. }
  60097. return MeshLODLevel;
  60098. }());
  60099. Internals.MeshLODLevel = MeshLODLevel;
  60100. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  60101. })(BABYLON || (BABYLON = {}));
  60102. //# sourceMappingURL=babylon.meshLODLevel.js.map
  60103. var BABYLON;
  60104. (function (BABYLON) {
  60105. // Standard optimizations
  60106. var SceneOptimization = (function () {
  60107. function SceneOptimization(priority) {
  60108. if (priority === void 0) { priority = 0; }
  60109. this.priority = priority;
  60110. this.apply = function (scene) {
  60111. return true; // Return true if everything that can be done was applied
  60112. };
  60113. }
  60114. return SceneOptimization;
  60115. }());
  60116. BABYLON.SceneOptimization = SceneOptimization;
  60117. var TextureOptimization = (function (_super) {
  60118. __extends(TextureOptimization, _super);
  60119. function TextureOptimization(priority, maximumSize) {
  60120. if (priority === void 0) { priority = 0; }
  60121. if (maximumSize === void 0) { maximumSize = 1024; }
  60122. var _this = _super.call(this, priority) || this;
  60123. _this.priority = priority;
  60124. _this.maximumSize = maximumSize;
  60125. _this.apply = function (scene) {
  60126. var allDone = true;
  60127. for (var index = 0; index < scene.textures.length; index++) {
  60128. var texture = scene.textures[index];
  60129. if (!texture.canRescale) {
  60130. continue;
  60131. }
  60132. var currentSize = texture.getSize();
  60133. var maxDimension = Math.max(currentSize.width, currentSize.height);
  60134. if (maxDimension > _this.maximumSize) {
  60135. texture.scale(0.5);
  60136. allDone = false;
  60137. }
  60138. }
  60139. return allDone;
  60140. };
  60141. return _this;
  60142. }
  60143. return TextureOptimization;
  60144. }(SceneOptimization));
  60145. BABYLON.TextureOptimization = TextureOptimization;
  60146. var HardwareScalingOptimization = (function (_super) {
  60147. __extends(HardwareScalingOptimization, _super);
  60148. function HardwareScalingOptimization(priority, maximumScale) {
  60149. if (priority === void 0) { priority = 0; }
  60150. if (maximumScale === void 0) { maximumScale = 2; }
  60151. var _this = _super.call(this, priority) || this;
  60152. _this.priority = priority;
  60153. _this.maximumScale = maximumScale;
  60154. _this._currentScale = 1;
  60155. _this.apply = function (scene) {
  60156. _this._currentScale++;
  60157. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  60158. return _this._currentScale >= _this.maximumScale;
  60159. };
  60160. return _this;
  60161. }
  60162. return HardwareScalingOptimization;
  60163. }(SceneOptimization));
  60164. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  60165. var ShadowsOptimization = (function (_super) {
  60166. __extends(ShadowsOptimization, _super);
  60167. function ShadowsOptimization() {
  60168. var _this = _super !== null && _super.apply(this, arguments) || this;
  60169. _this.apply = function (scene) {
  60170. scene.shadowsEnabled = false;
  60171. return true;
  60172. };
  60173. return _this;
  60174. }
  60175. return ShadowsOptimization;
  60176. }(SceneOptimization));
  60177. BABYLON.ShadowsOptimization = ShadowsOptimization;
  60178. var PostProcessesOptimization = (function (_super) {
  60179. __extends(PostProcessesOptimization, _super);
  60180. function PostProcessesOptimization() {
  60181. var _this = _super !== null && _super.apply(this, arguments) || this;
  60182. _this.apply = function (scene) {
  60183. scene.postProcessesEnabled = false;
  60184. return true;
  60185. };
  60186. return _this;
  60187. }
  60188. return PostProcessesOptimization;
  60189. }(SceneOptimization));
  60190. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  60191. var LensFlaresOptimization = (function (_super) {
  60192. __extends(LensFlaresOptimization, _super);
  60193. function LensFlaresOptimization() {
  60194. var _this = _super !== null && _super.apply(this, arguments) || this;
  60195. _this.apply = function (scene) {
  60196. scene.lensFlaresEnabled = false;
  60197. return true;
  60198. };
  60199. return _this;
  60200. }
  60201. return LensFlaresOptimization;
  60202. }(SceneOptimization));
  60203. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  60204. var ParticlesOptimization = (function (_super) {
  60205. __extends(ParticlesOptimization, _super);
  60206. function ParticlesOptimization() {
  60207. var _this = _super !== null && _super.apply(this, arguments) || this;
  60208. _this.apply = function (scene) {
  60209. scene.particlesEnabled = false;
  60210. return true;
  60211. };
  60212. return _this;
  60213. }
  60214. return ParticlesOptimization;
  60215. }(SceneOptimization));
  60216. BABYLON.ParticlesOptimization = ParticlesOptimization;
  60217. var RenderTargetsOptimization = (function (_super) {
  60218. __extends(RenderTargetsOptimization, _super);
  60219. function RenderTargetsOptimization() {
  60220. var _this = _super !== null && _super.apply(this, arguments) || this;
  60221. _this.apply = function (scene) {
  60222. scene.renderTargetsEnabled = false;
  60223. return true;
  60224. };
  60225. return _this;
  60226. }
  60227. return RenderTargetsOptimization;
  60228. }(SceneOptimization));
  60229. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  60230. var MergeMeshesOptimization = (function (_super) {
  60231. __extends(MergeMeshesOptimization, _super);
  60232. function MergeMeshesOptimization() {
  60233. var _this = _super !== null && _super.apply(this, arguments) || this;
  60234. _this._canBeMerged = function (abstractMesh) {
  60235. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  60236. return false;
  60237. }
  60238. var mesh = abstractMesh;
  60239. if (!mesh.isVisible || !mesh.isEnabled()) {
  60240. return false;
  60241. }
  60242. if (mesh.instances.length > 0) {
  60243. return false;
  60244. }
  60245. if (mesh.skeleton || mesh.hasLODLevels) {
  60246. return false;
  60247. }
  60248. if (mesh.parent) {
  60249. return false;
  60250. }
  60251. return true;
  60252. };
  60253. _this.apply = function (scene, updateSelectionTree) {
  60254. var globalPool = scene.meshes.slice(0);
  60255. var globalLength = globalPool.length;
  60256. for (var index = 0; index < globalLength; index++) {
  60257. var currentPool = new Array();
  60258. var current = globalPool[index];
  60259. // Checks
  60260. if (!_this._canBeMerged(current)) {
  60261. continue;
  60262. }
  60263. currentPool.push(current);
  60264. // Find compatible meshes
  60265. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  60266. var otherMesh = globalPool[subIndex];
  60267. if (!_this._canBeMerged(otherMesh)) {
  60268. continue;
  60269. }
  60270. if (otherMesh.material !== current.material) {
  60271. continue;
  60272. }
  60273. if (otherMesh.checkCollisions !== current.checkCollisions) {
  60274. continue;
  60275. }
  60276. currentPool.push(otherMesh);
  60277. globalLength--;
  60278. globalPool.splice(subIndex, 1);
  60279. subIndex--;
  60280. }
  60281. if (currentPool.length < 2) {
  60282. continue;
  60283. }
  60284. // Merge meshes
  60285. BABYLON.Mesh.MergeMeshes(currentPool);
  60286. }
  60287. if (updateSelectionTree != undefined) {
  60288. if (updateSelectionTree) {
  60289. scene.createOrUpdateSelectionOctree();
  60290. }
  60291. }
  60292. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  60293. scene.createOrUpdateSelectionOctree();
  60294. }
  60295. return true;
  60296. };
  60297. return _this;
  60298. }
  60299. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  60300. get: function () {
  60301. return MergeMeshesOptimization._UpdateSelectionTree;
  60302. },
  60303. set: function (value) {
  60304. MergeMeshesOptimization._UpdateSelectionTree = value;
  60305. },
  60306. enumerable: true,
  60307. configurable: true
  60308. });
  60309. return MergeMeshesOptimization;
  60310. }(SceneOptimization));
  60311. MergeMeshesOptimization._UpdateSelectionTree = false;
  60312. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  60313. // Options
  60314. var SceneOptimizerOptions = (function () {
  60315. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  60316. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  60317. if (trackerDuration === void 0) { trackerDuration = 2000; }
  60318. this.targetFrameRate = targetFrameRate;
  60319. this.trackerDuration = trackerDuration;
  60320. this.optimizations = new Array();
  60321. }
  60322. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  60323. var result = new SceneOptimizerOptions(targetFrameRate);
  60324. var priority = 0;
  60325. result.optimizations.push(new MergeMeshesOptimization(priority));
  60326. result.optimizations.push(new ShadowsOptimization(priority));
  60327. result.optimizations.push(new LensFlaresOptimization(priority));
  60328. // Next priority
  60329. priority++;
  60330. result.optimizations.push(new PostProcessesOptimization(priority));
  60331. result.optimizations.push(new ParticlesOptimization(priority));
  60332. // Next priority
  60333. priority++;
  60334. result.optimizations.push(new TextureOptimization(priority, 1024));
  60335. return result;
  60336. };
  60337. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  60338. var result = new SceneOptimizerOptions(targetFrameRate);
  60339. var priority = 0;
  60340. result.optimizations.push(new MergeMeshesOptimization(priority));
  60341. result.optimizations.push(new ShadowsOptimization(priority));
  60342. result.optimizations.push(new LensFlaresOptimization(priority));
  60343. // Next priority
  60344. priority++;
  60345. result.optimizations.push(new PostProcessesOptimization(priority));
  60346. result.optimizations.push(new ParticlesOptimization(priority));
  60347. // Next priority
  60348. priority++;
  60349. result.optimizations.push(new TextureOptimization(priority, 512));
  60350. // Next priority
  60351. priority++;
  60352. result.optimizations.push(new RenderTargetsOptimization(priority));
  60353. // Next priority
  60354. priority++;
  60355. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  60356. return result;
  60357. };
  60358. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  60359. var result = new SceneOptimizerOptions(targetFrameRate);
  60360. var priority = 0;
  60361. result.optimizations.push(new MergeMeshesOptimization(priority));
  60362. result.optimizations.push(new ShadowsOptimization(priority));
  60363. result.optimizations.push(new LensFlaresOptimization(priority));
  60364. // Next priority
  60365. priority++;
  60366. result.optimizations.push(new PostProcessesOptimization(priority));
  60367. result.optimizations.push(new ParticlesOptimization(priority));
  60368. // Next priority
  60369. priority++;
  60370. result.optimizations.push(new TextureOptimization(priority, 256));
  60371. // Next priority
  60372. priority++;
  60373. result.optimizations.push(new RenderTargetsOptimization(priority));
  60374. // Next priority
  60375. priority++;
  60376. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  60377. return result;
  60378. };
  60379. return SceneOptimizerOptions;
  60380. }());
  60381. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  60382. // Scene optimizer tool
  60383. var SceneOptimizer = (function () {
  60384. function SceneOptimizer() {
  60385. }
  60386. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  60387. // TODO: add an epsilon
  60388. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  60389. if (onSuccess) {
  60390. onSuccess();
  60391. }
  60392. return;
  60393. }
  60394. // Apply current level of optimizations
  60395. var allDone = true;
  60396. var noOptimizationApplied = true;
  60397. for (var index = 0; index < options.optimizations.length; index++) {
  60398. var optimization = options.optimizations[index];
  60399. if (optimization.priority === currentPriorityLevel) {
  60400. noOptimizationApplied = false;
  60401. allDone = allDone && optimization.apply(scene);
  60402. }
  60403. }
  60404. // If no optimization was applied, this is a failure :(
  60405. if (noOptimizationApplied) {
  60406. if (onFailure) {
  60407. onFailure();
  60408. }
  60409. return;
  60410. }
  60411. // If all optimizations were done, move to next level
  60412. if (allDone) {
  60413. currentPriorityLevel++;
  60414. }
  60415. // Let's the system running for a specific amount of time before checking FPS
  60416. scene.executeWhenReady(function () {
  60417. setTimeout(function () {
  60418. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  60419. }, options.trackerDuration);
  60420. });
  60421. };
  60422. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  60423. if (!options) {
  60424. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  60425. }
  60426. // Let's the system running for a specific amount of time before checking FPS
  60427. scene.executeWhenReady(function () {
  60428. setTimeout(function () {
  60429. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  60430. }, options.trackerDuration);
  60431. });
  60432. };
  60433. return SceneOptimizer;
  60434. }());
  60435. BABYLON.SceneOptimizer = SceneOptimizer;
  60436. })(BABYLON || (BABYLON = {}));
  60437. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  60438. var BABYLON;
  60439. (function (BABYLON) {
  60440. var OutlineRenderer = (function () {
  60441. function OutlineRenderer(scene) {
  60442. this._scene = scene;
  60443. }
  60444. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  60445. var _this = this;
  60446. if (useOverlay === void 0) { useOverlay = false; }
  60447. var scene = this._scene;
  60448. var engine = this._scene.getEngine();
  60449. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60450. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  60451. return;
  60452. }
  60453. var mesh = subMesh.getRenderingMesh();
  60454. var material = subMesh.getMaterial();
  60455. engine.enableEffect(this._effect);
  60456. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  60457. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  60458. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  60459. // Bones
  60460. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60461. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60462. }
  60463. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60464. // Alpha test
  60465. if (material && material.needAlphaTesting()) {
  60466. var alphaTexture = material.getAlphaTestTexture();
  60467. this._effect.setTexture("diffuseSampler", alphaTexture);
  60468. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60469. }
  60470. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  60471. };
  60472. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  60473. var defines = [];
  60474. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  60475. var mesh = subMesh.getMesh();
  60476. var material = subMesh.getMaterial();
  60477. // Alpha test
  60478. if (material && material.needAlphaTesting()) {
  60479. defines.push("#define ALPHATEST");
  60480. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60481. attribs.push(BABYLON.VertexBuffer.UVKind);
  60482. defines.push("#define UV1");
  60483. }
  60484. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60485. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60486. defines.push("#define UV2");
  60487. }
  60488. }
  60489. // Bones
  60490. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60491. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60492. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60493. if (mesh.numBoneInfluencers > 4) {
  60494. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60495. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60496. }
  60497. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60498. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60499. }
  60500. else {
  60501. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60502. }
  60503. // Instances
  60504. if (useInstances) {
  60505. defines.push("#define INSTANCES");
  60506. attribs.push("world0");
  60507. attribs.push("world1");
  60508. attribs.push("world2");
  60509. attribs.push("world3");
  60510. }
  60511. // Get correct effect
  60512. var join = defines.join("\n");
  60513. if (this._cachedDefines !== join) {
  60514. this._cachedDefines = join;
  60515. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  60516. }
  60517. return this._effect.isReady();
  60518. };
  60519. return OutlineRenderer;
  60520. }());
  60521. BABYLON.OutlineRenderer = OutlineRenderer;
  60522. })(BABYLON || (BABYLON = {}));
  60523. //# sourceMappingURL=babylon.outlineRenderer.js.map
  60524. var BABYLON;
  60525. (function (BABYLON) {
  60526. var FaceAdjacencies = (function () {
  60527. function FaceAdjacencies() {
  60528. this.edges = new Array();
  60529. this.edgesConnectedCount = 0;
  60530. }
  60531. return FaceAdjacencies;
  60532. }());
  60533. var EdgesRenderer = (function () {
  60534. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  60535. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  60536. if (epsilon === void 0) { epsilon = 0.95; }
  60537. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  60538. this.edgesWidthScalerForOrthographic = 1000.0;
  60539. this.edgesWidthScalerForPerspective = 50.0;
  60540. this._linesPositions = new Array();
  60541. this._linesNormals = new Array();
  60542. this._linesIndices = new Array();
  60543. this._buffers = {};
  60544. this._checkVerticesInsteadOfIndices = false;
  60545. this._source = source;
  60546. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  60547. this._epsilon = epsilon;
  60548. this._prepareRessources();
  60549. this._generateEdgesLines();
  60550. }
  60551. EdgesRenderer.prototype._prepareRessources = function () {
  60552. if (this._lineShader) {
  60553. return;
  60554. }
  60555. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  60556. attributes: ["position", "normal"],
  60557. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  60558. });
  60559. this._lineShader.disableDepthWrite = true;
  60560. this._lineShader.backFaceCulling = false;
  60561. };
  60562. EdgesRenderer.prototype.dispose = function () {
  60563. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  60564. if (buffer) {
  60565. buffer.dispose();
  60566. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  60567. }
  60568. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  60569. if (buffer) {
  60570. buffer.dispose();
  60571. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  60572. }
  60573. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  60574. this._lineShader.dispose();
  60575. };
  60576. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  60577. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  60578. return 0;
  60579. }
  60580. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  60581. return 1;
  60582. }
  60583. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  60584. return 2;
  60585. }
  60586. return -1;
  60587. };
  60588. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  60589. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  60590. return 0;
  60591. }
  60592. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  60593. return 1;
  60594. }
  60595. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  60596. return 2;
  60597. }
  60598. return -1;
  60599. };
  60600. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  60601. var needToCreateLine;
  60602. if (edge === undefined) {
  60603. needToCreateLine = true;
  60604. }
  60605. else {
  60606. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  60607. needToCreateLine = dotProduct < this._epsilon;
  60608. }
  60609. if (needToCreateLine) {
  60610. var offset = this._linesPositions.length / 3;
  60611. var normal = p0.subtract(p1);
  60612. normal.normalize();
  60613. // Positions
  60614. this._linesPositions.push(p0.x);
  60615. this._linesPositions.push(p0.y);
  60616. this._linesPositions.push(p0.z);
  60617. this._linesPositions.push(p0.x);
  60618. this._linesPositions.push(p0.y);
  60619. this._linesPositions.push(p0.z);
  60620. this._linesPositions.push(p1.x);
  60621. this._linesPositions.push(p1.y);
  60622. this._linesPositions.push(p1.z);
  60623. this._linesPositions.push(p1.x);
  60624. this._linesPositions.push(p1.y);
  60625. this._linesPositions.push(p1.z);
  60626. // Normals
  60627. this._linesNormals.push(p1.x);
  60628. this._linesNormals.push(p1.y);
  60629. this._linesNormals.push(p1.z);
  60630. this._linesNormals.push(-1);
  60631. this._linesNormals.push(p1.x);
  60632. this._linesNormals.push(p1.y);
  60633. this._linesNormals.push(p1.z);
  60634. this._linesNormals.push(1);
  60635. this._linesNormals.push(p0.x);
  60636. this._linesNormals.push(p0.y);
  60637. this._linesNormals.push(p0.z);
  60638. this._linesNormals.push(-1);
  60639. this._linesNormals.push(p0.x);
  60640. this._linesNormals.push(p0.y);
  60641. this._linesNormals.push(p0.z);
  60642. this._linesNormals.push(1);
  60643. // Indices
  60644. this._linesIndices.push(offset);
  60645. this._linesIndices.push(offset + 1);
  60646. this._linesIndices.push(offset + 2);
  60647. this._linesIndices.push(offset);
  60648. this._linesIndices.push(offset + 2);
  60649. this._linesIndices.push(offset + 3);
  60650. }
  60651. };
  60652. EdgesRenderer.prototype._generateEdgesLines = function () {
  60653. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60654. var indices = this._source.getIndices();
  60655. // First let's find adjacencies
  60656. var adjacencies = new Array();
  60657. var faceNormals = new Array();
  60658. var index;
  60659. var faceAdjacencies;
  60660. // Prepare faces
  60661. for (index = 0; index < indices.length; index += 3) {
  60662. faceAdjacencies = new FaceAdjacencies();
  60663. var p0Index = indices[index];
  60664. var p1Index = indices[index + 1];
  60665. var p2Index = indices[index + 2];
  60666. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  60667. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  60668. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  60669. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  60670. faceNormal.normalize();
  60671. faceNormals.push(faceNormal);
  60672. adjacencies.push(faceAdjacencies);
  60673. }
  60674. // Scan
  60675. for (index = 0; index < adjacencies.length; index++) {
  60676. faceAdjacencies = adjacencies[index];
  60677. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  60678. var otherFaceAdjacencies = adjacencies[otherIndex];
  60679. if (faceAdjacencies.edgesConnectedCount === 3) {
  60680. break;
  60681. }
  60682. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  60683. continue;
  60684. }
  60685. var otherP0 = indices[otherIndex * 3];
  60686. var otherP1 = indices[otherIndex * 3 + 1];
  60687. var otherP2 = indices[otherIndex * 3 + 2];
  60688. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  60689. var otherEdgeIndex;
  60690. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  60691. continue;
  60692. }
  60693. switch (edgeIndex) {
  60694. case 0:
  60695. if (this._checkVerticesInsteadOfIndices) {
  60696. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  60697. }
  60698. else {
  60699. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  60700. }
  60701. break;
  60702. case 1:
  60703. if (this._checkVerticesInsteadOfIndices) {
  60704. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  60705. }
  60706. else {
  60707. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  60708. }
  60709. break;
  60710. case 2:
  60711. if (this._checkVerticesInsteadOfIndices) {
  60712. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  60713. }
  60714. else {
  60715. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  60716. }
  60717. break;
  60718. }
  60719. if (otherEdgeIndex === -1) {
  60720. continue;
  60721. }
  60722. faceAdjacencies.edges[edgeIndex] = otherIndex;
  60723. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  60724. faceAdjacencies.edgesConnectedCount++;
  60725. otherFaceAdjacencies.edgesConnectedCount++;
  60726. if (faceAdjacencies.edgesConnectedCount === 3) {
  60727. break;
  60728. }
  60729. }
  60730. }
  60731. }
  60732. // Create lines
  60733. for (index = 0; index < adjacencies.length; index++) {
  60734. // 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
  60735. var current = adjacencies[index];
  60736. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  60737. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  60738. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  60739. }
  60740. // Merge into a single mesh
  60741. var engine = this._source.getScene().getEngine();
  60742. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  60743. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  60744. this._ib = engine.createIndexBuffer(this._linesIndices);
  60745. this._indicesCount = this._linesIndices.length;
  60746. };
  60747. EdgesRenderer.prototype.render = function () {
  60748. if (!this._lineShader.isReady()) {
  60749. return;
  60750. }
  60751. var scene = this._source.getScene();
  60752. var engine = scene.getEngine();
  60753. this._lineShader._preBind();
  60754. // VBOs
  60755. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  60756. scene.resetCachedMaterial();
  60757. this._lineShader.setColor4("color", this._source.edgesColor);
  60758. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  60759. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  60760. }
  60761. else {
  60762. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  60763. }
  60764. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  60765. this._lineShader.bind(this._source.getWorldMatrix());
  60766. // Draw order
  60767. engine.draw(true, 0, this._indicesCount);
  60768. this._lineShader.unbind();
  60769. engine.setDepthWrite(true);
  60770. };
  60771. return EdgesRenderer;
  60772. }());
  60773. BABYLON.EdgesRenderer = EdgesRenderer;
  60774. })(BABYLON || (BABYLON = {}));
  60775. //# sourceMappingURL=babylon.edgesRenderer.js.map
  60776. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  60777. /// <reference path="..\Math\babylon.math.ts" />
  60778. var BABYLON;
  60779. (function (BABYLON) {
  60780. /**
  60781. * Special Glow Blur post process only blurring the alpha channel
  60782. * It enforces keeping the most luminous color in the color channel.
  60783. */
  60784. var GlowBlurPostProcess = (function (_super) {
  60785. __extends(GlowBlurPostProcess, _super);
  60786. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  60787. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60788. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  60789. _this.direction = direction;
  60790. _this.blurWidth = blurWidth;
  60791. _this.onApplyObservable.add(function (effect) {
  60792. effect.setFloat2("screenSize", _this.width, _this.height);
  60793. effect.setVector2("direction", _this.direction);
  60794. effect.setFloat("blurWidth", _this.blurWidth);
  60795. });
  60796. return _this;
  60797. }
  60798. return GlowBlurPostProcess;
  60799. }(BABYLON.PostProcess));
  60800. /**
  60801. * The highlight layer Helps adding a glow effect around a mesh.
  60802. *
  60803. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  60804. * glowy meshes to your scene.
  60805. *
  60806. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  60807. */
  60808. var HighlightLayer = (function () {
  60809. /**
  60810. * Instantiates a new highlight Layer and references it to the scene..
  60811. * @param name The name of the layer
  60812. * @param scene The scene to use the layer in
  60813. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  60814. */
  60815. function HighlightLayer(name, scene, options) {
  60816. this.name = name;
  60817. this._vertexBuffers = {};
  60818. this._mainTextureDesiredSize = { width: 0, height: 0 };
  60819. this._meshes = {};
  60820. this._maxSize = 0;
  60821. this._shouldRender = false;
  60822. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  60823. this._excludedMeshes = {};
  60824. /**
  60825. * Specifies whether or not the inner glow is ACTIVE in the layer.
  60826. */
  60827. this.innerGlow = true;
  60828. /**
  60829. * Specifies whether or not the outer glow is ACTIVE in the layer.
  60830. */
  60831. this.outerGlow = true;
  60832. /**
  60833. * Specifies wether the highlight layer is enabled or not.
  60834. */
  60835. this.isEnabled = true;
  60836. /**
  60837. * An event triggered when the highlight layer has been disposed.
  60838. * @type {BABYLON.Observable}
  60839. */
  60840. this.onDisposeObservable = new BABYLON.Observable();
  60841. /**
  60842. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  60843. * @type {BABYLON.Observable}
  60844. */
  60845. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  60846. /**
  60847. * An event triggered when the highlight layer is being blurred.
  60848. * @type {BABYLON.Observable}
  60849. */
  60850. this.onBeforeBlurObservable = new BABYLON.Observable();
  60851. /**
  60852. * An event triggered when the highlight layer has been blurred.
  60853. * @type {BABYLON.Observable}
  60854. */
  60855. this.onAfterBlurObservable = new BABYLON.Observable();
  60856. /**
  60857. * An event triggered when the glowing blurred texture is being merged in the scene.
  60858. * @type {BABYLON.Observable}
  60859. */
  60860. this.onBeforeComposeObservable = new BABYLON.Observable();
  60861. /**
  60862. * An event triggered when the glowing blurred texture has been merged in the scene.
  60863. * @type {BABYLON.Observable}
  60864. */
  60865. this.onAfterComposeObservable = new BABYLON.Observable();
  60866. /**
  60867. * An event triggered when the highlight layer changes its size.
  60868. * @type {BABYLON.Observable}
  60869. */
  60870. this.onSizeChangedObservable = new BABYLON.Observable();
  60871. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60872. var engine = scene.getEngine();
  60873. this._engine = engine;
  60874. this._maxSize = this._engine.getCaps().maxTextureSize;
  60875. this._scene.highlightLayers.push(this);
  60876. // Warn on stencil.
  60877. if (!this._engine.isStencilEnable) {
  60878. 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 }");
  60879. }
  60880. // Adapt options
  60881. this._options = options || {
  60882. mainTextureRatio: 0.25,
  60883. blurTextureSizeRatio: 0.5,
  60884. blurHorizontalSize: 1,
  60885. blurVerticalSize: 1,
  60886. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  60887. };
  60888. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  60889. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  60890. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  60891. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  60892. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  60893. // VBO
  60894. var vertices = [];
  60895. vertices.push(1, 1);
  60896. vertices.push(-1, 1);
  60897. vertices.push(-1, -1);
  60898. vertices.push(1, -1);
  60899. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  60900. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  60901. // Indices
  60902. var indices = [];
  60903. indices.push(0);
  60904. indices.push(1);
  60905. indices.push(2);
  60906. indices.push(0);
  60907. indices.push(2);
  60908. indices.push(3);
  60909. this._indexBuffer = engine.createIndexBuffer(indices);
  60910. // Effect
  60911. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  60912. // Render target
  60913. this.setMainTextureSize();
  60914. // Create Textures and post processes
  60915. this.createTextureAndPostProcesses();
  60916. }
  60917. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  60918. /**
  60919. * Gets the horizontal size of the blur.
  60920. */
  60921. get: function () {
  60922. return this._horizontalBlurPostprocess.blurWidth;
  60923. },
  60924. /**
  60925. * Specifies the horizontal size of the blur.
  60926. */
  60927. set: function (value) {
  60928. this._horizontalBlurPostprocess.blurWidth = value;
  60929. },
  60930. enumerable: true,
  60931. configurable: true
  60932. });
  60933. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  60934. /**
  60935. * Gets the vertical size of the blur.
  60936. */
  60937. get: function () {
  60938. return this._verticalBlurPostprocess.blurWidth;
  60939. },
  60940. /**
  60941. * Specifies the vertical size of the blur.
  60942. */
  60943. set: function (value) {
  60944. this._verticalBlurPostprocess.blurWidth = value;
  60945. },
  60946. enumerable: true,
  60947. configurable: true
  60948. });
  60949. Object.defineProperty(HighlightLayer.prototype, "camera", {
  60950. /**
  60951. * Gets the camera attached to the layer.
  60952. */
  60953. get: function () {
  60954. return this._options.camera;
  60955. },
  60956. enumerable: true,
  60957. configurable: true
  60958. });
  60959. /**
  60960. * Creates the render target textures and post processes used in the highlight layer.
  60961. */
  60962. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  60963. var _this = this;
  60964. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  60965. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  60966. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  60967. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  60968. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  60969. width: this._mainTextureDesiredSize.width,
  60970. height: this._mainTextureDesiredSize.height
  60971. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  60972. this._mainTexture.activeCamera = this._options.camera;
  60973. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60974. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60975. this._mainTexture.anisotropicFilteringLevel = 1;
  60976. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60977. this._mainTexture.renderParticles = false;
  60978. this._mainTexture.renderList = null;
  60979. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  60980. width: blurTextureWidth,
  60981. height: blurTextureHeight
  60982. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  60983. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60984. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60985. this._blurTexture.anisotropicFilteringLevel = 16;
  60986. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60987. this._blurTexture.renderParticles = false;
  60988. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  60989. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  60990. effect.setTexture("textureSampler", _this._mainTexture);
  60991. });
  60992. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  60993. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  60994. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  60995. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  60996. });
  60997. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  60998. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  60999. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  61000. });
  61001. }
  61002. else {
  61003. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  61004. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  61005. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  61006. });
  61007. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  61008. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  61009. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  61010. });
  61011. }
  61012. this._mainTexture.onAfterUnbindObservable.add(function () {
  61013. _this.onBeforeBlurObservable.notifyObservers(_this);
  61014. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  61015. _this.onAfterBlurObservable.notifyObservers(_this);
  61016. });
  61017. // Custom render function
  61018. var renderSubMesh = function (subMesh) {
  61019. var mesh = subMesh.getRenderingMesh();
  61020. var scene = _this._scene;
  61021. var engine = scene.getEngine();
  61022. // Culling
  61023. engine.setState(subMesh.getMaterial().backFaceCulling);
  61024. // Managing instances
  61025. var batch = mesh._getInstancesRenderList(subMesh._id);
  61026. if (batch.mustReturn) {
  61027. return;
  61028. }
  61029. // Excluded Mesh
  61030. if (_this._excludedMeshes[mesh.uniqueId]) {
  61031. return;
  61032. }
  61033. ;
  61034. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61035. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  61036. var material = subMesh.getMaterial();
  61037. var emissiveTexture = null;
  61038. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  61039. emissiveTexture = material.emissiveTexture;
  61040. }
  61041. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  61042. engine.enableEffect(_this._glowMapGenerationEffect);
  61043. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  61044. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  61045. if (highlightLayerMesh) {
  61046. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  61047. }
  61048. else {
  61049. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  61050. }
  61051. // Alpha test
  61052. if (material && material.needAlphaTesting()) {
  61053. var alphaTexture = material.getAlphaTestTexture();
  61054. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  61055. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61056. }
  61057. // Glow emissive only
  61058. if (emissiveTexture) {
  61059. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  61060. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  61061. }
  61062. // Bones
  61063. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61064. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61065. }
  61066. // Draw
  61067. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  61068. }
  61069. else {
  61070. // Need to reset refresh rate of the shadowMap
  61071. _this._mainTexture.resetRefreshCounter();
  61072. }
  61073. };
  61074. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  61075. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  61076. var index;
  61077. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61078. renderSubMesh(opaqueSubMeshes.data[index]);
  61079. }
  61080. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61081. renderSubMesh(alphaTestSubMeshes.data[index]);
  61082. }
  61083. for (index = 0; index < transparentSubMeshes.length; index++) {
  61084. renderSubMesh(transparentSubMeshes.data[index]);
  61085. }
  61086. };
  61087. this._mainTexture.onClearObservable.add(function (engine) {
  61088. engine.clear(HighlightLayer.neutralColor, true, true, true);
  61089. });
  61090. };
  61091. /**
  61092. * Checks for the readiness of the element composing the layer.
  61093. * @param subMesh the mesh to check for
  61094. * @param useInstances specify wether or not to use instances to render the mesh
  61095. * @param emissiveTexture the associated emissive texture used to generate the glow
  61096. * @return true if ready otherwise, false
  61097. */
  61098. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  61099. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  61100. return false;
  61101. }
  61102. var defines = [];
  61103. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61104. var mesh = subMesh.getMesh();
  61105. var material = subMesh.getMaterial();
  61106. var uv1 = false;
  61107. var uv2 = false;
  61108. // Alpha test
  61109. if (material && material.needAlphaTesting()) {
  61110. var alphaTexture = material.getAlphaTestTexture();
  61111. if (alphaTexture) {
  61112. defines.push("#define ALPHATEST");
  61113. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  61114. alphaTexture.coordinatesIndex === 1) {
  61115. defines.push("#define DIFFUSEUV2");
  61116. uv2 = true;
  61117. }
  61118. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61119. defines.push("#define DIFFUSEUV1");
  61120. uv1 = true;
  61121. }
  61122. }
  61123. }
  61124. // Emissive
  61125. if (emissiveTexture) {
  61126. defines.push("#define EMISSIVE");
  61127. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  61128. emissiveTexture.coordinatesIndex === 1) {
  61129. defines.push("#define EMISSIVEUV2");
  61130. uv2 = true;
  61131. }
  61132. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61133. defines.push("#define EMISSIVEUV1");
  61134. uv1 = true;
  61135. }
  61136. }
  61137. if (uv1) {
  61138. attribs.push(BABYLON.VertexBuffer.UVKind);
  61139. defines.push("#define UV1");
  61140. }
  61141. if (uv2) {
  61142. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61143. defines.push("#define UV2");
  61144. }
  61145. // Bones
  61146. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61147. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61148. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61149. if (mesh.numBoneInfluencers > 4) {
  61150. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61151. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61152. }
  61153. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61154. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61155. }
  61156. else {
  61157. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61158. }
  61159. // Instances
  61160. if (useInstances) {
  61161. defines.push("#define INSTANCES");
  61162. attribs.push("world0");
  61163. attribs.push("world1");
  61164. attribs.push("world2");
  61165. attribs.push("world3");
  61166. }
  61167. // Get correct effect
  61168. var join = defines.join("\n");
  61169. if (this._cachedDefines !== join) {
  61170. this._cachedDefines = join;
  61171. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  61172. }
  61173. return this._glowMapGenerationEffect.isReady();
  61174. };
  61175. /**
  61176. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  61177. */
  61178. HighlightLayer.prototype.render = function () {
  61179. var currentEffect = this._glowMapMergeEffect;
  61180. // Check
  61181. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  61182. return;
  61183. var engine = this._scene.getEngine();
  61184. this.onBeforeComposeObservable.notifyObservers(this);
  61185. // Render
  61186. engine.enableEffect(currentEffect);
  61187. engine.setState(false);
  61188. // Cache
  61189. var previousStencilBuffer = engine.getStencilBuffer();
  61190. var previousStencilFunction = engine.getStencilFunction();
  61191. var previousStencilMask = engine.getStencilMask();
  61192. var previousAlphaMode = engine.getAlphaMode();
  61193. // Texture
  61194. currentEffect.setTexture("textureSampler", this._blurTexture);
  61195. // VBOs
  61196. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  61197. // Draw order
  61198. engine.setAlphaMode(this._options.alphaBlendingMode);
  61199. engine.setStencilMask(0x00);
  61200. engine.setStencilBuffer(true);
  61201. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  61202. if (this.outerGlow) {
  61203. currentEffect.setFloat("offset", 0);
  61204. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  61205. engine.draw(true, 0, 6);
  61206. }
  61207. if (this.innerGlow) {
  61208. currentEffect.setFloat("offset", 1);
  61209. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  61210. engine.draw(true, 0, 6);
  61211. }
  61212. // Restore Cache
  61213. engine.setStencilFunction(previousStencilFunction);
  61214. engine.setStencilMask(previousStencilMask);
  61215. engine.setAlphaMode(previousAlphaMode);
  61216. engine.setStencilBuffer(previousStencilBuffer);
  61217. this.onAfterComposeObservable.notifyObservers(this);
  61218. // Handle size changes.
  61219. var size = this._mainTexture.getSize();
  61220. this.setMainTextureSize();
  61221. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  61222. // Recreate RTT and post processes on size change.
  61223. this.onSizeChangedObservable.notifyObservers(this);
  61224. this.disposeTextureAndPostProcesses();
  61225. this.createTextureAndPostProcesses();
  61226. }
  61227. };
  61228. /**
  61229. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  61230. * @param mesh The mesh to exclude from the highlight layer
  61231. */
  61232. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  61233. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  61234. if (!meshExcluded) {
  61235. this._excludedMeshes[mesh.uniqueId] = {
  61236. mesh: mesh,
  61237. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  61238. mesh.getEngine().setStencilBuffer(false);
  61239. }),
  61240. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  61241. mesh.getEngine().setStencilBuffer(true);
  61242. }),
  61243. };
  61244. }
  61245. };
  61246. /**
  61247. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  61248. * @param mesh The mesh to highlight
  61249. */
  61250. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  61251. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  61252. if (meshExcluded) {
  61253. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  61254. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  61255. }
  61256. this._excludedMeshes[mesh.uniqueId] = undefined;
  61257. };
  61258. /**
  61259. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  61260. * @param mesh The mesh to highlight
  61261. * @param color The color of the highlight
  61262. * @param glowEmissiveOnly Extract the glow from the emissive texture
  61263. */
  61264. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  61265. var _this = this;
  61266. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  61267. var meshHighlight = this._meshes[mesh.uniqueId];
  61268. if (meshHighlight) {
  61269. meshHighlight.color = color;
  61270. }
  61271. else {
  61272. this._meshes[mesh.uniqueId] = {
  61273. mesh: mesh,
  61274. color: color,
  61275. // Lambda required for capture due to Observable this context
  61276. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  61277. if (_this._excludedMeshes[mesh.uniqueId]) {
  61278. _this.defaultStencilReference(mesh);
  61279. }
  61280. else {
  61281. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  61282. }
  61283. }),
  61284. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  61285. glowEmissiveOnly: glowEmissiveOnly
  61286. };
  61287. }
  61288. this._shouldRender = true;
  61289. };
  61290. /**
  61291. * Remove a mesh from the highlight layer in order to make it stop glowing.
  61292. * @param mesh The mesh to highlight
  61293. */
  61294. HighlightLayer.prototype.removeMesh = function (mesh) {
  61295. var meshHighlight = this._meshes[mesh.uniqueId];
  61296. if (meshHighlight) {
  61297. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  61298. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  61299. }
  61300. this._meshes[mesh.uniqueId] = undefined;
  61301. this._shouldRender = false;
  61302. for (var meshHighlightToCheck in this._meshes) {
  61303. if (meshHighlightToCheck) {
  61304. this._shouldRender = true;
  61305. break;
  61306. }
  61307. }
  61308. };
  61309. /**
  61310. * Returns true if the layer contains information to display, otherwise false.
  61311. */
  61312. HighlightLayer.prototype.shouldRender = function () {
  61313. return this.isEnabled && this._shouldRender;
  61314. };
  61315. /**
  61316. * Sets the main texture desired size which is the closest power of two
  61317. * of the engine canvas size.
  61318. */
  61319. HighlightLayer.prototype.setMainTextureSize = function () {
  61320. if (this._options.mainTextureFixedSize) {
  61321. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  61322. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  61323. }
  61324. else {
  61325. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  61326. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  61327. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  61328. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  61329. }
  61330. };
  61331. /**
  61332. * Force the stencil to the normal expected value for none glowing parts
  61333. */
  61334. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  61335. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  61336. };
  61337. /**
  61338. * Dispose only the render target textures and post process.
  61339. */
  61340. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  61341. this._blurTexture.dispose();
  61342. this._mainTexture.dispose();
  61343. this._downSamplePostprocess.dispose();
  61344. this._horizontalBlurPostprocess.dispose();
  61345. this._verticalBlurPostprocess.dispose();
  61346. };
  61347. /**
  61348. * Dispose the highlight layer and free resources.
  61349. */
  61350. HighlightLayer.prototype.dispose = function () {
  61351. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61352. if (vertexBuffer) {
  61353. vertexBuffer.dispose();
  61354. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61355. }
  61356. if (this._indexBuffer) {
  61357. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61358. this._indexBuffer = null;
  61359. }
  61360. // Clean textures and post processes
  61361. this.disposeTextureAndPostProcesses();
  61362. // Clean mesh references
  61363. for (var id in this._meshes) {
  61364. var meshHighlight = this._meshes[id];
  61365. if (meshHighlight && meshHighlight.mesh) {
  61366. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  61367. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  61368. }
  61369. }
  61370. this._meshes = null;
  61371. for (var id in this._excludedMeshes) {
  61372. var meshHighlight = this._excludedMeshes[id];
  61373. if (meshHighlight) {
  61374. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  61375. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  61376. }
  61377. }
  61378. this._excludedMeshes = null;
  61379. // Remove from scene
  61380. var index = this._scene.highlightLayers.indexOf(this, 0);
  61381. if (index > -1) {
  61382. this._scene.highlightLayers.splice(index, 1);
  61383. }
  61384. // Callback
  61385. this.onDisposeObservable.notifyObservers(this);
  61386. this.onDisposeObservable.clear();
  61387. this.onBeforeRenderMainTextureObservable.clear();
  61388. this.onBeforeBlurObservable.clear();
  61389. this.onBeforeComposeObservable.clear();
  61390. this.onAfterComposeObservable.clear();
  61391. this.onSizeChangedObservable.clear();
  61392. };
  61393. return HighlightLayer;
  61394. }());
  61395. /**
  61396. * The neutral color used during the preparation of the glow effect.
  61397. * This is black by default as the blend operation is a blend operation.
  61398. */
  61399. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  61400. /**
  61401. * Stencil value used for glowing meshes.
  61402. */
  61403. HighlightLayer.glowingMeshStencilReference = 0x02;
  61404. /**
  61405. * Stencil value used for the other meshes in the scene.
  61406. */
  61407. HighlightLayer.normalMeshStencilReference = 0x01;
  61408. BABYLON.HighlightLayer = HighlightLayer;
  61409. })(BABYLON || (BABYLON = {}));
  61410. //# sourceMappingURL=babylon.highlightlayer.js.map
  61411. var BABYLON;
  61412. (function (BABYLON) {
  61413. var MeshAssetTask = (function () {
  61414. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  61415. this.name = name;
  61416. this.meshesNames = meshesNames;
  61417. this.rootUrl = rootUrl;
  61418. this.sceneFilename = sceneFilename;
  61419. this.isCompleted = false;
  61420. }
  61421. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61422. var _this = this;
  61423. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61424. _this.loadedMeshes = meshes;
  61425. _this.loadedParticleSystems = particleSystems;
  61426. _this.loadedSkeletons = skeletons;
  61427. _this.isCompleted = true;
  61428. if (_this.onSuccess) {
  61429. _this.onSuccess(_this);
  61430. }
  61431. onSuccess();
  61432. }, null, function () {
  61433. if (_this.onError) {
  61434. _this.onError(_this);
  61435. }
  61436. onError();
  61437. });
  61438. };
  61439. return MeshAssetTask;
  61440. }());
  61441. BABYLON.MeshAssetTask = MeshAssetTask;
  61442. var TextFileAssetTask = (function () {
  61443. function TextFileAssetTask(name, url) {
  61444. this.name = name;
  61445. this.url = url;
  61446. this.isCompleted = false;
  61447. }
  61448. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61449. var _this = this;
  61450. BABYLON.Tools.LoadFile(this.url, function (data) {
  61451. _this.text = data;
  61452. _this.isCompleted = true;
  61453. if (_this.onSuccess) {
  61454. _this.onSuccess(_this);
  61455. }
  61456. onSuccess();
  61457. }, null, scene.database, false, function () {
  61458. if (_this.onError) {
  61459. _this.onError(_this);
  61460. }
  61461. onError();
  61462. });
  61463. };
  61464. return TextFileAssetTask;
  61465. }());
  61466. BABYLON.TextFileAssetTask = TextFileAssetTask;
  61467. var BinaryFileAssetTask = (function () {
  61468. function BinaryFileAssetTask(name, url) {
  61469. this.name = name;
  61470. this.url = url;
  61471. this.isCompleted = false;
  61472. }
  61473. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61474. var _this = this;
  61475. BABYLON.Tools.LoadFile(this.url, function (data) {
  61476. _this.data = data;
  61477. _this.isCompleted = true;
  61478. if (_this.onSuccess) {
  61479. _this.onSuccess(_this);
  61480. }
  61481. onSuccess();
  61482. }, null, scene.database, true, function () {
  61483. if (_this.onError) {
  61484. _this.onError(_this);
  61485. }
  61486. onError();
  61487. });
  61488. };
  61489. return BinaryFileAssetTask;
  61490. }());
  61491. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  61492. var ImageAssetTask = (function () {
  61493. function ImageAssetTask(name, url) {
  61494. this.name = name;
  61495. this.url = url;
  61496. this.isCompleted = false;
  61497. }
  61498. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61499. var _this = this;
  61500. var img = new Image();
  61501. BABYLON.Tools.SetCorsBehavior(this.url, img);
  61502. img.onload = function () {
  61503. _this.image = img;
  61504. _this.isCompleted = true;
  61505. if (_this.onSuccess) {
  61506. _this.onSuccess(_this);
  61507. }
  61508. onSuccess();
  61509. };
  61510. img.onerror = function () {
  61511. if (_this.onError) {
  61512. _this.onError(_this);
  61513. }
  61514. onError();
  61515. };
  61516. img.src = this.url;
  61517. };
  61518. return ImageAssetTask;
  61519. }());
  61520. BABYLON.ImageAssetTask = ImageAssetTask;
  61521. var TextureAssetTask = (function () {
  61522. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  61523. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61524. this.name = name;
  61525. this.url = url;
  61526. this.noMipmap = noMipmap;
  61527. this.invertY = invertY;
  61528. this.samplingMode = samplingMode;
  61529. this.isCompleted = false;
  61530. }
  61531. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61532. var _this = this;
  61533. var onload = function () {
  61534. _this.isCompleted = true;
  61535. if (_this.onSuccess) {
  61536. _this.onSuccess(_this);
  61537. }
  61538. onSuccess();
  61539. };
  61540. var onerror = function () {
  61541. if (_this.onError) {
  61542. _this.onError(_this);
  61543. }
  61544. onError();
  61545. };
  61546. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  61547. };
  61548. return TextureAssetTask;
  61549. }());
  61550. BABYLON.TextureAssetTask = TextureAssetTask;
  61551. var CubeTextureAssetTask = (function () {
  61552. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  61553. this.name = name;
  61554. this.url = url;
  61555. this.extensions = extensions;
  61556. this.noMipmap = noMipmap;
  61557. this.files = files;
  61558. this.isCompleted = false;
  61559. }
  61560. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61561. var _this = this;
  61562. var onload = function () {
  61563. _this.isCompleted = true;
  61564. if (_this.onSuccess) {
  61565. _this.onSuccess(_this);
  61566. }
  61567. onSuccess();
  61568. };
  61569. var onerror = function () {
  61570. if (_this.onError) {
  61571. _this.onError(_this);
  61572. }
  61573. onError();
  61574. };
  61575. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  61576. };
  61577. return CubeTextureAssetTask;
  61578. }());
  61579. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  61580. var HDRCubeTextureAssetTask = (function () {
  61581. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  61582. if (noMipmap === void 0) { noMipmap = false; }
  61583. if (generateHarmonics === void 0) { generateHarmonics = true; }
  61584. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  61585. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  61586. this.name = name;
  61587. this.url = url;
  61588. this.size = size;
  61589. this.noMipmap = noMipmap;
  61590. this.generateHarmonics = generateHarmonics;
  61591. this.useInGammaSpace = useInGammaSpace;
  61592. this.usePMREMGenerator = usePMREMGenerator;
  61593. this.isCompleted = false;
  61594. }
  61595. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61596. var _this = this;
  61597. var onload = function () {
  61598. _this.isCompleted = true;
  61599. if (_this.onSuccess) {
  61600. _this.onSuccess(_this);
  61601. }
  61602. onSuccess();
  61603. };
  61604. var onerror = function () {
  61605. if (_this.onError) {
  61606. _this.onError(_this);
  61607. }
  61608. onError();
  61609. };
  61610. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  61611. };
  61612. return HDRCubeTextureAssetTask;
  61613. }());
  61614. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  61615. var AssetsManager = (function () {
  61616. function AssetsManager(scene) {
  61617. this.tasks = new Array();
  61618. this.waitingTasksCount = 0;
  61619. this.useDefaultLoadingScreen = true;
  61620. this._scene = scene;
  61621. }
  61622. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  61623. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  61624. this.tasks.push(task);
  61625. return task;
  61626. };
  61627. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  61628. var task = new TextFileAssetTask(taskName, url);
  61629. this.tasks.push(task);
  61630. return task;
  61631. };
  61632. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  61633. var task = new BinaryFileAssetTask(taskName, url);
  61634. this.tasks.push(task);
  61635. return task;
  61636. };
  61637. AssetsManager.prototype.addImageTask = function (taskName, url) {
  61638. var task = new ImageAssetTask(taskName, url);
  61639. this.tasks.push(task);
  61640. return task;
  61641. };
  61642. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  61643. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61644. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  61645. this.tasks.push(task);
  61646. return task;
  61647. };
  61648. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  61649. this.waitingTasksCount--;
  61650. if (this.waitingTasksCount === 0) {
  61651. if (this.onFinish) {
  61652. this.onFinish(this.tasks);
  61653. }
  61654. this._scene.getEngine().hideLoadingUI();
  61655. }
  61656. };
  61657. AssetsManager.prototype._runTask = function (task) {
  61658. var _this = this;
  61659. task.run(this._scene, function () {
  61660. if (_this.onTaskSuccess) {
  61661. _this.onTaskSuccess(task);
  61662. }
  61663. _this._decreaseWaitingTasksCount();
  61664. }, function () {
  61665. if (_this.onTaskError) {
  61666. _this.onTaskError(task);
  61667. }
  61668. _this._decreaseWaitingTasksCount();
  61669. });
  61670. };
  61671. AssetsManager.prototype.reset = function () {
  61672. this.tasks = new Array();
  61673. return this;
  61674. };
  61675. AssetsManager.prototype.load = function () {
  61676. this.waitingTasksCount = this.tasks.length;
  61677. if (this.waitingTasksCount === 0) {
  61678. if (this.onFinish) {
  61679. this.onFinish(this.tasks);
  61680. }
  61681. return this;
  61682. }
  61683. if (this.useDefaultLoadingScreen) {
  61684. this._scene.getEngine().displayLoadingUI();
  61685. }
  61686. for (var index = 0; index < this.tasks.length; index++) {
  61687. var task = this.tasks[index];
  61688. this._runTask(task);
  61689. }
  61690. return this;
  61691. };
  61692. return AssetsManager;
  61693. }());
  61694. BABYLON.AssetsManager = AssetsManager;
  61695. })(BABYLON || (BABYLON = {}));
  61696. //# sourceMappingURL=babylon.assetsManager.js.map
  61697. var BABYLON;
  61698. (function (BABYLON) {
  61699. var MapTexture = (function (_super) {
  61700. __extends(MapTexture, _super);
  61701. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  61702. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61703. if (useMipMap === void 0) { useMipMap = false; }
  61704. if (margin === void 0) { margin = 0; }
  61705. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  61706. _this.name = name;
  61707. _this._size = size;
  61708. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61709. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61710. // Create the rectPackMap that will allocate portion of the texture
  61711. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  61712. // Create the texture that will store the content
  61713. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  61714. return _this;
  61715. }
  61716. /**
  61717. * Allocate a rectangle of a given size in the texture map
  61718. * @param size the size of the rectangle to allocation
  61719. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  61720. */
  61721. MapTexture.prototype.allocateRect = function (size) {
  61722. return this._rectPackingMap.addRect(size);
  61723. };
  61724. /**
  61725. * Free a given rectangle from the texture map
  61726. * @param rectInfo the instance corresponding to the rect to free.
  61727. */
  61728. MapTexture.prototype.freeRect = function (rectInfo) {
  61729. if (rectInfo) {
  61730. rectInfo.freeContent();
  61731. }
  61732. };
  61733. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  61734. /**
  61735. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  61736. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  61737. * @returns {}
  61738. */
  61739. get: function () {
  61740. return this._rectPackingMap.freeSpace;
  61741. },
  61742. enumerable: true,
  61743. configurable: true
  61744. });
  61745. /**
  61746. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  61747. * 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.
  61748. * Don't forget to call unbindTexture when you're done rendering
  61749. * @param rect the zone to render to
  61750. * @param clear true to clear the portion's color/depth data
  61751. */
  61752. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  61753. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  61754. };
  61755. /**
  61756. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  61757. * 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.
  61758. * Don't forget to call unbindTexture when you're done rendering
  61759. * @param pos the position into the texture
  61760. * @param size the portion to fit the clip space to
  61761. * @param clear true to clear the portion's color/depth data
  61762. */
  61763. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  61764. var engine = this.getScene().getEngine();
  61765. engine.bindFramebuffer(this._texture);
  61766. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  61767. if (clear) {
  61768. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  61769. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  61770. }
  61771. };
  61772. /**
  61773. * Unbind the texture map from the rendering engine.
  61774. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  61775. * @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.
  61776. */
  61777. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  61778. // Dump ?
  61779. if (dumpForDebug) {
  61780. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  61781. }
  61782. var engine = this.getScene().getEngine();
  61783. if (this._replacedViewport) {
  61784. engine.setViewport(this._replacedViewport);
  61785. this._replacedViewport = null;
  61786. }
  61787. engine.unBindFramebuffer(this._texture);
  61788. };
  61789. Object.defineProperty(MapTexture.prototype, "canRescale", {
  61790. get: function () {
  61791. return false;
  61792. },
  61793. enumerable: true,
  61794. configurable: true
  61795. });
  61796. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  61797. // Anyway, there's not much point to use this method for this kind of texture I guess
  61798. MapTexture.prototype.clone = function () {
  61799. return null;
  61800. };
  61801. return MapTexture;
  61802. }(BABYLON.Texture));
  61803. BABYLON.MapTexture = MapTexture;
  61804. })(BABYLON || (BABYLON = {}));
  61805. //# sourceMappingURL=babylon.mapTexture.js.map
  61806. var BABYLON;
  61807. (function (BABYLON) {
  61808. /**
  61809. * This class describe a rectangle that were added to the map.
  61810. * You have access to its coordinates either in pixel or normalized (UV)
  61811. */
  61812. var PackedRect = (function () {
  61813. function PackedRect(root, parent, pos, size) {
  61814. this._pos = pos;
  61815. this._size = size;
  61816. this._root = root;
  61817. this._parent = parent;
  61818. this._contentSize = null;
  61819. this._bottomNode = null;
  61820. this._leftNode = null;
  61821. this._initialSize = null;
  61822. this._rightNode = null;
  61823. }
  61824. Object.defineProperty(PackedRect.prototype, "pos", {
  61825. /**
  61826. * @returns the position of this node into the map
  61827. */
  61828. get: function () {
  61829. return this._pos;
  61830. },
  61831. enumerable: true,
  61832. configurable: true
  61833. });
  61834. Object.defineProperty(PackedRect.prototype, "contentSize", {
  61835. /**
  61836. * @returns the size of the rectangle this node handles
  61837. */
  61838. get: function () {
  61839. return this._contentSize;
  61840. },
  61841. enumerable: true,
  61842. configurable: true
  61843. });
  61844. /**
  61845. * Retrieve the inner position (considering the margin) and stores it into the res object
  61846. * @param res must be a valid Vector2 that will contain the inner position after this call
  61847. */
  61848. PackedRect.prototype.getInnerPosToRef = function (res) {
  61849. var m = this._root._margin;
  61850. res.x = this._pos.x + m;
  61851. res.y = this._pos.y + m;
  61852. };
  61853. /**
  61854. * Retrieve the inner size (considering the margin) and stores it into the res object
  61855. * @param res must be a valid Size that will contain the inner size after this call
  61856. */
  61857. PackedRect.prototype.getInnerSizeToRef = function (res) {
  61858. var m = this._root._margin;
  61859. res.width = this._contentSize.width - (m * 2);
  61860. res.height = this._contentSize.height - (m * 2);
  61861. };
  61862. Object.defineProperty(PackedRect.prototype, "UVs", {
  61863. /**
  61864. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  61865. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  61866. */
  61867. get: function () {
  61868. if (!this._contentSize) {
  61869. throw new Error("Can't compute UVs for this object because it's nor allocated");
  61870. }
  61871. return this.getUVsForCustomSize(this._contentSize);
  61872. },
  61873. enumerable: true,
  61874. configurable: true
  61875. });
  61876. /**
  61877. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  61878. * and then using only a part of the PackRect.
  61879. * This method will return the UVs for this part by given the custom size of what you really use
  61880. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  61881. */
  61882. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  61883. var mainWidth = this._root._size.width;
  61884. var mainHeight = this._root._size.height;
  61885. var margin = this._root._margin;
  61886. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  61887. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  61888. var uvs = new Array();
  61889. uvs.push(topLeft);
  61890. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  61891. uvs.push(rightBottom);
  61892. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  61893. return uvs;
  61894. };
  61895. /**
  61896. * Free this rectangle from the map.
  61897. * Call this method when you no longer need the rectangle to be in the map.
  61898. */
  61899. PackedRect.prototype.freeContent = function () {
  61900. if (!this.contentSize) {
  61901. return;
  61902. }
  61903. this._contentSize = null;
  61904. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  61905. this.attemptDefrag();
  61906. };
  61907. Object.defineProperty(PackedRect.prototype, "isUsed", {
  61908. get: function () {
  61909. return this._contentSize != null || this._leftNode != null;
  61910. },
  61911. enumerable: true,
  61912. configurable: true
  61913. });
  61914. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  61915. var node = this.findNode(contentSize);
  61916. // Not enough space...
  61917. if (!node) {
  61918. return null;
  61919. }
  61920. node.splitNode(contentSize);
  61921. return node;
  61922. };
  61923. PackedRect.prototype.findNode = function (size) {
  61924. var resNode = null;
  61925. var margin = this._root._margin * 2;
  61926. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  61927. if (this.isUsed) {
  61928. if (this._leftNode) {
  61929. resNode = this._leftNode.findNode(size);
  61930. }
  61931. if (!resNode && this._rightNode) {
  61932. resNode = this._rightNode.findNode(size);
  61933. }
  61934. if (!resNode && this._bottomNode) {
  61935. resNode = this._bottomNode.findNode(size);
  61936. }
  61937. }
  61938. else if (this._initialSize) {
  61939. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  61940. resNode = this;
  61941. }
  61942. else {
  61943. return null;
  61944. }
  61945. }
  61946. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  61947. resNode = this;
  61948. }
  61949. return resNode;
  61950. };
  61951. PackedRect.prototype.splitNode = function (contentSize) {
  61952. var cs = PackedRect.TpsSize;
  61953. var margin = this._root._margin * 2;
  61954. cs.copyFrom(contentSize);
  61955. cs.width += margin;
  61956. cs.height += margin;
  61957. // 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)
  61958. if (!this._contentSize && this._initialSize) {
  61959. this._contentSize = cs.clone();
  61960. 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));
  61961. return this._leftNode.splitNode(contentSize);
  61962. }
  61963. else {
  61964. this._contentSize = cs.clone();
  61965. this._initialSize = cs.clone();
  61966. if (cs.width !== this._size.width) {
  61967. 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));
  61968. }
  61969. if (cs.height !== this._size.height) {
  61970. 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));
  61971. }
  61972. return this;
  61973. }
  61974. };
  61975. PackedRect.prototype.attemptDefrag = function () {
  61976. if (!this.isUsed && this.isRecursiveFree) {
  61977. this.clearNode();
  61978. if (this._parent) {
  61979. this._parent.attemptDefrag();
  61980. }
  61981. }
  61982. };
  61983. PackedRect.prototype.clearNode = function () {
  61984. this._initialSize = null;
  61985. this._rightNode = null;
  61986. this._bottomNode = null;
  61987. };
  61988. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  61989. get: function () {
  61990. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  61991. },
  61992. enumerable: true,
  61993. configurable: true
  61994. });
  61995. PackedRect.prototype.evalFreeSize = function (size) {
  61996. var levelSize = 0;
  61997. if (!this.isUsed) {
  61998. var margin = this._root._margin;
  61999. var is = this._initialSize;
  62000. if (is) {
  62001. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  62002. }
  62003. else {
  62004. var size_1 = this._size;
  62005. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  62006. }
  62007. }
  62008. if (this._rightNode) {
  62009. levelSize += this._rightNode.evalFreeSize(0);
  62010. }
  62011. if (this._bottomNode) {
  62012. levelSize += this._bottomNode.evalFreeSize(0);
  62013. }
  62014. return levelSize + size;
  62015. };
  62016. return PackedRect;
  62017. }());
  62018. PackedRect.TpsSize = BABYLON.Size.Zero();
  62019. BABYLON.PackedRect = PackedRect;
  62020. /**
  62021. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  62022. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  62023. * 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.
  62024. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  62025. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  62026. */
  62027. var RectPackingMap = (function (_super) {
  62028. __extends(RectPackingMap, _super);
  62029. /**
  62030. * Create an instance of the object with a dimension using the given size
  62031. * @param size The dimension of the rectangle that will contain all the sub ones.
  62032. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  62033. */
  62034. function RectPackingMap(size, margin) {
  62035. if (margin === void 0) { margin = 0; }
  62036. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  62037. _this._margin = margin;
  62038. _this._root = _this;
  62039. return _this;
  62040. }
  62041. /**
  62042. * Add a rectangle, finding the best location to store it into the map
  62043. * @param size the dimension of the rectangle to store
  62044. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  62045. */
  62046. RectPackingMap.prototype.addRect = function (size) {
  62047. var node = this.findAndSplitNode(size);
  62048. return node;
  62049. };
  62050. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  62051. /**
  62052. * Return the current space free normalized between [0;1]
  62053. * @returns {}
  62054. */
  62055. get: function () {
  62056. var freeSize = 0;
  62057. freeSize = this.evalFreeSize(freeSize);
  62058. return freeSize / (this._size.width * this._size.height);
  62059. },
  62060. enumerable: true,
  62061. configurable: true
  62062. });
  62063. return RectPackingMap;
  62064. }(PackedRect));
  62065. BABYLON.RectPackingMap = RectPackingMap;
  62066. })(BABYLON || (BABYLON = {}));
  62067. //# sourceMappingURL=babylon.rectPackingMap.js.map
  62068. var BABYLON;
  62069. (function (BABYLON) {
  62070. var DynamicFloatArrayElementInfo = (function () {
  62071. function DynamicFloatArrayElementInfo() {
  62072. }
  62073. return DynamicFloatArrayElementInfo;
  62074. }());
  62075. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  62076. /**
  62077. * 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.
  62078. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  62079. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  62080. * 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.
  62081. * 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.
  62082. * 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".
  62083. */
  62084. var DynamicFloatArray = (function () {
  62085. /**
  62086. * Construct an instance of the dynamic float array
  62087. * @param stride size of one element in float (i.e. not bytes!)
  62088. * @param initialElementCount the number of available entries at construction
  62089. */
  62090. function DynamicFloatArray(stride, initialElementCount) {
  62091. this.compareValueOffset = null;
  62092. this.sortingAscending = true;
  62093. this._stride = stride;
  62094. this.buffer = new Float32Array(stride * initialElementCount);
  62095. this._lastUsed = 0;
  62096. this._firstFree = 0;
  62097. this._allEntries = new Array(initialElementCount);
  62098. this._freeEntries = new Array(initialElementCount);
  62099. for (var i = 0; i < initialElementCount; i++) {
  62100. var element = new DynamicFloatArrayElementInfo();
  62101. element.offset = i * stride;
  62102. this._allEntries[i] = element;
  62103. this._freeEntries[initialElementCount - i - 1] = element;
  62104. }
  62105. }
  62106. /**
  62107. * Allocate an element in the array.
  62108. * @return the element info instance that contains the offset into the main buffer of the element's location.
  62109. * Beware, this offset may change when you call pack()
  62110. */
  62111. DynamicFloatArray.prototype.allocElement = function () {
  62112. if (this._freeEntries.length === 0) {
  62113. this._growBuffer();
  62114. }
  62115. var el = this._freeEntries.pop();
  62116. this._lastUsed = Math.max(el.offset, this._lastUsed);
  62117. if (el.offset === this._firstFree) {
  62118. if (this._freeEntries.length > 0) {
  62119. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  62120. }
  62121. else {
  62122. this._firstFree += this._stride;
  62123. }
  62124. }
  62125. return el;
  62126. };
  62127. /**
  62128. * Free the element corresponding to the given element info
  62129. * @param elInfo the element that describe the allocated element
  62130. */
  62131. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  62132. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  62133. this._freeEntries.push(elInfo);
  62134. };
  62135. /**
  62136. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  62137. * 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().
  62138. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  62139. */
  62140. DynamicFloatArray.prototype.pack = function () {
  62141. // no free slot? no need to pack
  62142. if (this._freeEntries.length === 0) {
  62143. return this.buffer;
  62144. }
  62145. // If the buffer is already packed the last used will always be lower than the first free
  62146. // 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.
  62147. if (this._lastUsed < this._firstFree) {
  62148. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  62149. return elementsBuffer_1;
  62150. }
  62151. var s = this._stride;
  62152. // 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
  62153. var lastFree = new DynamicFloatArrayElementInfo();
  62154. lastFree.offset = this.totalElementCount * s;
  62155. this._freeEntries.push(lastFree);
  62156. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  62157. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  62158. var firstFreeSlotOffset = sortedFree[0].offset;
  62159. var freeZoneSize = 1;
  62160. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  62161. var prevOffset = sortedFree[0].offset;
  62162. for (var i = 1; i < sortedFree.length; i++) {
  62163. // 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
  62164. if (firstFreeSlotOffset >= occupiedZoneSize) {
  62165. break;
  62166. }
  62167. var curFree = sortedFree[i];
  62168. var curOffset = curFree.offset;
  62169. // Compute the distance between this offset and the previous
  62170. var distance = curOffset - prevOffset;
  62171. // If the distance is the stride size, they are adjacent, it good, move to the next
  62172. if (distance === s) {
  62173. // Free zone is one element bigger
  62174. ++freeZoneSize;
  62175. // as we're about to iterate to the next, the cur becomes the previous...
  62176. prevOffset = curOffset;
  62177. continue;
  62178. }
  62179. // Distance is bigger, which means there's x element between the previous free and this one
  62180. var usedRange = (distance / s) - 1;
  62181. // Two cases the free zone is smaller than the data to move or bigger
  62182. // Copy what can fit in the free zone
  62183. var curMoveOffset = curOffset - s;
  62184. var copyCount = Math.min(freeZoneSize, usedRange);
  62185. for (var j = 0; j < copyCount; j++) {
  62186. var freeI = firstFreeSlotOffset / s;
  62187. var curI = curMoveOffset / s;
  62188. var moveEl = sortedAll[curI];
  62189. this._moveElement(moveEl, firstFreeSlotOffset);
  62190. var replacedEl = sortedAll[freeI];
  62191. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  62192. replacedEl.offset = curMoveOffset;
  62193. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  62194. sortedAll[freeI] = moveEl;
  62195. sortedAll[curI] = replacedEl;
  62196. curMoveOffset -= s;
  62197. firstFreeSlotOffset += s;
  62198. }
  62199. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  62200. if (freeZoneSize <= usedRange) {
  62201. firstFreeSlotOffset = curMoveOffset + s;
  62202. freeZoneSize = 1 + copyCount;
  62203. }
  62204. else {
  62205. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  62206. }
  62207. // as we're about to iterate to the next, the cur becomes the previous...
  62208. prevOffset = curOffset;
  62209. }
  62210. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  62211. this._lastUsed = firstFreeSlotOffset - s;
  62212. this._firstFree = firstFreeSlotOffset;
  62213. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  62214. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  62215. this._allEntries = sortedAll;
  62216. return elementsBuffer;
  62217. };
  62218. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  62219. for (var i = 0; i < this._stride; i++) {
  62220. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  62221. }
  62222. element.offset = destOffset;
  62223. };
  62224. DynamicFloatArray.prototype._growBuffer = function () {
  62225. // Allocate the new buffer with 50% more entries, copy the content of the current one
  62226. var newElCount = Math.floor(this.totalElementCount * 1.5);
  62227. var newBuffer = new Float32Array(newElCount * this._stride);
  62228. newBuffer.set(this.buffer);
  62229. var curCount = this.totalElementCount;
  62230. var addedCount = newElCount - this.totalElementCount;
  62231. for (var i = 0; i < addedCount; i++) {
  62232. var element = new DynamicFloatArrayElementInfo();
  62233. element.offset = (curCount + i) * this.stride;
  62234. this._allEntries.push(element);
  62235. this._freeEntries[addedCount - i - 1] = element;
  62236. }
  62237. this._firstFree = curCount * this.stride;
  62238. this.buffer = newBuffer;
  62239. };
  62240. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  62241. /**
  62242. * Get the total count of entries that can fit in the current buffer
  62243. * @returns the elements count
  62244. */
  62245. get: function () {
  62246. return this._allEntries.length;
  62247. },
  62248. enumerable: true,
  62249. configurable: true
  62250. });
  62251. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  62252. /**
  62253. * Get the count of free entries that can still be allocated without resizing the buffer
  62254. * @returns the free elements count
  62255. */
  62256. get: function () {
  62257. return this._freeEntries.length;
  62258. },
  62259. enumerable: true,
  62260. configurable: true
  62261. });
  62262. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  62263. /**
  62264. * Get the count of allocated elements
  62265. * @returns the allocated elements count
  62266. */
  62267. get: function () {
  62268. return this._allEntries.length - this._freeEntries.length;
  62269. },
  62270. enumerable: true,
  62271. configurable: true
  62272. });
  62273. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  62274. /**
  62275. * Return the size of one element in float
  62276. * @returns the size in float
  62277. */
  62278. get: function () {
  62279. return this._stride;
  62280. },
  62281. enumerable: true,
  62282. configurable: true
  62283. });
  62284. DynamicFloatArray.prototype.sort = function () {
  62285. var _this = this;
  62286. if (!this.compareValueOffset) {
  62287. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  62288. }
  62289. var count = this.usedElementCount;
  62290. // Do we have to (re)create the sort table?
  62291. if (!this._sortTable || this._sortTable.length < count) {
  62292. // 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...
  62293. var newCount = Math.min(this.totalElementCount, count * 2);
  62294. this._sortTable = new Array(newCount);
  62295. }
  62296. if (!this._sortedTable || this._sortedTable.length !== count) {
  62297. this._sortedTable = new Array(count);
  62298. }
  62299. // Because, you know...
  62300. this.pack();
  62301. //let stride = this.stride;
  62302. //for (let i = 0; i < count; i++) {
  62303. // let si = this._sortTable[i];
  62304. // if (!si) {
  62305. // si = new SortInfo();
  62306. // this._sortTable[i] = si;
  62307. // }
  62308. // si.entry = this._allEntries[i];
  62309. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  62310. // si.swapedOffset = null;
  62311. // this._sortedTable[i] = si;
  62312. //}
  62313. var curOffset = 0;
  62314. var stride = this.stride;
  62315. for (var i = 0; i < count; i++, curOffset += stride) {
  62316. var si = this._sortTable[i];
  62317. if (!si) {
  62318. si = new SortInfo();
  62319. this._sortTable[i] = si;
  62320. }
  62321. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  62322. si.offset = curOffset;
  62323. si.swapedOffset = null;
  62324. this._sortedTable[i] = si;
  62325. }
  62326. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  62327. if (this.sortingAscending) {
  62328. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  62329. }
  62330. else {
  62331. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  62332. }
  62333. var swapElements = function (src, dst) {
  62334. for (var i = 0; i < stride; i++) {
  62335. var tps = _this.buffer[dst + i];
  62336. _this.buffer[dst + i] = _this.buffer[src + i];
  62337. _this.buffer[src + i] = tps;
  62338. }
  62339. };
  62340. // 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:
  62341. // 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),
  62342. // and I still want something with a good algorithm complexity.
  62343. // 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,
  62344. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  62345. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  62346. // 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
  62347. // until we find a SortInfo object without a swapedOffset which means we got the right location
  62348. // 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
  62349. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  62350. for (var i = 0; i < count; i++) {
  62351. // Get the element to move
  62352. var sourceSI = this._sortedTable[i];
  62353. var destSI = this._sortTable[i];
  62354. var sourceOff = sourceSI.offset;
  62355. // If the source changed location, find the new one
  62356. if (sourceSI.swapedOffset) {
  62357. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  62358. var curSI = sourceSI;
  62359. while (curSI.swapedOffset) {
  62360. curSI = this._sortTable[curSI.swapedOffset / stride];
  62361. }
  62362. // Finally get the right location
  62363. sourceOff = curSI.offset;
  62364. }
  62365. // Tag the element being replaced with its new location
  62366. destSI.swapedOffset = sourceOff;
  62367. // Swap elements (only if needed)
  62368. if (sourceOff !== destSI.offset) {
  62369. swapElements(sourceOff, destSI.offset);
  62370. }
  62371. // Update the offset in the corresponding DFAE
  62372. //sourceSI.entry.offset = destSI.entry.offset;
  62373. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  62374. }
  62375. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  62376. return true;
  62377. };
  62378. return DynamicFloatArray;
  62379. }());
  62380. BABYLON.DynamicFloatArray = DynamicFloatArray;
  62381. var SortInfo = (function () {
  62382. function SortInfo() {
  62383. this.compareData = this.offset = this.swapedOffset = null;
  62384. }
  62385. return SortInfo;
  62386. }());
  62387. })(BABYLON || (BABYLON = {}));
  62388. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  62389. var BABYLON;
  62390. (function (BABYLON) {
  62391. var serializedGeometries = [];
  62392. var serializeGeometry = function (geometry, serializationGeometries) {
  62393. if (serializedGeometries[geometry.id]) {
  62394. return;
  62395. }
  62396. if (geometry.doNotSerialize) {
  62397. return;
  62398. }
  62399. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  62400. serializationGeometries.boxes.push(geometry.serialize());
  62401. }
  62402. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  62403. serializationGeometries.spheres.push(geometry.serialize());
  62404. }
  62405. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  62406. serializationGeometries.cylinders.push(geometry.serialize());
  62407. }
  62408. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  62409. serializationGeometries.toruses.push(geometry.serialize());
  62410. }
  62411. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  62412. serializationGeometries.grounds.push(geometry.serialize());
  62413. }
  62414. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  62415. serializationGeometries.planes.push(geometry.serialize());
  62416. }
  62417. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  62418. serializationGeometries.torusKnots.push(geometry.serialize());
  62419. }
  62420. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  62421. throw new Error("Unknown primitive type");
  62422. }
  62423. else {
  62424. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  62425. }
  62426. serializedGeometries[geometry.id] = true;
  62427. };
  62428. var serializeMesh = function (mesh, serializationScene) {
  62429. var serializationObject = {};
  62430. // Geometry
  62431. var geometry = mesh._geometry;
  62432. if (geometry) {
  62433. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  62434. // 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
  62435. serializeGeometry(geometry, serializationScene.geometries);
  62436. }
  62437. }
  62438. // Custom
  62439. if (mesh.serialize) {
  62440. mesh.serialize(serializationObject);
  62441. }
  62442. return serializationObject;
  62443. };
  62444. var finalizeSingleMesh = function (mesh, serializationObject) {
  62445. //only works if the mesh is already loaded
  62446. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  62447. //serialize material
  62448. if (mesh.material) {
  62449. if (mesh.material instanceof BABYLON.StandardMaterial) {
  62450. serializationObject.materials = serializationObject.materials || [];
  62451. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  62452. serializationObject.materials.push(mesh.material.serialize());
  62453. }
  62454. }
  62455. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  62456. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  62457. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  62458. serializationObject.multiMaterials.push(mesh.material.serialize());
  62459. }
  62460. }
  62461. }
  62462. //serialize geometry
  62463. var geometry = mesh._geometry;
  62464. if (geometry) {
  62465. if (!serializationObject.geometries) {
  62466. serializationObject.geometries = {};
  62467. serializationObject.geometries.boxes = [];
  62468. serializationObject.geometries.spheres = [];
  62469. serializationObject.geometries.cylinders = [];
  62470. serializationObject.geometries.toruses = [];
  62471. serializationObject.geometries.grounds = [];
  62472. serializationObject.geometries.planes = [];
  62473. serializationObject.geometries.torusKnots = [];
  62474. serializationObject.geometries.vertexData = [];
  62475. }
  62476. serializeGeometry(geometry, serializationObject.geometries);
  62477. }
  62478. // Skeletons
  62479. if (mesh.skeleton) {
  62480. serializationObject.skeletons = serializationObject.skeletons || [];
  62481. serializationObject.skeletons.push(mesh.skeleton.serialize());
  62482. }
  62483. //serialize the actual mesh
  62484. serializationObject.meshes = serializationObject.meshes || [];
  62485. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  62486. }
  62487. };
  62488. var SceneSerializer = (function () {
  62489. function SceneSerializer() {
  62490. }
  62491. SceneSerializer.ClearCache = function () {
  62492. serializedGeometries = [];
  62493. };
  62494. SceneSerializer.Serialize = function (scene) {
  62495. var serializationObject = {};
  62496. SceneSerializer.ClearCache();
  62497. // Scene
  62498. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  62499. serializationObject.autoClear = scene.autoClear;
  62500. serializationObject.clearColor = scene.clearColor.asArray();
  62501. serializationObject.ambientColor = scene.ambientColor.asArray();
  62502. serializationObject.gravity = scene.gravity.asArray();
  62503. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  62504. serializationObject.workerCollisions = scene.workerCollisions;
  62505. // Fog
  62506. if (scene.fogMode && scene.fogMode !== 0) {
  62507. serializationObject.fogMode = scene.fogMode;
  62508. serializationObject.fogColor = scene.fogColor.asArray();
  62509. serializationObject.fogStart = scene.fogStart;
  62510. serializationObject.fogEnd = scene.fogEnd;
  62511. serializationObject.fogDensity = scene.fogDensity;
  62512. }
  62513. //Physics
  62514. if (scene.isPhysicsEnabled()) {
  62515. serializationObject.physicsEnabled = true;
  62516. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  62517. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  62518. }
  62519. // Metadata
  62520. if (scene.metadata) {
  62521. serializationObject.metadata = scene.metadata;
  62522. }
  62523. // Morph targets
  62524. serializationObject.morphTargetManagers = [];
  62525. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  62526. var abstractMesh = _a[_i];
  62527. var manager = abstractMesh.morphTargetManager;
  62528. if (manager) {
  62529. serializationObject.morphTargetManagers.push(manager.serialize());
  62530. }
  62531. }
  62532. // Lights
  62533. serializationObject.lights = [];
  62534. var index;
  62535. var light;
  62536. for (index = 0; index < scene.lights.length; index++) {
  62537. light = scene.lights[index];
  62538. if (!light.doNotSerialize) {
  62539. serializationObject.lights.push(light.serialize());
  62540. }
  62541. }
  62542. // Cameras
  62543. serializationObject.cameras = [];
  62544. for (index = 0; index < scene.cameras.length; index++) {
  62545. var camera = scene.cameras[index];
  62546. if (!camera.doNotSerialize) {
  62547. serializationObject.cameras.push(camera.serialize());
  62548. }
  62549. }
  62550. if (scene.activeCamera) {
  62551. serializationObject.activeCameraID = scene.activeCamera.id;
  62552. }
  62553. // Animations
  62554. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  62555. // Materials
  62556. serializationObject.materials = [];
  62557. serializationObject.multiMaterials = [];
  62558. var material;
  62559. for (index = 0; index < scene.materials.length; index++) {
  62560. material = scene.materials[index];
  62561. if (!material.doNotSerialize) {
  62562. serializationObject.materials.push(material.serialize());
  62563. }
  62564. }
  62565. // MultiMaterials
  62566. serializationObject.multiMaterials = [];
  62567. for (index = 0; index < scene.multiMaterials.length; index++) {
  62568. var multiMaterial = scene.multiMaterials[index];
  62569. serializationObject.multiMaterials.push(multiMaterial.serialize());
  62570. }
  62571. // Skeletons
  62572. serializationObject.skeletons = [];
  62573. for (index = 0; index < scene.skeletons.length; index++) {
  62574. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  62575. }
  62576. // Geometries
  62577. serializationObject.geometries = {};
  62578. serializationObject.geometries.boxes = [];
  62579. serializationObject.geometries.spheres = [];
  62580. serializationObject.geometries.cylinders = [];
  62581. serializationObject.geometries.toruses = [];
  62582. serializationObject.geometries.grounds = [];
  62583. serializationObject.geometries.planes = [];
  62584. serializationObject.geometries.torusKnots = [];
  62585. serializationObject.geometries.vertexData = [];
  62586. serializedGeometries = [];
  62587. var geometries = scene.getGeometries();
  62588. for (index = 0; index < geometries.length; index++) {
  62589. var geometry = geometries[index];
  62590. if (geometry.isReady()) {
  62591. serializeGeometry(geometry, serializationObject.geometries);
  62592. }
  62593. }
  62594. // Meshes
  62595. serializationObject.meshes = [];
  62596. for (index = 0; index < scene.meshes.length; index++) {
  62597. var abstractMesh = scene.meshes[index];
  62598. if (abstractMesh instanceof BABYLON.Mesh) {
  62599. var mesh = abstractMesh;
  62600. if (!mesh.doNotSerialize) {
  62601. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  62602. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  62603. }
  62604. }
  62605. }
  62606. }
  62607. // Particles Systems
  62608. serializationObject.particleSystems = [];
  62609. for (index = 0; index < scene.particleSystems.length; index++) {
  62610. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  62611. }
  62612. // Lens flares
  62613. serializationObject.lensFlareSystems = [];
  62614. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  62615. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  62616. }
  62617. // Shadows
  62618. serializationObject.shadowGenerators = [];
  62619. for (index = 0; index < scene.lights.length; index++) {
  62620. light = scene.lights[index];
  62621. var shadowGenerator = light.getShadowGenerator();
  62622. // Only support serialization for official generator so far.
  62623. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  62624. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  62625. }
  62626. }
  62627. // Action Manager
  62628. if (scene.actionManager) {
  62629. serializationObject.actions = scene.actionManager.serialize("scene");
  62630. }
  62631. // Audio
  62632. serializationObject.sounds = [];
  62633. for (index = 0; index < scene.soundTracks.length; index++) {
  62634. var soundtrack = scene.soundTracks[index];
  62635. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  62636. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  62637. }
  62638. }
  62639. return serializationObject;
  62640. };
  62641. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  62642. if (withParents === void 0) { withParents = false; }
  62643. if (withChildren === void 0) { withChildren = false; }
  62644. var serializationObject = {};
  62645. SceneSerializer.ClearCache();
  62646. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  62647. if (withParents || withChildren) {
  62648. //deliberate for loop! not for each, appended should be processed as well.
  62649. for (var i = 0; i < toSerialize.length; ++i) {
  62650. if (withChildren) {
  62651. toSerialize[i].getDescendants().forEach(function (node) {
  62652. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  62653. toSerialize.push(node);
  62654. }
  62655. });
  62656. }
  62657. //make sure the array doesn't contain the object already
  62658. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  62659. toSerialize.push(toSerialize[i].parent);
  62660. }
  62661. }
  62662. }
  62663. toSerialize.forEach(function (mesh) {
  62664. finalizeSingleMesh(mesh, serializationObject);
  62665. });
  62666. return serializationObject;
  62667. };
  62668. return SceneSerializer;
  62669. }());
  62670. BABYLON.SceneSerializer = SceneSerializer;
  62671. })(BABYLON || (BABYLON = {}));
  62672. //# sourceMappingURL=babylon.sceneSerializer.js.map
  62673. var BABYLON;
  62674. (function (BABYLON) {
  62675. var ReflectionProbe = (function () {
  62676. function ReflectionProbe(name, size, scene, generateMipMaps) {
  62677. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62678. var _this = this;
  62679. this.name = name;
  62680. this._viewMatrix = BABYLON.Matrix.Identity();
  62681. this._target = BABYLON.Vector3.Zero();
  62682. this._add = BABYLON.Vector3.Zero();
  62683. this.invertYAxis = false;
  62684. this.position = BABYLON.Vector3.Zero();
  62685. this._scene = scene;
  62686. this._scene.reflectionProbes.push(this);
  62687. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  62688. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  62689. switch (faceIndex) {
  62690. case 0:
  62691. _this._add.copyFromFloats(1, 0, 0);
  62692. break;
  62693. case 1:
  62694. _this._add.copyFromFloats(-1, 0, 0);
  62695. break;
  62696. case 2:
  62697. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  62698. break;
  62699. case 3:
  62700. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  62701. break;
  62702. case 4:
  62703. _this._add.copyFromFloats(0, 0, 1);
  62704. break;
  62705. case 5:
  62706. _this._add.copyFromFloats(0, 0, -1);
  62707. break;
  62708. }
  62709. if (_this._attachedMesh) {
  62710. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  62711. }
  62712. _this.position.addToRef(_this._add, _this._target);
  62713. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  62714. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  62715. });
  62716. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  62717. scene.updateTransformMatrix(true);
  62718. });
  62719. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  62720. }
  62721. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  62722. get: function () {
  62723. return this._renderTargetTexture.samples;
  62724. },
  62725. set: function (value) {
  62726. this._renderTargetTexture.samples = value;
  62727. },
  62728. enumerable: true,
  62729. configurable: true
  62730. });
  62731. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  62732. get: function () {
  62733. return this._renderTargetTexture.refreshRate;
  62734. },
  62735. set: function (value) {
  62736. this._renderTargetTexture.refreshRate = value;
  62737. },
  62738. enumerable: true,
  62739. configurable: true
  62740. });
  62741. ReflectionProbe.prototype.getScene = function () {
  62742. return this._scene;
  62743. };
  62744. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  62745. get: function () {
  62746. return this._renderTargetTexture;
  62747. },
  62748. enumerable: true,
  62749. configurable: true
  62750. });
  62751. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  62752. get: function () {
  62753. return this._renderTargetTexture.renderList;
  62754. },
  62755. enumerable: true,
  62756. configurable: true
  62757. });
  62758. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  62759. this._attachedMesh = mesh;
  62760. };
  62761. ReflectionProbe.prototype.dispose = function () {
  62762. var index = this._scene.reflectionProbes.indexOf(this);
  62763. if (index !== -1) {
  62764. // Remove from the scene if found
  62765. this._scene.reflectionProbes.splice(index, 1);
  62766. }
  62767. if (this._renderTargetTexture) {
  62768. this._renderTargetTexture.dispose();
  62769. this._renderTargetTexture = null;
  62770. }
  62771. };
  62772. return ReflectionProbe;
  62773. }());
  62774. BABYLON.ReflectionProbe = ReflectionProbe;
  62775. })(BABYLON || (BABYLON = {}));
  62776. //# sourceMappingURL=babylon.reflectionProbe.js.map
  62777. var BABYLON;
  62778. (function (BABYLON) {
  62779. var Layer = (function () {
  62780. function Layer(name, imgUrl, scene, isBackground, color) {
  62781. this.name = name;
  62782. this.scale = new BABYLON.Vector2(1, 1);
  62783. this.offset = new BABYLON.Vector2(0, 0);
  62784. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  62785. this._vertexBuffers = {};
  62786. // Events
  62787. /**
  62788. * An event triggered when the layer is disposed.
  62789. * @type {BABYLON.Observable}
  62790. */
  62791. this.onDisposeObservable = new BABYLON.Observable();
  62792. /**
  62793. * An event triggered before rendering the scene
  62794. * @type {BABYLON.Observable}
  62795. */
  62796. this.onBeforeRenderObservable = new BABYLON.Observable();
  62797. /**
  62798. * An event triggered after rendering the scene
  62799. * @type {BABYLON.Observable}
  62800. */
  62801. this.onAfterRenderObservable = new BABYLON.Observable();
  62802. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  62803. this.isBackground = isBackground === undefined ? true : isBackground;
  62804. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  62805. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62806. this._scene.layers.push(this);
  62807. var engine = this._scene.getEngine();
  62808. // VBO
  62809. var vertices = [];
  62810. vertices.push(1, 1);
  62811. vertices.push(-1, 1);
  62812. vertices.push(-1, -1);
  62813. vertices.push(1, -1);
  62814. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  62815. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  62816. // Indices
  62817. var indices = [];
  62818. indices.push(0);
  62819. indices.push(1);
  62820. indices.push(2);
  62821. indices.push(0);
  62822. indices.push(2);
  62823. indices.push(3);
  62824. this._indexBuffer = engine.createIndexBuffer(indices);
  62825. // Effects
  62826. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  62827. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  62828. }
  62829. Object.defineProperty(Layer.prototype, "onDispose", {
  62830. set: function (callback) {
  62831. if (this._onDisposeObserver) {
  62832. this.onDisposeObservable.remove(this._onDisposeObserver);
  62833. }
  62834. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  62835. },
  62836. enumerable: true,
  62837. configurable: true
  62838. });
  62839. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  62840. set: function (callback) {
  62841. if (this._onBeforeRenderObserver) {
  62842. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62843. }
  62844. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62845. },
  62846. enumerable: true,
  62847. configurable: true
  62848. });
  62849. Object.defineProperty(Layer.prototype, "onAfterRender", {
  62850. set: function (callback) {
  62851. if (this._onAfterRenderObserver) {
  62852. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62853. }
  62854. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62855. },
  62856. enumerable: true,
  62857. configurable: true
  62858. });
  62859. Layer.prototype.render = function () {
  62860. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  62861. // Check
  62862. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  62863. return;
  62864. var engine = this._scene.getEngine();
  62865. this.onBeforeRenderObservable.notifyObservers(this);
  62866. // Render
  62867. engine.enableEffect(currentEffect);
  62868. engine.setState(false);
  62869. // Texture
  62870. currentEffect.setTexture("textureSampler", this.texture);
  62871. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  62872. // Color
  62873. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  62874. // Scale / offset
  62875. currentEffect.setVector2("offset", this.offset);
  62876. currentEffect.setVector2("scale", this.scale);
  62877. // VBOs
  62878. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  62879. // Draw order
  62880. if (!this.alphaTest) {
  62881. engine.setAlphaMode(this.alphaBlendingMode);
  62882. engine.draw(true, 0, 6);
  62883. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62884. }
  62885. else {
  62886. engine.draw(true, 0, 6);
  62887. }
  62888. this.onAfterRenderObservable.notifyObservers(this);
  62889. };
  62890. Layer.prototype.dispose = function () {
  62891. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62892. if (vertexBuffer) {
  62893. vertexBuffer.dispose();
  62894. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62895. }
  62896. if (this._indexBuffer) {
  62897. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  62898. this._indexBuffer = null;
  62899. }
  62900. if (this.texture) {
  62901. this.texture.dispose();
  62902. this.texture = null;
  62903. }
  62904. // Remove from scene
  62905. var index = this._scene.layers.indexOf(this);
  62906. this._scene.layers.splice(index, 1);
  62907. // Callback
  62908. this.onDisposeObservable.notifyObservers(this);
  62909. this.onDisposeObservable.clear();
  62910. this.onAfterRenderObservable.clear();
  62911. this.onBeforeRenderObservable.clear();
  62912. };
  62913. return Layer;
  62914. }());
  62915. BABYLON.Layer = Layer;
  62916. })(BABYLON || (BABYLON = {}));
  62917. //# sourceMappingURL=babylon.layer.js.map
  62918. 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<shadowsVertexDeclaration>[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#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\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#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\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<shadowsVertexDeclaration>[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#include<fresnelFunction>\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#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\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#ifdef OVERLOADEDVALUES\nambientOcclusionColor.rgb=mix(ambientOcclusionColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a*vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#else\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#endif\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.rgb;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo.rgb=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#else\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface=microSurfaceTexel.r;\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\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 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\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\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\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#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=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=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=lightDiffuseContribution*surfaceAlbedoContribution;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=(lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=(shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution;\n#endif\n#else\nvec3 finalDiffuse=lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor;\n#endif\n#endif\n#endif\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution+=vAmbientColor;\nshadowedOnlyLightDiffuseContribution*=surfaceAlbedo.rgb;\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution,0.0);\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\nfinalDiffuse=(finalDiffuse*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance)*ambientOcclusionColor;\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\nvec4 finalColor=vec4(finalDiffuse+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#ifdef EMISSIVEASILLUMINATION\nfinalColor.rgb+=(surfaceEmissiveColor*vLightingIntensity.y);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\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;\nvarying vec4 vPosition;\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>\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 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 FULLFLOAT\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 vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nuniform vec2 biasAndScale;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5; \n#endif\ndepth+=biasAndScale.x;\n#ifdef ESM\ndepth=exp(-min(87.,biasAndScale.y*depth));\n#endif\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\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;\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\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\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}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,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","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(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\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(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","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\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(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\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() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\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(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\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(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\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{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\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;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,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}","fxaaPixelShader":"varying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\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 sampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nvec2 sampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nvec2 sampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nvec2 sampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nvec2 sampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nvec2 sampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nvec2 sampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nvec2 sampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\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}","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}","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,1.0);\nelse{\ngl_FragColor=vec4(texture2D(textureSampler,tc).rgb,1.0);\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}"};
  62919. 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","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n","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(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\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":"mat3 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}","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(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{X};\n#endif\nuniform vec3 shadowsInfo{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};\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));\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));\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\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;\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;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvarying vec4 vPositionFromLight{X};\nuniform sampler2D shadowSampler{X};\n#else\nuniform samplerCube shadowSampler{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 SHADOWFULLFLOAT\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\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\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 SHADOWFULLFLOAT\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\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\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-darkness,0.,1.); \n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,esm,vOverloadedShadowIntensity.x);\n#else\nreturn esm;\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\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 SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<depth.z) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<depth.z) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<depth.z) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<depth.z) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,min(1.0,visibility+darkness),vOverloadedShadowIntensity.x);\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float depthScale)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 depth=0.5*clipSpace+vec3(0.5);\nvec2 uv=depth.xy;\nfloat shadowPixelDepth=depth.z;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\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-darkness,0.,1.); \n\n\n\n\n\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,esm,vOverloadedShadowIntensity.x);\n#else\nreturn esm;\n#endif\n}\n#endif","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}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\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\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#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,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 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#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x);\n#else\nshadow=computeShadow(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x);\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#if 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#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\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#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\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 vec4 opacityParts;\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\nuniform vec4 vOverloadedShadowIntensity;\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 kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\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/(kPi*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 specularColor,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); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \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 diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\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{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","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.0001));\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 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=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*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 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=max(0.00000000001,dot(vNormal,directionToLightCenterW));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*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 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=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\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,roughness,NdotV,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,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,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWESM{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#else\nnotShadowLevel=computeShadowWithESM(light{X}.vPositionFromLight,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z);\n#endif\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},light{X}.shadowsInfo.x);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif"};
  62920. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  62921. module.exports = BABYLON;
  62922. };