babylon.max.js 3.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160
  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. return Quaternion;
  2665. }());
  2666. BABYLON.Quaternion = Quaternion;
  2667. var Matrix = (function () {
  2668. function Matrix() {
  2669. this.m = new Float32Array(16);
  2670. this._markAsUpdated();
  2671. }
  2672. Matrix.prototype._markAsUpdated = function () {
  2673. this.updateFlag = Matrix._updateFlagSeed++;
  2674. };
  2675. // Properties
  2676. /**
  2677. * Boolean : True is the matrix is the identity matrix
  2678. */
  2679. Matrix.prototype.isIdentity = function () {
  2680. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  2681. return false;
  2682. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2683. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2684. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2685. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  2686. return false;
  2687. return true;
  2688. };
  2689. /**
  2690. * Returns the matrix determinant (float).
  2691. */
  2692. Matrix.prototype.determinant = function () {
  2693. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2694. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2695. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2696. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2697. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2698. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2699. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2700. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2701. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2702. };
  2703. // Methods
  2704. /**
  2705. * Returns the matrix underlying array.
  2706. */
  2707. Matrix.prototype.toArray = function () {
  2708. return this.m;
  2709. };
  2710. /**
  2711. * Returns the matrix underlying array.
  2712. */
  2713. Matrix.prototype.asArray = function () {
  2714. return this.toArray();
  2715. };
  2716. /**
  2717. * Inverts in place the Matrix.
  2718. * Returns the Matrix inverted.
  2719. */
  2720. Matrix.prototype.invert = function () {
  2721. this.invertToRef(this);
  2722. return this;
  2723. };
  2724. /**
  2725. * Sets all the matrix elements to zero.
  2726. * Returns the Matrix.
  2727. */
  2728. Matrix.prototype.reset = function () {
  2729. for (var index = 0; index < 16; index++) {
  2730. this.m[index] = 0.0;
  2731. }
  2732. this._markAsUpdated();
  2733. return this;
  2734. };
  2735. /**
  2736. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2737. */
  2738. Matrix.prototype.add = function (other) {
  2739. var result = new Matrix();
  2740. this.addToRef(other, result);
  2741. return result;
  2742. };
  2743. /**
  2744. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2745. * Returns the Matrix.
  2746. */
  2747. Matrix.prototype.addToRef = function (other, result) {
  2748. for (var index = 0; index < 16; index++) {
  2749. result.m[index] = this.m[index] + other.m[index];
  2750. }
  2751. result._markAsUpdated();
  2752. return this;
  2753. };
  2754. /**
  2755. * Adds in place the passed matrix to the current Matrix.
  2756. * Returns the updated Matrix.
  2757. */
  2758. Matrix.prototype.addToSelf = function (other) {
  2759. for (var index = 0; index < 16; index++) {
  2760. this.m[index] += other.m[index];
  2761. }
  2762. this._markAsUpdated();
  2763. return this;
  2764. };
  2765. /**
  2766. * Sets the passed matrix with the current inverted Matrix.
  2767. * Returns the unmodified current Matrix.
  2768. */
  2769. Matrix.prototype.invertToRef = function (other) {
  2770. var l1 = this.m[0];
  2771. var l2 = this.m[1];
  2772. var l3 = this.m[2];
  2773. var l4 = this.m[3];
  2774. var l5 = this.m[4];
  2775. var l6 = this.m[5];
  2776. var l7 = this.m[6];
  2777. var l8 = this.m[7];
  2778. var l9 = this.m[8];
  2779. var l10 = this.m[9];
  2780. var l11 = this.m[10];
  2781. var l12 = this.m[11];
  2782. var l13 = this.m[12];
  2783. var l14 = this.m[13];
  2784. var l15 = this.m[14];
  2785. var l16 = this.m[15];
  2786. var l17 = (l11 * l16) - (l12 * l15);
  2787. var l18 = (l10 * l16) - (l12 * l14);
  2788. var l19 = (l10 * l15) - (l11 * l14);
  2789. var l20 = (l9 * l16) - (l12 * l13);
  2790. var l21 = (l9 * l15) - (l11 * l13);
  2791. var l22 = (l9 * l14) - (l10 * l13);
  2792. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2793. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2794. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2795. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2796. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2797. var l28 = (l7 * l16) - (l8 * l15);
  2798. var l29 = (l6 * l16) - (l8 * l14);
  2799. var l30 = (l6 * l15) - (l7 * l14);
  2800. var l31 = (l5 * l16) - (l8 * l13);
  2801. var l32 = (l5 * l15) - (l7 * l13);
  2802. var l33 = (l5 * l14) - (l6 * l13);
  2803. var l34 = (l7 * l12) - (l8 * l11);
  2804. var l35 = (l6 * l12) - (l8 * l10);
  2805. var l36 = (l6 * l11) - (l7 * l10);
  2806. var l37 = (l5 * l12) - (l8 * l9);
  2807. var l38 = (l5 * l11) - (l7 * l9);
  2808. var l39 = (l5 * l10) - (l6 * l9);
  2809. other.m[0] = l23 * l27;
  2810. other.m[4] = l24 * l27;
  2811. other.m[8] = l25 * l27;
  2812. other.m[12] = l26 * l27;
  2813. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2814. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2815. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2816. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2817. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2818. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2819. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2820. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2821. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2822. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2823. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2824. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2825. other._markAsUpdated();
  2826. return this;
  2827. };
  2828. /**
  2829. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2830. * Returns the updated Matrix.
  2831. */
  2832. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2833. this.m[12] = x;
  2834. this.m[13] = y;
  2835. this.m[14] = z;
  2836. this._markAsUpdated();
  2837. return this;
  2838. };
  2839. /**
  2840. * Inserts the translation vector in the current Matrix.
  2841. * Returns the updated Matrix.
  2842. */
  2843. Matrix.prototype.setTranslation = function (vector3) {
  2844. this.m[12] = vector3.x;
  2845. this.m[13] = vector3.y;
  2846. this.m[14] = vector3.z;
  2847. this._markAsUpdated();
  2848. return this;
  2849. };
  2850. /**
  2851. * Returns a new Vector3 as the extracted translation from the Matrix.
  2852. */
  2853. Matrix.prototype.getTranslation = function () {
  2854. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2855. };
  2856. /**
  2857. * Fill a Vector3 with the extracted translation from the Matrix.
  2858. */
  2859. Matrix.prototype.getTranslationToRef = function (result) {
  2860. result.x = this.m[12];
  2861. result.y = this.m[13];
  2862. result.z = this.m[14];
  2863. return this;
  2864. };
  2865. /**
  2866. * Remove rotation and scaling part from the Matrix.
  2867. * Returns the updated Matrix.
  2868. */
  2869. Matrix.prototype.removeRotationAndScaling = function () {
  2870. this.setRowFromFloats(0, 1, 0, 0, 0);
  2871. this.setRowFromFloats(1, 0, 1, 0, 0);
  2872. this.setRowFromFloats(2, 0, 0, 1, 0);
  2873. return this;
  2874. };
  2875. /**
  2876. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2877. */
  2878. Matrix.prototype.multiply = function (other) {
  2879. var result = new Matrix();
  2880. this.multiplyToRef(other, result);
  2881. return result;
  2882. };
  2883. /**
  2884. * Updates the current Matrix from the passed one values.
  2885. * Returns the updated Matrix.
  2886. */
  2887. Matrix.prototype.copyFrom = function (other) {
  2888. for (var index = 0; index < 16; index++) {
  2889. this.m[index] = other.m[index];
  2890. }
  2891. this._markAsUpdated();
  2892. return this;
  2893. };
  2894. /**
  2895. * Populates the passed array from the starting index with the Matrix values.
  2896. * Returns the Matrix.
  2897. */
  2898. Matrix.prototype.copyToArray = function (array, offset) {
  2899. if (offset === void 0) { offset = 0; }
  2900. for (var index = 0; index < 16; index++) {
  2901. array[offset + index] = this.m[index];
  2902. }
  2903. return this;
  2904. };
  2905. /**
  2906. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2907. */
  2908. Matrix.prototype.multiplyToRef = function (other, result) {
  2909. this.multiplyToArray(other, result.m, 0);
  2910. result._markAsUpdated();
  2911. return this;
  2912. };
  2913. /**
  2914. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2915. */
  2916. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2917. var tm0 = this.m[0];
  2918. var tm1 = this.m[1];
  2919. var tm2 = this.m[2];
  2920. var tm3 = this.m[3];
  2921. var tm4 = this.m[4];
  2922. var tm5 = this.m[5];
  2923. var tm6 = this.m[6];
  2924. var tm7 = this.m[7];
  2925. var tm8 = this.m[8];
  2926. var tm9 = this.m[9];
  2927. var tm10 = this.m[10];
  2928. var tm11 = this.m[11];
  2929. var tm12 = this.m[12];
  2930. var tm13 = this.m[13];
  2931. var tm14 = this.m[14];
  2932. var tm15 = this.m[15];
  2933. var om0 = other.m[0];
  2934. var om1 = other.m[1];
  2935. var om2 = other.m[2];
  2936. var om3 = other.m[3];
  2937. var om4 = other.m[4];
  2938. var om5 = other.m[5];
  2939. var om6 = other.m[6];
  2940. var om7 = other.m[7];
  2941. var om8 = other.m[8];
  2942. var om9 = other.m[9];
  2943. var om10 = other.m[10];
  2944. var om11 = other.m[11];
  2945. var om12 = other.m[12];
  2946. var om13 = other.m[13];
  2947. var om14 = other.m[14];
  2948. var om15 = other.m[15];
  2949. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2950. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2951. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  2952. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  2953. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  2954. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  2955. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  2956. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  2957. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  2958. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  2959. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  2960. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  2961. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  2962. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  2963. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  2964. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  2965. return this;
  2966. };
  2967. /**
  2968. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  2969. */
  2970. Matrix.prototype.equals = function (value) {
  2971. return value &&
  2972. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  2973. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  2974. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  2975. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  2976. };
  2977. /**
  2978. * Returns a new Matrix from the current Matrix.
  2979. */
  2980. Matrix.prototype.clone = function () {
  2981. 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]);
  2982. };
  2983. /**
  2984. * Returns the string "Matrix"
  2985. */
  2986. Matrix.prototype.getClassName = function () {
  2987. return "Matrix";
  2988. };
  2989. /**
  2990. * Returns the Matrix hash code.
  2991. */
  2992. Matrix.prototype.getHashCode = function () {
  2993. var hash = this.m[0] || 0;
  2994. for (var i = 1; i < 16; i++) {
  2995. hash = (hash * 397) ^ (this.m[i] || 0);
  2996. }
  2997. return hash;
  2998. };
  2999. /**
  3000. * Decomposes the current Matrix into :
  3001. * - a scale vector3 passed as a reference to update,
  3002. * - a rotation quaternion passed as a reference to update,
  3003. * - a translation vector3 passed as a reference to update.
  3004. * Returns the boolean `true`.
  3005. */
  3006. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3007. translation.x = this.m[12];
  3008. translation.y = this.m[13];
  3009. translation.z = this.m[14];
  3010. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  3011. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  3012. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  3013. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3014. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3015. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3016. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3017. rotation.x = 0;
  3018. rotation.y = 0;
  3019. rotation.z = 0;
  3020. rotation.w = 1;
  3021. return false;
  3022. }
  3023. 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]);
  3024. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3025. return true;
  3026. };
  3027. /**
  3028. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3029. */
  3030. Matrix.prototype.getRotationMatrix = function () {
  3031. var result = Matrix.Identity();
  3032. this.getRotationMatrixToRef(result);
  3033. return result;
  3034. };
  3035. /**
  3036. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3037. * Returns the current Matrix.
  3038. */
  3039. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3040. var m = this.m;
  3041. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3042. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3043. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3044. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3045. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3046. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3047. 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);
  3048. return this;
  3049. };
  3050. // Statics
  3051. /**
  3052. * Returns a new Matrix set from the starting index of the passed array.
  3053. */
  3054. Matrix.FromArray = function (array, offset) {
  3055. var result = new Matrix();
  3056. if (!offset) {
  3057. offset = 0;
  3058. }
  3059. Matrix.FromArrayToRef(array, offset, result);
  3060. return result;
  3061. };
  3062. /**
  3063. * Sets the passed "result" matrix from the starting index of the passed array.
  3064. */
  3065. Matrix.FromArrayToRef = function (array, offset, result) {
  3066. for (var index = 0; index < 16; index++) {
  3067. result.m[index] = array[index + offset];
  3068. }
  3069. result._markAsUpdated();
  3070. };
  3071. /**
  3072. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3073. */
  3074. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3075. for (var index = 0; index < 16; index++) {
  3076. result.m[index] = array[index + offset] * scale;
  3077. }
  3078. result._markAsUpdated();
  3079. };
  3080. /**
  3081. * Sets the passed matrix "result" with the 16 passed floats.
  3082. */
  3083. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3084. result.m[0] = initialM11;
  3085. result.m[1] = initialM12;
  3086. result.m[2] = initialM13;
  3087. result.m[3] = initialM14;
  3088. result.m[4] = initialM21;
  3089. result.m[5] = initialM22;
  3090. result.m[6] = initialM23;
  3091. result.m[7] = initialM24;
  3092. result.m[8] = initialM31;
  3093. result.m[9] = initialM32;
  3094. result.m[10] = initialM33;
  3095. result.m[11] = initialM34;
  3096. result.m[12] = initialM41;
  3097. result.m[13] = initialM42;
  3098. result.m[14] = initialM43;
  3099. result.m[15] = initialM44;
  3100. result._markAsUpdated();
  3101. };
  3102. /**
  3103. * Returns the index-th row of the current matrix as a new Vector4.
  3104. */
  3105. Matrix.prototype.getRow = function (index) {
  3106. if (index < 0 || index > 3) {
  3107. return null;
  3108. }
  3109. var i = index * 4;
  3110. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3111. };
  3112. /**
  3113. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3114. * Returns the updated Matrix.
  3115. */
  3116. Matrix.prototype.setRow = function (index, row) {
  3117. if (index < 0 || index > 3) {
  3118. return this;
  3119. }
  3120. var i = index * 4;
  3121. this.m[i + 0] = row.x;
  3122. this.m[i + 1] = row.y;
  3123. this.m[i + 2] = row.z;
  3124. this.m[i + 3] = row.w;
  3125. this._markAsUpdated();
  3126. return this;
  3127. };
  3128. /**
  3129. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3130. * Returns the updated Matrix.
  3131. */
  3132. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3133. if (index < 0 || index > 3) {
  3134. return this;
  3135. }
  3136. var i = index * 4;
  3137. this.m[i + 0] = x;
  3138. this.m[i + 1] = y;
  3139. this.m[i + 2] = z;
  3140. this.m[i + 3] = w;
  3141. this._markAsUpdated();
  3142. return this;
  3143. };
  3144. /**
  3145. * Returns a new Matrix set from the 16 passed floats.
  3146. */
  3147. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3148. var result = new Matrix();
  3149. result.m[0] = initialM11;
  3150. result.m[1] = initialM12;
  3151. result.m[2] = initialM13;
  3152. result.m[3] = initialM14;
  3153. result.m[4] = initialM21;
  3154. result.m[5] = initialM22;
  3155. result.m[6] = initialM23;
  3156. result.m[7] = initialM24;
  3157. result.m[8] = initialM31;
  3158. result.m[9] = initialM32;
  3159. result.m[10] = initialM33;
  3160. result.m[11] = initialM34;
  3161. result.m[12] = initialM41;
  3162. result.m[13] = initialM42;
  3163. result.m[14] = initialM43;
  3164. result.m[15] = initialM44;
  3165. return result;
  3166. };
  3167. /**
  3168. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3169. */
  3170. Matrix.Compose = function (scale, rotation, translation) {
  3171. var result = Matrix.Identity();
  3172. Matrix.ComposeToRef(scale, rotation, translation, result);
  3173. return result;
  3174. };
  3175. /**
  3176. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3177. */
  3178. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3179. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3180. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3181. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3182. result.setTranslation(translation);
  3183. };
  3184. /**
  3185. * Returns a new indentity Matrix.
  3186. */
  3187. Matrix.Identity = function () {
  3188. 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);
  3189. };
  3190. /**
  3191. * Sets the passed "result" as an identity matrix.
  3192. */
  3193. Matrix.IdentityToRef = function (result) {
  3194. 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);
  3195. };
  3196. /**
  3197. * Returns a new zero Matrix.
  3198. */
  3199. Matrix.Zero = function () {
  3200. 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);
  3201. };
  3202. /**
  3203. * Returns a new rotation matrix for "angle" radians around the X axis.
  3204. */
  3205. Matrix.RotationX = function (angle) {
  3206. var result = new Matrix();
  3207. Matrix.RotationXToRef(angle, result);
  3208. return result;
  3209. };
  3210. /**
  3211. * Returns a new Matrix as the passed inverted one.
  3212. */
  3213. Matrix.Invert = function (source) {
  3214. var result = new Matrix();
  3215. source.invertToRef(result);
  3216. return result;
  3217. };
  3218. /**
  3219. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3220. */
  3221. Matrix.RotationXToRef = function (angle, result) {
  3222. var s = Math.sin(angle);
  3223. var c = Math.cos(angle);
  3224. result.m[0] = 1.0;
  3225. result.m[15] = 1.0;
  3226. result.m[5] = c;
  3227. result.m[10] = c;
  3228. result.m[9] = -s;
  3229. result.m[6] = s;
  3230. result.m[1] = 0.0;
  3231. result.m[2] = 0.0;
  3232. result.m[3] = 0.0;
  3233. result.m[4] = 0.0;
  3234. result.m[7] = 0.0;
  3235. result.m[8] = 0.0;
  3236. result.m[11] = 0.0;
  3237. result.m[12] = 0.0;
  3238. result.m[13] = 0.0;
  3239. result.m[14] = 0.0;
  3240. result._markAsUpdated();
  3241. };
  3242. /**
  3243. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3244. */
  3245. Matrix.RotationY = function (angle) {
  3246. var result = new Matrix();
  3247. Matrix.RotationYToRef(angle, result);
  3248. return result;
  3249. };
  3250. /**
  3251. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3252. */
  3253. Matrix.RotationYToRef = function (angle, result) {
  3254. var s = Math.sin(angle);
  3255. var c = Math.cos(angle);
  3256. result.m[5] = 1.0;
  3257. result.m[15] = 1.0;
  3258. result.m[0] = c;
  3259. result.m[2] = -s;
  3260. result.m[8] = s;
  3261. result.m[10] = c;
  3262. result.m[1] = 0.0;
  3263. result.m[3] = 0.0;
  3264. result.m[4] = 0.0;
  3265. result.m[6] = 0.0;
  3266. result.m[7] = 0.0;
  3267. result.m[9] = 0.0;
  3268. result.m[11] = 0.0;
  3269. result.m[12] = 0.0;
  3270. result.m[13] = 0.0;
  3271. result.m[14] = 0.0;
  3272. result._markAsUpdated();
  3273. };
  3274. /**
  3275. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3276. */
  3277. Matrix.RotationZ = function (angle) {
  3278. var result = new Matrix();
  3279. Matrix.RotationZToRef(angle, result);
  3280. return result;
  3281. };
  3282. /**
  3283. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3284. */
  3285. Matrix.RotationZToRef = function (angle, result) {
  3286. var s = Math.sin(angle);
  3287. var c = Math.cos(angle);
  3288. result.m[10] = 1.0;
  3289. result.m[15] = 1.0;
  3290. result.m[0] = c;
  3291. result.m[1] = s;
  3292. result.m[4] = -s;
  3293. result.m[5] = c;
  3294. result.m[2] = 0.0;
  3295. result.m[3] = 0.0;
  3296. result.m[6] = 0.0;
  3297. result.m[7] = 0.0;
  3298. result.m[8] = 0.0;
  3299. result.m[9] = 0.0;
  3300. result.m[11] = 0.0;
  3301. result.m[12] = 0.0;
  3302. result.m[13] = 0.0;
  3303. result.m[14] = 0.0;
  3304. result._markAsUpdated();
  3305. };
  3306. /**
  3307. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3308. */
  3309. Matrix.RotationAxis = function (axis, angle) {
  3310. var result = Matrix.Zero();
  3311. Matrix.RotationAxisToRef(axis, angle, result);
  3312. return result;
  3313. };
  3314. /**
  3315. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3316. */
  3317. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3318. var s = Math.sin(-angle);
  3319. var c = Math.cos(-angle);
  3320. var c1 = 1 - c;
  3321. axis.normalize();
  3322. result.m[0] = (axis.x * axis.x) * c1 + c;
  3323. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3324. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3325. result.m[3] = 0.0;
  3326. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3327. result.m[5] = (axis.y * axis.y) * c1 + c;
  3328. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3329. result.m[7] = 0.0;
  3330. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3331. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3332. result.m[10] = (axis.z * axis.z) * c1 + c;
  3333. result.m[11] = 0.0;
  3334. result.m[15] = 1.0;
  3335. result._markAsUpdated();
  3336. };
  3337. /**
  3338. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3339. */
  3340. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3341. var result = new Matrix();
  3342. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3343. return result;
  3344. };
  3345. /**
  3346. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3347. */
  3348. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3349. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3350. this._tempQuaternion.toRotationMatrix(result);
  3351. };
  3352. /**
  3353. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3354. */
  3355. Matrix.Scaling = function (x, y, z) {
  3356. var result = Matrix.Zero();
  3357. Matrix.ScalingToRef(x, y, z, result);
  3358. return result;
  3359. };
  3360. /**
  3361. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3362. */
  3363. Matrix.ScalingToRef = function (x, y, z, result) {
  3364. result.m[0] = x;
  3365. result.m[1] = 0.0;
  3366. result.m[2] = 0.0;
  3367. result.m[3] = 0.0;
  3368. result.m[4] = 0.0;
  3369. result.m[5] = y;
  3370. result.m[6] = 0.0;
  3371. result.m[7] = 0.0;
  3372. result.m[8] = 0.0;
  3373. result.m[9] = 0.0;
  3374. result.m[10] = z;
  3375. result.m[11] = 0.0;
  3376. result.m[12] = 0.0;
  3377. result.m[13] = 0.0;
  3378. result.m[14] = 0.0;
  3379. result.m[15] = 1.0;
  3380. result._markAsUpdated();
  3381. };
  3382. /**
  3383. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3384. */
  3385. Matrix.Translation = function (x, y, z) {
  3386. var result = Matrix.Identity();
  3387. Matrix.TranslationToRef(x, y, z, result);
  3388. return result;
  3389. };
  3390. /**
  3391. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3392. */
  3393. Matrix.TranslationToRef = function (x, y, z, result) {
  3394. 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);
  3395. };
  3396. /**
  3397. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3398. */
  3399. Matrix.Lerp = function (startValue, endValue, gradient) {
  3400. var result = Matrix.Zero();
  3401. for (var index = 0; index < 16; index++) {
  3402. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3403. }
  3404. result._markAsUpdated();
  3405. return result;
  3406. };
  3407. /**
  3408. * Returns a new Matrix whose values are computed by :
  3409. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3410. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3411. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3412. */
  3413. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3414. var startScale = new Vector3(0, 0, 0);
  3415. var startRotation = new Quaternion();
  3416. var startTranslation = new Vector3(0, 0, 0);
  3417. startValue.decompose(startScale, startRotation, startTranslation);
  3418. var endScale = new Vector3(0, 0, 0);
  3419. var endRotation = new Quaternion();
  3420. var endTranslation = new Vector3(0, 0, 0);
  3421. endValue.decompose(endScale, endRotation, endTranslation);
  3422. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3423. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3424. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3425. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3426. };
  3427. /**
  3428. * 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".
  3429. * This methods works for a Left-Handed system.
  3430. */
  3431. Matrix.LookAtLH = function (eye, target, up) {
  3432. var result = Matrix.Zero();
  3433. Matrix.LookAtLHToRef(eye, target, up, result);
  3434. return result;
  3435. };
  3436. /**
  3437. * 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".
  3438. * This methods works for a Left-Handed system.
  3439. */
  3440. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3441. // Z axis
  3442. target.subtractToRef(eye, this._zAxis);
  3443. this._zAxis.normalize();
  3444. // X axis
  3445. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3446. if (this._xAxis.lengthSquared() === 0) {
  3447. this._xAxis.x = 1.0;
  3448. }
  3449. else {
  3450. this._xAxis.normalize();
  3451. }
  3452. // Y axis
  3453. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3454. this._yAxis.normalize();
  3455. // Eye angles
  3456. var ex = -Vector3.Dot(this._xAxis, eye);
  3457. var ey = -Vector3.Dot(this._yAxis, eye);
  3458. var ez = -Vector3.Dot(this._zAxis, eye);
  3459. 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);
  3460. };
  3461. /**
  3462. * 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".
  3463. * This methods works for a Right-Handed system.
  3464. */
  3465. Matrix.LookAtRH = function (eye, target, up) {
  3466. var result = Matrix.Zero();
  3467. Matrix.LookAtRHToRef(eye, target, up, result);
  3468. return result;
  3469. };
  3470. /**
  3471. * 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".
  3472. * This methods works for a Left-Handed system.
  3473. */
  3474. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3475. // Z axis
  3476. eye.subtractToRef(target, this._zAxis);
  3477. this._zAxis.normalize();
  3478. // X axis
  3479. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3480. if (this._xAxis.lengthSquared() === 0) {
  3481. this._xAxis.x = 1.0;
  3482. }
  3483. else {
  3484. this._xAxis.normalize();
  3485. }
  3486. // Y axis
  3487. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3488. this._yAxis.normalize();
  3489. // Eye angles
  3490. var ex = -Vector3.Dot(this._xAxis, eye);
  3491. var ey = -Vector3.Dot(this._yAxis, eye);
  3492. var ez = -Vector3.Dot(this._zAxis, eye);
  3493. 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);
  3494. };
  3495. /**
  3496. * 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.
  3497. */
  3498. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3499. var matrix = Matrix.Zero();
  3500. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3501. return matrix;
  3502. };
  3503. /**
  3504. * 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.
  3505. */
  3506. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3507. var n = znear;
  3508. var f = zfar;
  3509. var a = 2.0 / width;
  3510. var b = 2.0 / height;
  3511. var c = 2.0 / (f - n);
  3512. var d = -(f + n) / (f - n);
  3513. 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);
  3514. };
  3515. /**
  3516. * 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.
  3517. */
  3518. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3519. var matrix = Matrix.Zero();
  3520. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3521. return matrix;
  3522. };
  3523. /**
  3524. * 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.
  3525. */
  3526. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3527. var n = znear;
  3528. var f = zfar;
  3529. var a = 2.0 / (right - left);
  3530. var b = 2.0 / (top - bottom);
  3531. var c = 2.0 / (f - n);
  3532. var d = -(f + n) / (f - n);
  3533. var i0 = (left + right) / (left - right);
  3534. var i1 = (top + bottom) / (bottom - top);
  3535. 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);
  3536. };
  3537. /**
  3538. * 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.
  3539. */
  3540. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3541. var matrix = Matrix.Zero();
  3542. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3543. return matrix;
  3544. };
  3545. /**
  3546. * 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.
  3547. */
  3548. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3549. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3550. result.m[10] *= -1.0;
  3551. };
  3552. /**
  3553. * 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.
  3554. */
  3555. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3556. var matrix = Matrix.Zero();
  3557. var n = znear;
  3558. var f = zfar;
  3559. var a = 2.0 * n / width;
  3560. var b = 2.0 * n / height;
  3561. var c = (f + n) / (f - n);
  3562. var d = -2.0 * f * n / (f - n);
  3563. 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);
  3564. return matrix;
  3565. };
  3566. /**
  3567. * 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.
  3568. */
  3569. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3570. var matrix = Matrix.Zero();
  3571. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3572. return matrix;
  3573. };
  3574. /**
  3575. * 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.
  3576. */
  3577. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3578. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3579. var n = znear;
  3580. var f = zfar;
  3581. var t = 1.0 / (Math.tan(fov * 0.5));
  3582. var a = isVerticalFovFixed ? (t / aspect) : t;
  3583. var b = isVerticalFovFixed ? t : (t * aspect);
  3584. var c = (f + n) / (f - n);
  3585. var d = -2.0 * f * n / (f - n);
  3586. 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);
  3587. };
  3588. /**
  3589. * 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.
  3590. */
  3591. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3592. var matrix = Matrix.Zero();
  3593. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3594. return matrix;
  3595. };
  3596. /**
  3597. * 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.
  3598. */
  3599. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3600. //alternatively this could be expressed as:
  3601. // m = PerspectiveFovLHToRef
  3602. // m[10] *= -1.0;
  3603. // m[11] *= -1.0;
  3604. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3605. var n = znear;
  3606. var f = zfar;
  3607. var t = 1.0 / (Math.tan(fov * 0.5));
  3608. var a = isVerticalFovFixed ? (t / aspect) : t;
  3609. var b = isVerticalFovFixed ? t : (t * aspect);
  3610. var c = -(f + n) / (f - n);
  3611. var d = -2 * f * n / (f - n);
  3612. 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);
  3613. };
  3614. /**
  3615. * 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.
  3616. */
  3617. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3618. if (rightHanded === void 0) { rightHanded = false; }
  3619. var rightHandedFactor = rightHanded ? -1 : 1;
  3620. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3621. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3622. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3623. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3624. var xScale = 2.0 / (leftTan + rightTan);
  3625. var yScale = 2.0 / (upTan + downTan);
  3626. result.m[0] = xScale;
  3627. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3628. result.m[5] = yScale;
  3629. result.m[6] = result.m[7] = 0.0;
  3630. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3631. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3632. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3633. result.m[10] = -zfar / (znear - zfar);
  3634. result.m[11] = 1.0 * rightHandedFactor;
  3635. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3636. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3637. // result.m[14] = (znear * zfar) / (znear - zfar);
  3638. result._markAsUpdated();
  3639. };
  3640. /**
  3641. * Returns the final transformation matrix : world * view * projection * viewport
  3642. */
  3643. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3644. var cw = viewport.width;
  3645. var ch = viewport.height;
  3646. var cx = viewport.x;
  3647. var cy = viewport.y;
  3648. 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);
  3649. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3650. };
  3651. /**
  3652. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3653. */
  3654. Matrix.GetAsMatrix2x2 = function (matrix) {
  3655. return new Float32Array([
  3656. matrix.m[0], matrix.m[1],
  3657. matrix.m[4], matrix.m[5]
  3658. ]);
  3659. };
  3660. /**
  3661. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3662. */
  3663. Matrix.GetAsMatrix3x3 = function (matrix) {
  3664. return new Float32Array([
  3665. matrix.m[0], matrix.m[1], matrix.m[2],
  3666. matrix.m[4], matrix.m[5], matrix.m[6],
  3667. matrix.m[8], matrix.m[9], matrix.m[10]
  3668. ]);
  3669. };
  3670. /**
  3671. * Compute the transpose of the passed Matrix.
  3672. * Returns a new Matrix.
  3673. */
  3674. Matrix.Transpose = function (matrix) {
  3675. var result = new Matrix();
  3676. result.m[0] = matrix.m[0];
  3677. result.m[1] = matrix.m[4];
  3678. result.m[2] = matrix.m[8];
  3679. result.m[3] = matrix.m[12];
  3680. result.m[4] = matrix.m[1];
  3681. result.m[5] = matrix.m[5];
  3682. result.m[6] = matrix.m[9];
  3683. result.m[7] = matrix.m[13];
  3684. result.m[8] = matrix.m[2];
  3685. result.m[9] = matrix.m[6];
  3686. result.m[10] = matrix.m[10];
  3687. result.m[11] = matrix.m[14];
  3688. result.m[12] = matrix.m[3];
  3689. result.m[13] = matrix.m[7];
  3690. result.m[14] = matrix.m[11];
  3691. result.m[15] = matrix.m[15];
  3692. return result;
  3693. };
  3694. /**
  3695. * Returns a new Matrix as the reflection matrix across the passed plane.
  3696. */
  3697. Matrix.Reflection = function (plane) {
  3698. var matrix = new Matrix();
  3699. Matrix.ReflectionToRef(plane, matrix);
  3700. return matrix;
  3701. };
  3702. /**
  3703. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3704. */
  3705. Matrix.ReflectionToRef = function (plane, result) {
  3706. plane.normalize();
  3707. var x = plane.normal.x;
  3708. var y = plane.normal.y;
  3709. var z = plane.normal.z;
  3710. var temp = -2 * x;
  3711. var temp2 = -2 * y;
  3712. var temp3 = -2 * z;
  3713. result.m[0] = (temp * x) + 1;
  3714. result.m[1] = temp2 * x;
  3715. result.m[2] = temp3 * x;
  3716. result.m[3] = 0.0;
  3717. result.m[4] = temp * y;
  3718. result.m[5] = (temp2 * y) + 1;
  3719. result.m[6] = temp3 * y;
  3720. result.m[7] = 0.0;
  3721. result.m[8] = temp * z;
  3722. result.m[9] = temp2 * z;
  3723. result.m[10] = (temp3 * z) + 1;
  3724. result.m[11] = 0.0;
  3725. result.m[12] = temp * plane.d;
  3726. result.m[13] = temp2 * plane.d;
  3727. result.m[14] = temp3 * plane.d;
  3728. result.m[15] = 1.0;
  3729. result._markAsUpdated();
  3730. };
  3731. /**
  3732. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3733. */
  3734. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3735. result.m[0] = xaxis.x;
  3736. result.m[1] = xaxis.y;
  3737. result.m[2] = xaxis.z;
  3738. result.m[3] = 0.0;
  3739. result.m[4] = yaxis.x;
  3740. result.m[5] = yaxis.y;
  3741. result.m[6] = yaxis.z;
  3742. result.m[7] = 0.0;
  3743. result.m[8] = zaxis.x;
  3744. result.m[9] = zaxis.y;
  3745. result.m[10] = zaxis.z;
  3746. result.m[11] = 0.0;
  3747. result.m[12] = 0.0;
  3748. result.m[13] = 0.0;
  3749. result.m[14] = 0.0;
  3750. result.m[15] = 1.0;
  3751. result._markAsUpdated();
  3752. };
  3753. /**
  3754. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3755. */
  3756. Matrix.FromQuaternionToRef = function (quat, result) {
  3757. var xx = quat.x * quat.x;
  3758. var yy = quat.y * quat.y;
  3759. var zz = quat.z * quat.z;
  3760. var xy = quat.x * quat.y;
  3761. var zw = quat.z * quat.w;
  3762. var zx = quat.z * quat.x;
  3763. var yw = quat.y * quat.w;
  3764. var yz = quat.y * quat.z;
  3765. var xw = quat.x * quat.w;
  3766. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3767. result.m[1] = 2.0 * (xy + zw);
  3768. result.m[2] = 2.0 * (zx - yw);
  3769. result.m[3] = 0.0;
  3770. result.m[4] = 2.0 * (xy - zw);
  3771. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3772. result.m[6] = 2.0 * (yz + xw);
  3773. result.m[7] = 0.0;
  3774. result.m[8] = 2.0 * (zx + yw);
  3775. result.m[9] = 2.0 * (yz - xw);
  3776. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3777. result.m[11] = 0.0;
  3778. result.m[12] = 0.0;
  3779. result.m[13] = 0.0;
  3780. result.m[14] = 0.0;
  3781. result.m[15] = 1.0;
  3782. result._markAsUpdated();
  3783. };
  3784. return Matrix;
  3785. }());
  3786. Matrix._tempQuaternion = new Quaternion();
  3787. Matrix._xAxis = Vector3.Zero();
  3788. Matrix._yAxis = Vector3.Zero();
  3789. Matrix._zAxis = Vector3.Zero();
  3790. Matrix._updateFlagSeed = 0;
  3791. BABYLON.Matrix = Matrix;
  3792. var Plane = (function () {
  3793. /**
  3794. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3795. */
  3796. function Plane(a, b, c, d) {
  3797. this.normal = new Vector3(a, b, c);
  3798. this.d = d;
  3799. }
  3800. /**
  3801. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3802. */
  3803. Plane.prototype.asArray = function () {
  3804. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3805. };
  3806. // Methods
  3807. /**
  3808. * Returns a new plane copied from the current Plane.
  3809. */
  3810. Plane.prototype.clone = function () {
  3811. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3812. };
  3813. /**
  3814. * Returns the string "Plane".
  3815. */
  3816. Plane.prototype.getClassName = function () {
  3817. return "Plane";
  3818. };
  3819. /**
  3820. * Returns the Plane hash code.
  3821. */
  3822. Plane.prototype.getHashCode = function () {
  3823. var hash = this.normal.getHashCode();
  3824. hash = (hash * 397) ^ (this.d || 0);
  3825. return hash;
  3826. };
  3827. /**
  3828. * Normalize the current Plane in place.
  3829. * Returns the updated Plane.
  3830. */
  3831. Plane.prototype.normalize = function () {
  3832. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3833. var magnitude = 0.0;
  3834. if (norm !== 0) {
  3835. magnitude = 1.0 / norm;
  3836. }
  3837. this.normal.x *= magnitude;
  3838. this.normal.y *= magnitude;
  3839. this.normal.z *= magnitude;
  3840. this.d *= magnitude;
  3841. return this;
  3842. };
  3843. /**
  3844. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3845. */
  3846. Plane.prototype.transform = function (transformation) {
  3847. var transposedMatrix = Matrix.Transpose(transformation);
  3848. var x = this.normal.x;
  3849. var y = this.normal.y;
  3850. var z = this.normal.z;
  3851. var d = this.d;
  3852. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3853. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3854. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3855. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3856. return new Plane(normalX, normalY, normalZ, finalD);
  3857. };
  3858. /**
  3859. * Returns the dot product (float) of the point coordinates and the plane normal.
  3860. */
  3861. Plane.prototype.dotCoordinate = function (point) {
  3862. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3863. };
  3864. /**
  3865. * Updates the current Plane from the plane defined by the three passed points.
  3866. * Returns the updated Plane.
  3867. */
  3868. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3869. var x1 = point2.x - point1.x;
  3870. var y1 = point2.y - point1.y;
  3871. var z1 = point2.z - point1.z;
  3872. var x2 = point3.x - point1.x;
  3873. var y2 = point3.y - point1.y;
  3874. var z2 = point3.z - point1.z;
  3875. var yz = (y1 * z2) - (z1 * y2);
  3876. var xz = (z1 * x2) - (x1 * z2);
  3877. var xy = (x1 * y2) - (y1 * x2);
  3878. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3879. var invPyth;
  3880. if (pyth !== 0) {
  3881. invPyth = 1.0 / pyth;
  3882. }
  3883. else {
  3884. invPyth = 0.0;
  3885. }
  3886. this.normal.x = yz * invPyth;
  3887. this.normal.y = xz * invPyth;
  3888. this.normal.z = xy * invPyth;
  3889. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3890. return this;
  3891. };
  3892. /**
  3893. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3894. */
  3895. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3896. var dot = Vector3.Dot(this.normal, direction);
  3897. return (dot <= epsilon);
  3898. };
  3899. /**
  3900. * Returns the signed distance (float) from the passed point to the Plane.
  3901. */
  3902. Plane.prototype.signedDistanceTo = function (point) {
  3903. return Vector3.Dot(point, this.normal) + this.d;
  3904. };
  3905. // Statics
  3906. /**
  3907. * Returns a new Plane from the passed array.
  3908. */
  3909. Plane.FromArray = function (array) {
  3910. return new Plane(array[0], array[1], array[2], array[3]);
  3911. };
  3912. /**
  3913. * Returns a new Plane defined by the three passed points.
  3914. */
  3915. Plane.FromPoints = function (point1, point2, point3) {
  3916. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3917. result.copyFromPoints(point1, point2, point3);
  3918. return result;
  3919. };
  3920. /**
  3921. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3922. * Note : the vector "normal" is updated because normalized.
  3923. */
  3924. Plane.FromPositionAndNormal = function (origin, normal) {
  3925. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3926. normal.normalize();
  3927. result.normal = normal;
  3928. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3929. return result;
  3930. };
  3931. /**
  3932. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3933. */
  3934. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3935. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3936. return Vector3.Dot(point, normal) + d;
  3937. };
  3938. return Plane;
  3939. }());
  3940. BABYLON.Plane = Plane;
  3941. var Viewport = (function () {
  3942. /**
  3943. * Creates a Viewport object located at (x, y) and sized (width, height).
  3944. */
  3945. function Viewport(x, y, width, height) {
  3946. this.x = x;
  3947. this.y = y;
  3948. this.width = width;
  3949. this.height = height;
  3950. }
  3951. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  3952. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  3953. };
  3954. /**
  3955. * Returns a new Viewport copied from the current one.
  3956. */
  3957. Viewport.prototype.clone = function () {
  3958. return new Viewport(this.x, this.y, this.width, this.height);
  3959. };
  3960. return Viewport;
  3961. }());
  3962. BABYLON.Viewport = Viewport;
  3963. var Frustum = (function () {
  3964. function Frustum() {
  3965. }
  3966. /**
  3967. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  3968. */
  3969. Frustum.GetPlanes = function (transform) {
  3970. var frustumPlanes = [];
  3971. for (var index = 0; index < 6; index++) {
  3972. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  3973. }
  3974. Frustum.GetPlanesToRef(transform, frustumPlanes);
  3975. return frustumPlanes;
  3976. };
  3977. /**
  3978. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  3979. */
  3980. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  3981. // Near
  3982. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  3983. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  3984. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  3985. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  3986. frustumPlanes[0].normalize();
  3987. // Far
  3988. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  3989. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  3990. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  3991. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  3992. frustumPlanes[1].normalize();
  3993. // Left
  3994. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  3995. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  3996. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  3997. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  3998. frustumPlanes[2].normalize();
  3999. // Right
  4000. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4001. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4002. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4003. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4004. frustumPlanes[3].normalize();
  4005. // Top
  4006. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4007. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4008. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4009. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4010. frustumPlanes[4].normalize();
  4011. // Bottom
  4012. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4013. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4014. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4015. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4016. frustumPlanes[5].normalize();
  4017. };
  4018. return Frustum;
  4019. }());
  4020. BABYLON.Frustum = Frustum;
  4021. var Space;
  4022. (function (Space) {
  4023. Space[Space["LOCAL"] = 0] = "LOCAL";
  4024. Space[Space["WORLD"] = 1] = "WORLD";
  4025. Space[Space["BONE"] = 2] = "BONE";
  4026. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4027. var Axis = (function () {
  4028. function Axis() {
  4029. }
  4030. return Axis;
  4031. }());
  4032. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4033. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4034. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4035. BABYLON.Axis = Axis;
  4036. ;
  4037. var BezierCurve = (function () {
  4038. function BezierCurve() {
  4039. }
  4040. /**
  4041. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4042. */
  4043. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4044. // Extract X (which is equal to time here)
  4045. var f0 = 1 - 3 * x2 + 3 * x1;
  4046. var f1 = 3 * x2 - 6 * x1;
  4047. var f2 = 3 * x1;
  4048. var refinedT = t;
  4049. for (var i = 0; i < 5; i++) {
  4050. var refinedT2 = refinedT * refinedT;
  4051. var refinedT3 = refinedT2 * refinedT;
  4052. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4053. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4054. refinedT -= (x - t) * slope;
  4055. refinedT = Math.min(1, Math.max(0, refinedT));
  4056. }
  4057. // Resolve cubic bezier for the given x
  4058. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4059. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4060. Math.pow(refinedT, 3);
  4061. };
  4062. return BezierCurve;
  4063. }());
  4064. BABYLON.BezierCurve = BezierCurve;
  4065. var Orientation;
  4066. (function (Orientation) {
  4067. Orientation[Orientation["CW"] = 0] = "CW";
  4068. Orientation[Orientation["CCW"] = 1] = "CCW";
  4069. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4070. var Angle = (function () {
  4071. /**
  4072. * Creates an Angle object of "radians" radians (float).
  4073. */
  4074. function Angle(radians) {
  4075. var _this = this;
  4076. /**
  4077. * Returns the Angle value in degrees (float).
  4078. */
  4079. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4080. /**
  4081. * Returns the Angle value in radians (float).
  4082. */
  4083. this.radians = function () { return _this._radians; };
  4084. this._radians = radians;
  4085. if (this._radians < 0.0)
  4086. this._radians += (2.0 * Math.PI);
  4087. }
  4088. /**
  4089. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4090. */
  4091. Angle.BetweenTwoPoints = function (a, b) {
  4092. var delta = b.subtract(a);
  4093. var theta = Math.atan2(delta.y, delta.x);
  4094. return new Angle(theta);
  4095. };
  4096. /**
  4097. * Returns a new Angle object from the passed float in radians.
  4098. */
  4099. Angle.FromRadians = function (radians) {
  4100. return new Angle(radians);
  4101. };
  4102. /**
  4103. * Returns a new Angle object from the passed float in degrees.
  4104. */
  4105. Angle.FromDegrees = function (degrees) {
  4106. return new Angle(degrees * Math.PI / 180.0);
  4107. };
  4108. return Angle;
  4109. }());
  4110. BABYLON.Angle = Angle;
  4111. var Arc2 = (function () {
  4112. /**
  4113. * Creates an Arc object from the three passed points : start, middle and end.
  4114. */
  4115. function Arc2(startPoint, midPoint, endPoint) {
  4116. this.startPoint = startPoint;
  4117. this.midPoint = midPoint;
  4118. this.endPoint = endPoint;
  4119. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4120. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4121. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4122. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4123. 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);
  4124. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4125. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4126. var a1 = this.startAngle.degrees();
  4127. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4128. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4129. // angles correction
  4130. if (a2 - a1 > +180.0)
  4131. a2 -= 360.0;
  4132. if (a2 - a1 < -180.0)
  4133. a2 += 360.0;
  4134. if (a3 - a2 > +180.0)
  4135. a3 -= 360.0;
  4136. if (a3 - a2 < -180.0)
  4137. a3 += 360.0;
  4138. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4139. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4140. }
  4141. return Arc2;
  4142. }());
  4143. BABYLON.Arc2 = Arc2;
  4144. var Path2 = (function () {
  4145. /**
  4146. * Creates a Path2 object from the starting 2D coordinates x and y.
  4147. */
  4148. function Path2(x, y) {
  4149. this._points = new Array();
  4150. this._length = 0.0;
  4151. this.closed = false;
  4152. this._points.push(new Vector2(x, y));
  4153. }
  4154. /**
  4155. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4156. * Returns the updated Path2.
  4157. */
  4158. Path2.prototype.addLineTo = function (x, y) {
  4159. if (closed) {
  4160. //Tools.Error("cannot add lines to closed paths");
  4161. return this;
  4162. }
  4163. var newPoint = new Vector2(x, y);
  4164. var previousPoint = this._points[this._points.length - 1];
  4165. this._points.push(newPoint);
  4166. this._length += newPoint.subtract(previousPoint).length();
  4167. return this;
  4168. };
  4169. /**
  4170. * 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.
  4171. * Returns the updated Path2.
  4172. */
  4173. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4174. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4175. if (closed) {
  4176. //Tools.Error("cannot add arcs to closed paths");
  4177. return this;
  4178. }
  4179. var startPoint = this._points[this._points.length - 1];
  4180. var midPoint = new Vector2(midX, midY);
  4181. var endPoint = new Vector2(endX, endY);
  4182. var arc = new Arc2(startPoint, midPoint, endPoint);
  4183. var increment = arc.angle.radians() / numberOfSegments;
  4184. if (arc.orientation === Orientation.CW)
  4185. increment *= -1;
  4186. var currentAngle = arc.startAngle.radians() + increment;
  4187. for (var i = 0; i < numberOfSegments; i++) {
  4188. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4189. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4190. this.addLineTo(x, y);
  4191. currentAngle += increment;
  4192. }
  4193. return this;
  4194. };
  4195. /**
  4196. * Closes the Path2.
  4197. * Returns the Path2.
  4198. */
  4199. Path2.prototype.close = function () {
  4200. this.closed = true;
  4201. return this;
  4202. };
  4203. /**
  4204. * Returns the Path2 total length (float).
  4205. */
  4206. Path2.prototype.length = function () {
  4207. var result = this._length;
  4208. if (!this.closed) {
  4209. var lastPoint = this._points[this._points.length - 1];
  4210. var firstPoint = this._points[0];
  4211. result += (firstPoint.subtract(lastPoint).length());
  4212. }
  4213. return result;
  4214. };
  4215. /**
  4216. * Returns the Path2 internal array of points.
  4217. */
  4218. Path2.prototype.getPoints = function () {
  4219. return this._points;
  4220. };
  4221. /**
  4222. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4223. */
  4224. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4225. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4226. //Tools.Error("normalized length position should be between 0 and 1.");
  4227. return Vector2.Zero();
  4228. }
  4229. var lengthPosition = normalizedLengthPosition * this.length();
  4230. var previousOffset = 0;
  4231. for (var i = 0; i < this._points.length; i++) {
  4232. var j = (i + 1) % this._points.length;
  4233. var a = this._points[i];
  4234. var b = this._points[j];
  4235. var bToA = b.subtract(a);
  4236. var nextOffset = (bToA.length() + previousOffset);
  4237. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4238. var dir = bToA.normalize();
  4239. var localOffset = lengthPosition - previousOffset;
  4240. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4241. }
  4242. previousOffset = nextOffset;
  4243. }
  4244. //Tools.Error("internal error");
  4245. return Vector2.Zero();
  4246. };
  4247. /**
  4248. * Returns a new Path2 starting at the coordinates (x, y).
  4249. */
  4250. Path2.StartingAt = function (x, y) {
  4251. return new Path2(x, y);
  4252. };
  4253. return Path2;
  4254. }());
  4255. BABYLON.Path2 = Path2;
  4256. var Path3D = (function () {
  4257. /**
  4258. * new Path3D(path, normal, raw)
  4259. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4260. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4261. * path : an array of Vector3, the curve axis of the Path3D
  4262. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4263. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4264. */
  4265. function Path3D(path, firstNormal, raw) {
  4266. this.path = path;
  4267. this._curve = new Array();
  4268. this._distances = new Array();
  4269. this._tangents = new Array();
  4270. this._normals = new Array();
  4271. this._binormals = new Array();
  4272. for (var p = 0; p < path.length; p++) {
  4273. this._curve[p] = path[p].clone(); // hard copy
  4274. }
  4275. this._raw = raw || false;
  4276. this._compute(firstNormal);
  4277. }
  4278. /**
  4279. * Returns the Path3D array of successive Vector3 designing its curve.
  4280. */
  4281. Path3D.prototype.getCurve = function () {
  4282. return this._curve;
  4283. };
  4284. /**
  4285. * Returns an array populated with tangent vectors on each Path3D curve point.
  4286. */
  4287. Path3D.prototype.getTangents = function () {
  4288. return this._tangents;
  4289. };
  4290. /**
  4291. * Returns an array populated with normal vectors on each Path3D curve point.
  4292. */
  4293. Path3D.prototype.getNormals = function () {
  4294. return this._normals;
  4295. };
  4296. /**
  4297. * Returns an array populated with binormal vectors on each Path3D curve point.
  4298. */
  4299. Path3D.prototype.getBinormals = function () {
  4300. return this._binormals;
  4301. };
  4302. /**
  4303. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4304. */
  4305. Path3D.prototype.getDistances = function () {
  4306. return this._distances;
  4307. };
  4308. /**
  4309. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4310. * Returns the same object updated.
  4311. */
  4312. Path3D.prototype.update = function (path, firstNormal) {
  4313. for (var p = 0; p < path.length; p++) {
  4314. this._curve[p].x = path[p].x;
  4315. this._curve[p].y = path[p].y;
  4316. this._curve[p].z = path[p].z;
  4317. }
  4318. this._compute(firstNormal);
  4319. return this;
  4320. };
  4321. // private function compute() : computes tangents, normals and binormals
  4322. Path3D.prototype._compute = function (firstNormal) {
  4323. var l = this._curve.length;
  4324. // first and last tangents
  4325. this._tangents[0] = this._getFirstNonNullVector(0);
  4326. if (!this._raw) {
  4327. this._tangents[0].normalize();
  4328. }
  4329. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4330. if (!this._raw) {
  4331. this._tangents[l - 1].normalize();
  4332. }
  4333. // normals and binormals at first point : arbitrary vector with _normalVector()
  4334. var tg0 = this._tangents[0];
  4335. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4336. this._normals[0] = pp0;
  4337. if (!this._raw) {
  4338. this._normals[0].normalize();
  4339. }
  4340. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4341. if (!this._raw) {
  4342. this._binormals[0].normalize();
  4343. }
  4344. this._distances[0] = 0.0;
  4345. // normals and binormals : next points
  4346. var prev; // previous vector (segment)
  4347. var cur; // current vector (segment)
  4348. var curTang; // current tangent
  4349. // previous normal
  4350. var prevBinor; // previous binormal
  4351. for (var i = 1; i < l; i++) {
  4352. // tangents
  4353. prev = this._getLastNonNullVector(i);
  4354. if (i < l - 1) {
  4355. cur = this._getFirstNonNullVector(i);
  4356. this._tangents[i] = prev.add(cur);
  4357. this._tangents[i].normalize();
  4358. }
  4359. this._distances[i] = this._distances[i - 1] + prev.length();
  4360. // normals and binormals
  4361. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4362. curTang = this._tangents[i];
  4363. prevBinor = this._binormals[i - 1];
  4364. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4365. if (!this._raw) {
  4366. this._normals[i].normalize();
  4367. }
  4368. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4369. if (!this._raw) {
  4370. this._binormals[i].normalize();
  4371. }
  4372. }
  4373. };
  4374. // private function getFirstNonNullVector(index)
  4375. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4376. Path3D.prototype._getFirstNonNullVector = function (index) {
  4377. var i = 1;
  4378. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4379. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4380. i++;
  4381. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4382. }
  4383. return nNVector;
  4384. };
  4385. // private function getLastNonNullVector(index)
  4386. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4387. Path3D.prototype._getLastNonNullVector = function (index) {
  4388. var i = 1;
  4389. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4390. while (nLVector.length() === 0 && index > i + 1) {
  4391. i++;
  4392. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4393. }
  4394. return nLVector;
  4395. };
  4396. // private function normalVector(v0, vt, va) :
  4397. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4398. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4399. Path3D.prototype._normalVector = function (v0, vt, va) {
  4400. var normal0;
  4401. var tgl = vt.length();
  4402. if (tgl === 0.0) {
  4403. tgl = 1.0;
  4404. }
  4405. if (va === undefined || va === null) {
  4406. var point;
  4407. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4408. point = new Vector3(0.0, -1.0, 0.0);
  4409. }
  4410. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4411. point = new Vector3(1.0, 0.0, 0.0);
  4412. }
  4413. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4414. point = new Vector3(0.0, 0.0, 1.0);
  4415. }
  4416. normal0 = Vector3.Cross(vt, point);
  4417. }
  4418. else {
  4419. normal0 = Vector3.Cross(vt, va);
  4420. Vector3.CrossToRef(normal0, vt, normal0);
  4421. }
  4422. normal0.normalize();
  4423. return normal0;
  4424. };
  4425. return Path3D;
  4426. }());
  4427. BABYLON.Path3D = Path3D;
  4428. var Curve3 = (function () {
  4429. /**
  4430. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4431. * A Curve3 is designed from a series of successive Vector3.
  4432. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4433. */
  4434. function Curve3(points) {
  4435. this._length = 0.0;
  4436. this._points = points;
  4437. this._length = this._computeLength(points);
  4438. }
  4439. /**
  4440. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4441. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4442. * @param v1 (Vector3) the control point
  4443. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4444. * @param nbPoints (integer) the wanted number of points in the curve
  4445. */
  4446. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4447. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4448. var bez = new Array();
  4449. var equation = function (t, val0, val1, val2) {
  4450. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4451. return res;
  4452. };
  4453. for (var i = 0; i <= nbPoints; i++) {
  4454. 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)));
  4455. }
  4456. return new Curve3(bez);
  4457. };
  4458. /**
  4459. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4460. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4461. * @param v1 (Vector3) the first control point
  4462. * @param v2 (Vector3) the second control point
  4463. * @param v3 (Vector3) the end point of the Cubic Bezier
  4464. * @param nbPoints (integer) the wanted number of points in the curve
  4465. */
  4466. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4467. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4468. var bez = new Array();
  4469. var equation = function (t, val0, val1, val2, val3) {
  4470. 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;
  4471. return res;
  4472. };
  4473. for (var i = 0; i <= nbPoints; i++) {
  4474. 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)));
  4475. }
  4476. return new Curve3(bez);
  4477. };
  4478. /**
  4479. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4480. * @param p1 (Vector3) the origin point of the Hermite Spline
  4481. * @param t1 (Vector3) the tangent vector at the origin point
  4482. * @param p2 (Vector3) the end point of the Hermite Spline
  4483. * @param t2 (Vector3) the tangent vector at the end point
  4484. * @param nbPoints (integer) the wanted number of points in the curve
  4485. */
  4486. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4487. var hermite = new Array();
  4488. var step = 1.0 / nbPoints;
  4489. for (var i = 0; i <= nbPoints; i++) {
  4490. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4491. }
  4492. return new Curve3(hermite);
  4493. };
  4494. /**
  4495. * Returns a Curve3 object along a CatmullRom Spline curve :
  4496. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4497. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4498. */
  4499. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4500. var totalPoints = new Array();
  4501. totalPoints.push(points[0].clone());
  4502. Array.prototype.push.apply(totalPoints, points);
  4503. totalPoints.push(points[points.length - 1].clone());
  4504. var catmullRom = new Array();
  4505. var step = 1.0 / nbPoints;
  4506. for (var i = 0; i < totalPoints.length - 3; i++) {
  4507. var amount = 0.0;
  4508. for (var c = 0; c < nbPoints; c++) {
  4509. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4510. amount += step;
  4511. }
  4512. }
  4513. i--;
  4514. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4515. return new Curve3(catmullRom);
  4516. };
  4517. /**
  4518. * Returns the Curve3 stored array of successive Vector3
  4519. */
  4520. Curve3.prototype.getPoints = function () {
  4521. return this._points;
  4522. };
  4523. /**
  4524. * Returns the computed length (float) of the curve.
  4525. */
  4526. Curve3.prototype.length = function () {
  4527. return this._length;
  4528. };
  4529. /**
  4530. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4531. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4532. * curveA and curveB keep unchanged.
  4533. */
  4534. Curve3.prototype.continue = function (curve) {
  4535. var lastPoint = this._points[this._points.length - 1];
  4536. var continuedPoints = this._points.slice();
  4537. var curvePoints = curve.getPoints();
  4538. for (var i = 1; i < curvePoints.length; i++) {
  4539. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4540. }
  4541. var continuedCurve = new Curve3(continuedPoints);
  4542. return continuedCurve;
  4543. };
  4544. Curve3.prototype._computeLength = function (path) {
  4545. var l = 0;
  4546. for (var i = 1; i < path.length; i++) {
  4547. l += (path[i].subtract(path[i - 1])).length();
  4548. }
  4549. return l;
  4550. };
  4551. return Curve3;
  4552. }());
  4553. BABYLON.Curve3 = Curve3;
  4554. // SphericalHarmonics
  4555. var SphericalHarmonics = (function () {
  4556. function SphericalHarmonics() {
  4557. this.L00 = Vector3.Zero();
  4558. this.L1_1 = Vector3.Zero();
  4559. this.L10 = Vector3.Zero();
  4560. this.L11 = Vector3.Zero();
  4561. this.L2_2 = Vector3.Zero();
  4562. this.L2_1 = Vector3.Zero();
  4563. this.L20 = Vector3.Zero();
  4564. this.L21 = Vector3.Zero();
  4565. this.L22 = Vector3.Zero();
  4566. }
  4567. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  4568. var colorVector = new Vector3(color.r, color.g, color.b);
  4569. var c = colorVector.scale(deltaSolidAngle);
  4570. this.L00 = this.L00.add(c.scale(0.282095));
  4571. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  4572. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  4573. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  4574. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  4575. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  4576. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  4577. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  4578. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  4579. };
  4580. SphericalHarmonics.prototype.scale = function (scale) {
  4581. this.L00 = this.L00.scale(scale);
  4582. this.L1_1 = this.L1_1.scale(scale);
  4583. this.L10 = this.L10.scale(scale);
  4584. this.L11 = this.L11.scale(scale);
  4585. this.L2_2 = this.L2_2.scale(scale);
  4586. this.L2_1 = this.L2_1.scale(scale);
  4587. this.L20 = this.L20.scale(scale);
  4588. this.L21 = this.L21.scale(scale);
  4589. this.L22 = this.L22.scale(scale);
  4590. };
  4591. return SphericalHarmonics;
  4592. }());
  4593. BABYLON.SphericalHarmonics = SphericalHarmonics;
  4594. // SphericalPolynomial
  4595. var SphericalPolynomial = (function () {
  4596. function SphericalPolynomial() {
  4597. this.x = Vector3.Zero();
  4598. this.y = Vector3.Zero();
  4599. this.z = Vector3.Zero();
  4600. this.xx = Vector3.Zero();
  4601. this.yy = Vector3.Zero();
  4602. this.zz = Vector3.Zero();
  4603. this.xy = Vector3.Zero();
  4604. this.yz = Vector3.Zero();
  4605. this.zx = Vector3.Zero();
  4606. }
  4607. SphericalPolynomial.prototype.addAmbient = function (color) {
  4608. var colorVector = new Vector3(color.r, color.g, color.b);
  4609. this.xx = this.xx.add(colorVector);
  4610. this.yy = this.yy.add(colorVector);
  4611. this.zz = this.zz.add(colorVector);
  4612. };
  4613. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  4614. var result = new SphericalPolynomial();
  4615. result.x = harmonics.L11.scale(1.02333);
  4616. result.y = harmonics.L1_1.scale(1.02333);
  4617. result.z = harmonics.L10.scale(1.02333);
  4618. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  4619. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  4620. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  4621. result.yz = harmonics.L2_1.scale(0.858086);
  4622. result.zx = harmonics.L21.scale(0.858086);
  4623. result.xy = harmonics.L2_2.scale(0.858086);
  4624. return result;
  4625. };
  4626. return SphericalPolynomial;
  4627. }());
  4628. BABYLON.SphericalPolynomial = SphericalPolynomial;
  4629. // Vertex formats
  4630. var PositionNormalVertex = (function () {
  4631. function PositionNormalVertex(position, normal) {
  4632. if (position === void 0) { position = Vector3.Zero(); }
  4633. if (normal === void 0) { normal = Vector3.Up(); }
  4634. this.position = position;
  4635. this.normal = normal;
  4636. }
  4637. PositionNormalVertex.prototype.clone = function () {
  4638. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4639. };
  4640. return PositionNormalVertex;
  4641. }());
  4642. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4643. var PositionNormalTextureVertex = (function () {
  4644. function PositionNormalTextureVertex(position, normal, uv) {
  4645. if (position === void 0) { position = Vector3.Zero(); }
  4646. if (normal === void 0) { normal = Vector3.Up(); }
  4647. if (uv === void 0) { uv = Vector2.Zero(); }
  4648. this.position = position;
  4649. this.normal = normal;
  4650. this.uv = uv;
  4651. }
  4652. PositionNormalTextureVertex.prototype.clone = function () {
  4653. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4654. };
  4655. return PositionNormalTextureVertex;
  4656. }());
  4657. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4658. // Temporary pre-allocated objects for engine internal use
  4659. // usage in any internal function :
  4660. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4661. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4662. var Tmp = (function () {
  4663. function Tmp() {
  4664. }
  4665. return Tmp;
  4666. }());
  4667. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4668. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4669. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4670. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4671. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4672. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4673. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4674. Matrix.Zero(), Matrix.Zero(),
  4675. Matrix.Zero(), Matrix.Zero(),
  4676. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4677. BABYLON.Tmp = Tmp;
  4678. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4679. var MathTmp = (function () {
  4680. function MathTmp() {
  4681. }
  4682. return MathTmp;
  4683. }());
  4684. MathTmp.Vector3 = [Vector3.Zero()];
  4685. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4686. MathTmp.Quaternion = [Quaternion.Zero()];
  4687. })(BABYLON || (BABYLON = {}));
  4688. //# sourceMappingURL=babylon.math.js.map
  4689. //# sourceMappingURL=babylon.mixins.js.map
  4690. var BABYLON;
  4691. (function (BABYLON) {
  4692. function generateSerializableMember(type, sourceName) {
  4693. return function (target, propertyKey) {
  4694. if (!target.__serializableMembers) {
  4695. target.__serializableMembers = {};
  4696. }
  4697. if (!target.__serializableMembers[propertyKey]) {
  4698. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  4699. }
  4700. };
  4701. }
  4702. function generateExpandMember(setCallback) {
  4703. return function (target, propertyKey) {
  4704. if (setCallback) {
  4705. var key = "_" + propertyKey;
  4706. Object.defineProperty(target, propertyKey, {
  4707. get: function () {
  4708. return this[key];
  4709. },
  4710. set: function (value) {
  4711. if (this[key] === value) {
  4712. return;
  4713. }
  4714. this[key] = value;
  4715. target[setCallback].apply(this);
  4716. },
  4717. enumerable: true,
  4718. configurable: true
  4719. });
  4720. }
  4721. };
  4722. }
  4723. function expandToProperty(callback) {
  4724. return generateExpandMember(callback);
  4725. }
  4726. BABYLON.expandToProperty = expandToProperty;
  4727. function serialize(sourceName) {
  4728. return generateSerializableMember(0, sourceName); // value member
  4729. }
  4730. BABYLON.serialize = serialize;
  4731. function serializeAsTexture(sourceName) {
  4732. return generateSerializableMember(1, sourceName); // texture member
  4733. }
  4734. BABYLON.serializeAsTexture = serializeAsTexture;
  4735. function serializeAsColor3(sourceName) {
  4736. return generateSerializableMember(2, sourceName); // color3 member
  4737. }
  4738. BABYLON.serializeAsColor3 = serializeAsColor3;
  4739. function serializeAsFresnelParameters(sourceName) {
  4740. return generateSerializableMember(3, sourceName); // fresnel parameters member
  4741. }
  4742. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  4743. function serializeAsVector2(sourceName) {
  4744. return generateSerializableMember(4, sourceName); // vector2 member
  4745. }
  4746. BABYLON.serializeAsVector2 = serializeAsVector2;
  4747. function serializeAsVector3(sourceName) {
  4748. return generateSerializableMember(5, sourceName); // vector3 member
  4749. }
  4750. BABYLON.serializeAsVector3 = serializeAsVector3;
  4751. function serializeAsMeshReference(sourceName) {
  4752. return generateSerializableMember(6, sourceName); // mesh reference member
  4753. }
  4754. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  4755. function serializeAsColorCurves(sourceName) {
  4756. return generateSerializableMember(7, sourceName); // color curves
  4757. }
  4758. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  4759. var SerializationHelper = (function () {
  4760. function SerializationHelper() {
  4761. }
  4762. SerializationHelper.Serialize = function (entity, serializationObject) {
  4763. if (!serializationObject) {
  4764. serializationObject = {};
  4765. }
  4766. // Tags
  4767. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  4768. // Properties
  4769. for (var property in entity.__serializableMembers) {
  4770. var propertyDescriptor = entity.__serializableMembers[property];
  4771. var targetPropertyName = propertyDescriptor.sourceName || property;
  4772. var propertyType = propertyDescriptor.type;
  4773. var sourceProperty = entity[property];
  4774. if (sourceProperty !== undefined && sourceProperty !== null) {
  4775. switch (propertyType) {
  4776. case 0:
  4777. serializationObject[targetPropertyName] = sourceProperty;
  4778. break;
  4779. case 1:
  4780. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4781. break;
  4782. case 2:
  4783. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4784. break;
  4785. case 3:
  4786. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4787. break;
  4788. case 4:
  4789. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4790. break;
  4791. case 5:
  4792. serializationObject[targetPropertyName] = sourceProperty.asArray();
  4793. break;
  4794. case 6:
  4795. serializationObject[targetPropertyName] = sourceProperty.id;
  4796. break;
  4797. case 7:
  4798. serializationObject[targetPropertyName] = sourceProperty.serialize();
  4799. break;
  4800. }
  4801. }
  4802. }
  4803. return serializationObject;
  4804. };
  4805. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  4806. var destination = creationFunction();
  4807. // Tags
  4808. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4809. // Properties
  4810. for (var property in destination.__serializableMembers) {
  4811. var propertyDescriptor = destination.__serializableMembers[property];
  4812. var sourceProperty = source[propertyDescriptor.sourceName || property];
  4813. var propertyType = propertyDescriptor.type;
  4814. if (sourceProperty !== undefined && sourceProperty !== null) {
  4815. switch (propertyType) {
  4816. case 0:
  4817. destination[property] = sourceProperty;
  4818. break;
  4819. case 1:
  4820. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  4821. break;
  4822. case 2:
  4823. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  4824. break;
  4825. case 3:
  4826. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  4827. break;
  4828. case 4:
  4829. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  4830. break;
  4831. case 5:
  4832. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  4833. break;
  4834. case 6:
  4835. destination[property] = scene.getLastMeshByID(sourceProperty);
  4836. break;
  4837. case 7:
  4838. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  4839. break;
  4840. }
  4841. }
  4842. }
  4843. return destination;
  4844. };
  4845. SerializationHelper.Clone = function (creationFunction, source) {
  4846. var destination = creationFunction();
  4847. // Tags
  4848. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4849. // Properties
  4850. for (var property in destination.__serializableMembers) {
  4851. var propertyDescriptor = destination.__serializableMembers[property];
  4852. var sourceProperty = source[property];
  4853. var propertyType = propertyDescriptor.type;
  4854. if (sourceProperty !== undefined && sourceProperty !== null) {
  4855. switch (propertyType) {
  4856. case 0: // Value
  4857. case 6:
  4858. destination[property] = sourceProperty;
  4859. break;
  4860. case 1: // Texture
  4861. case 2: // Color3
  4862. case 3: // FresnelParameters
  4863. case 4: // Vector2
  4864. case 5: // Vector3
  4865. case 7:
  4866. destination[property] = sourceProperty.clone();
  4867. break;
  4868. }
  4869. }
  4870. }
  4871. return destination;
  4872. };
  4873. return SerializationHelper;
  4874. }());
  4875. BABYLON.SerializationHelper = SerializationHelper;
  4876. })(BABYLON || (BABYLON = {}));
  4877. //# sourceMappingURL=babylon.decorators.js.map
  4878. var BABYLON;
  4879. (function (BABYLON) {
  4880. /**
  4881. * A class serves as a medium between the observable and its observers
  4882. */
  4883. var EventState = (function () {
  4884. /**
  4885. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  4886. */
  4887. function EventState(mask, skipNextObservers) {
  4888. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4889. this.initalize(mask, skipNextObservers);
  4890. }
  4891. EventState.prototype.initalize = function (mask, skipNextObservers) {
  4892. if (skipNextObservers === void 0) { skipNextObservers = false; }
  4893. this.mask = mask;
  4894. this.skipNextObservers = skipNextObservers;
  4895. return this;
  4896. };
  4897. return EventState;
  4898. }());
  4899. BABYLON.EventState = EventState;
  4900. /**
  4901. * Represent an Observer registered to a given Observable object.
  4902. */
  4903. var Observer = (function () {
  4904. function Observer(callback, mask) {
  4905. this.callback = callback;
  4906. this.mask = mask;
  4907. }
  4908. return Observer;
  4909. }());
  4910. BABYLON.Observer = Observer;
  4911. /**
  4912. * The Observable class is a simple implementation of the Observable pattern.
  4913. * 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.
  4914. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  4915. * 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).
  4916. * 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.
  4917. */
  4918. var Observable = (function () {
  4919. function Observable() {
  4920. this._observers = new Array();
  4921. this._eventState = new EventState(0);
  4922. }
  4923. /**
  4924. * Create a new Observer with the specified callback
  4925. * @param callback the callback that will be executed for that Observer
  4926. * @param mask the mask used to filter observers
  4927. * @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.
  4928. */
  4929. Observable.prototype.add = function (callback, mask, insertFirst) {
  4930. if (mask === void 0) { mask = -1; }
  4931. if (insertFirst === void 0) { insertFirst = false; }
  4932. if (!callback) {
  4933. return null;
  4934. }
  4935. var observer = new Observer(callback, mask);
  4936. if (insertFirst) {
  4937. this._observers.unshift(observer);
  4938. }
  4939. else {
  4940. this._observers.push(observer);
  4941. }
  4942. return observer;
  4943. };
  4944. /**
  4945. * Remove an Observer from the Observable object
  4946. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  4947. */
  4948. Observable.prototype.remove = function (observer) {
  4949. var index = this._observers.indexOf(observer);
  4950. if (index !== -1) {
  4951. this._observers.splice(index, 1);
  4952. return true;
  4953. }
  4954. return false;
  4955. };
  4956. /**
  4957. * Remove a callback from the Observable object
  4958. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  4959. */
  4960. Observable.prototype.removeCallback = function (callback) {
  4961. for (var index = 0; index < this._observers.length; index++) {
  4962. if (this._observers[index].callback === callback) {
  4963. this._observers.splice(index, 1);
  4964. return true;
  4965. }
  4966. }
  4967. return false;
  4968. };
  4969. /**
  4970. * Notify all Observers by calling their respective callback with the given data
  4971. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  4972. * @param eventData
  4973. * @param mask
  4974. */
  4975. Observable.prototype.notifyObservers = function (eventData, mask) {
  4976. if (mask === void 0) { mask = -1; }
  4977. var state = this._eventState;
  4978. state.mask = mask;
  4979. state.skipNextObservers = false;
  4980. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  4981. var obs = _a[_i];
  4982. if (obs.mask & mask) {
  4983. obs.callback(eventData, state);
  4984. }
  4985. if (state.skipNextObservers) {
  4986. return false;
  4987. }
  4988. }
  4989. return true;
  4990. };
  4991. /**
  4992. * return true is the Observable has at least one Observer registered
  4993. */
  4994. Observable.prototype.hasObservers = function () {
  4995. return this._observers.length > 0;
  4996. };
  4997. /**
  4998. * Clear the list of observers
  4999. */
  5000. Observable.prototype.clear = function () {
  5001. this._observers = new Array();
  5002. };
  5003. /**
  5004. * Clone the current observable
  5005. */
  5006. Observable.prototype.clone = function () {
  5007. var result = new Observable();
  5008. result._observers = this._observers.slice(0);
  5009. return result;
  5010. };
  5011. /**
  5012. * Does this observable handles observer registered with a given mask
  5013. * @param {number} trigger - the mask to be tested
  5014. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5015. **/
  5016. Observable.prototype.hasSpecificMask = function (mask) {
  5017. if (mask === void 0) { mask = -1; }
  5018. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5019. var obs = _a[_i];
  5020. if (obs.mask & mask && obs.mask === mask) {
  5021. return true;
  5022. }
  5023. }
  5024. return false;
  5025. };
  5026. return Observable;
  5027. }());
  5028. BABYLON.Observable = Observable;
  5029. })(BABYLON || (BABYLON = {}));
  5030. //# sourceMappingURL=babylon.observable.js.map
  5031. var BABYLON;
  5032. (function (BABYLON) {
  5033. var SmartArray = (function () {
  5034. function SmartArray(capacity) {
  5035. this.length = 0;
  5036. this._duplicateId = 0;
  5037. this.data = new Array(capacity);
  5038. this._id = SmartArray._GlobalId++;
  5039. }
  5040. SmartArray.prototype.push = function (value) {
  5041. this.data[this.length++] = value;
  5042. if (this.length > this.data.length) {
  5043. this.data.length *= 2;
  5044. }
  5045. if (!value.__smartArrayFlags) {
  5046. value.__smartArrayFlags = {};
  5047. }
  5048. value.__smartArrayFlags[this._id] = this._duplicateId;
  5049. };
  5050. SmartArray.prototype.forEach = function (func) {
  5051. for (var index = 0; index < this.length; index++) {
  5052. func(this.data[index]);
  5053. }
  5054. };
  5055. SmartArray.prototype.pushNoDuplicate = function (value) {
  5056. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5057. return false;
  5058. }
  5059. this.push(value);
  5060. return true;
  5061. };
  5062. SmartArray.prototype.sort = function (compareFn) {
  5063. this.data.sort(compareFn);
  5064. };
  5065. SmartArray.prototype.reset = function () {
  5066. this.length = 0;
  5067. this._duplicateId++;
  5068. };
  5069. SmartArray.prototype.dispose = function () {
  5070. this.reset();
  5071. this.data.length = 0;
  5072. };
  5073. SmartArray.prototype.concat = function (array) {
  5074. if (array.length === 0) {
  5075. return;
  5076. }
  5077. if (this.length + array.length > this.data.length) {
  5078. this.data.length = (this.length + array.length) * 2;
  5079. }
  5080. for (var index = 0; index < array.length; index++) {
  5081. this.data[this.length++] = (array.data || array)[index];
  5082. }
  5083. };
  5084. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5085. if (array.length === 0) {
  5086. return;
  5087. }
  5088. if (this.length + array.length > this.data.length) {
  5089. this.data.length = (this.length + array.length) * 2;
  5090. }
  5091. for (var index = 0; index < array.length; index++) {
  5092. var item = (array.data || array)[index];
  5093. this.pushNoDuplicate(item);
  5094. }
  5095. };
  5096. SmartArray.prototype.indexOf = function (value) {
  5097. var position = this.data.indexOf(value);
  5098. if (position >= this.length) {
  5099. return -1;
  5100. }
  5101. return position;
  5102. };
  5103. SmartArray.prototype.contains = function (value) {
  5104. return this.data.indexOf(value) !== -1;
  5105. };
  5106. return SmartArray;
  5107. }());
  5108. // Statics
  5109. SmartArray._GlobalId = 0;
  5110. BABYLON.SmartArray = SmartArray;
  5111. })(BABYLON || (BABYLON = {}));
  5112. //# sourceMappingURL=babylon.smartArray.js.map
  5113. var BABYLON;
  5114. (function (BABYLON) {
  5115. // Screenshots
  5116. var screenshotCanvas;
  5117. var cloneValue = function (source, destinationObject) {
  5118. if (!source)
  5119. return null;
  5120. if (source instanceof BABYLON.Mesh) {
  5121. return null;
  5122. }
  5123. if (source instanceof BABYLON.SubMesh) {
  5124. return source.clone(destinationObject);
  5125. }
  5126. else if (source.clone) {
  5127. return source.clone();
  5128. }
  5129. return null;
  5130. };
  5131. var Tools = (function () {
  5132. function Tools() {
  5133. }
  5134. ;
  5135. Tools.Instantiate = function (className) {
  5136. var arr = className.split(".");
  5137. var fn = (window || this);
  5138. for (var i = 0, len = arr.length; i < len; i++) {
  5139. fn = fn[arr[i]];
  5140. }
  5141. if (typeof fn !== "function") {
  5142. return null;
  5143. }
  5144. return fn;
  5145. };
  5146. Tools.SetImmediate = function (action) {
  5147. if (window.setImmediate) {
  5148. window.setImmediate(action);
  5149. }
  5150. else {
  5151. setTimeout(action, 1);
  5152. }
  5153. };
  5154. Tools.IsExponentOfTwo = function (value) {
  5155. var count = 1;
  5156. do {
  5157. count *= 2;
  5158. } while (count < value);
  5159. return count === value;
  5160. };
  5161. Tools.GetExponentOfTwo = function (value, max) {
  5162. var count = 1;
  5163. do {
  5164. count *= 2;
  5165. } while (count < value);
  5166. if (count > max)
  5167. count = max;
  5168. return count;
  5169. };
  5170. Tools.GetFilename = function (path) {
  5171. var index = path.lastIndexOf("/");
  5172. if (index < 0)
  5173. return path;
  5174. return path.substring(index + 1);
  5175. };
  5176. Tools.GetDOMTextContent = function (element) {
  5177. var result = "";
  5178. var child = element.firstChild;
  5179. while (child) {
  5180. if (child.nodeType === 3) {
  5181. result += child.textContent;
  5182. }
  5183. child = child.nextSibling;
  5184. }
  5185. return result;
  5186. };
  5187. Tools.ToDegrees = function (angle) {
  5188. return angle * 180 / Math.PI;
  5189. };
  5190. Tools.ToRadians = function (angle) {
  5191. return angle * Math.PI / 180;
  5192. };
  5193. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5194. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5195. var output = "";
  5196. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5197. var i = 0;
  5198. var bytes = new Uint8Array(buffer);
  5199. while (i < bytes.length) {
  5200. chr1 = bytes[i++];
  5201. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5202. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5203. enc1 = chr1 >> 2;
  5204. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5205. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5206. enc4 = chr3 & 63;
  5207. if (isNaN(chr2)) {
  5208. enc3 = enc4 = 64;
  5209. }
  5210. else if (isNaN(chr3)) {
  5211. enc4 = 64;
  5212. }
  5213. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5214. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5215. }
  5216. return "data:image/png;base64," + output;
  5217. };
  5218. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5219. if (bias === void 0) { bias = null; }
  5220. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5221. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5222. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5223. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5224. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5225. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5226. }
  5227. if (bias) {
  5228. minimum.x -= minimum.x * bias.x + bias.y;
  5229. minimum.y -= minimum.y * bias.x + bias.y;
  5230. minimum.z -= minimum.z * bias.x + bias.y;
  5231. maximum.x += maximum.x * bias.x + bias.y;
  5232. maximum.y += maximum.y * bias.x + bias.y;
  5233. maximum.z += maximum.z * bias.x + bias.y;
  5234. }
  5235. return {
  5236. minimum: minimum,
  5237. maximum: maximum
  5238. };
  5239. };
  5240. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5241. if (bias === void 0) { bias = null; }
  5242. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5243. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5244. if (!stride) {
  5245. stride = 3;
  5246. }
  5247. for (var index = start; index < start + count; index++) {
  5248. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5249. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5250. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5251. }
  5252. if (bias) {
  5253. minimum.x -= minimum.x * bias.x + bias.y;
  5254. minimum.y -= minimum.y * bias.x + bias.y;
  5255. minimum.z -= minimum.z * bias.x + bias.y;
  5256. maximum.x += maximum.x * bias.x + bias.y;
  5257. maximum.y += maximum.y * bias.x + bias.y;
  5258. maximum.z += maximum.z * bias.x + bias.y;
  5259. }
  5260. return {
  5261. minimum: minimum,
  5262. maximum: maximum
  5263. };
  5264. };
  5265. Tools.Vector2ArrayFeeder = function (array) {
  5266. return function (index) {
  5267. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5268. var length = isFloatArray ? array.length / 2 : array.length;
  5269. if (index >= length) {
  5270. return null;
  5271. }
  5272. if (isFloatArray) {
  5273. var fa = array;
  5274. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5275. }
  5276. var a = array;
  5277. return a[index];
  5278. };
  5279. };
  5280. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5281. if (bias === void 0) { bias = null; }
  5282. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5283. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5284. var i = 0;
  5285. var cur = feeder(i++);
  5286. while (cur) {
  5287. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5288. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5289. cur = feeder(i++);
  5290. }
  5291. if (bias) {
  5292. minimum.x -= minimum.x * bias.x + bias.y;
  5293. minimum.y -= minimum.y * bias.x + bias.y;
  5294. maximum.x += maximum.x * bias.x + bias.y;
  5295. maximum.y += maximum.y * bias.x + bias.y;
  5296. }
  5297. return {
  5298. minimum: minimum,
  5299. maximum: maximum
  5300. };
  5301. };
  5302. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5303. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5304. return undefined;
  5305. return Array.isArray(obj) ? obj : [obj];
  5306. };
  5307. // Misc.
  5308. Tools.GetPointerPrefix = function () {
  5309. var eventPrefix = "pointer";
  5310. // Check if pointer events are supported
  5311. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5312. eventPrefix = "mouse";
  5313. }
  5314. return eventPrefix;
  5315. };
  5316. /**
  5317. * @param func - the function to be called
  5318. * @param requester - the object that will request the next frame. Falls back to window.
  5319. */
  5320. Tools.QueueNewFrame = function (func, requester) {
  5321. if (requester === void 0) { requester = window; }
  5322. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5323. /*if(requester.isPresenting) {
  5324. return;
  5325. } else*/ if (requester.requestAnimationFrame)
  5326. requester.requestAnimationFrame(func);
  5327. else if (requester.msRequestAnimationFrame)
  5328. requester.msRequestAnimationFrame(func);
  5329. else if (requester.webkitRequestAnimationFrame)
  5330. requester.webkitRequestAnimationFrame(func);
  5331. else if (requester.mozRequestAnimationFrame)
  5332. requester.mozRequestAnimationFrame(func);
  5333. else if (requester.oRequestAnimationFrame)
  5334. requester.oRequestAnimationFrame(func);
  5335. else {
  5336. window.setTimeout(func, 16);
  5337. }
  5338. };
  5339. Tools.RequestFullscreen = function (element) {
  5340. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5341. if (!requestFunction)
  5342. return;
  5343. requestFunction.call(element);
  5344. };
  5345. Tools.ExitFullscreen = function () {
  5346. if (document.exitFullscreen) {
  5347. document.exitFullscreen();
  5348. }
  5349. else if (document.mozCancelFullScreen) {
  5350. document.mozCancelFullScreen();
  5351. }
  5352. else if (document.webkitCancelFullScreen) {
  5353. document.webkitCancelFullScreen();
  5354. }
  5355. else if (document.msCancelFullScreen) {
  5356. document.msCancelFullScreen();
  5357. }
  5358. };
  5359. Tools.SetCorsBehavior = function (url, img) {
  5360. if (Tools.CorsBehavior) {
  5361. switch (typeof (Tools.CorsBehavior)) {
  5362. case "function":
  5363. var result = Tools.CorsBehavior(url);
  5364. if (result) {
  5365. img.crossOrigin = result;
  5366. }
  5367. break;
  5368. case "string":
  5369. default:
  5370. img.crossOrigin = Tools.CorsBehavior;
  5371. break;
  5372. }
  5373. }
  5374. };
  5375. // External files
  5376. Tools.CleanUrl = function (url) {
  5377. url = url.replace(/#/mg, "%23");
  5378. return url;
  5379. };
  5380. Tools.LoadImage = function (url, onload, onerror, database) {
  5381. if (url instanceof ArrayBuffer) {
  5382. url = Tools.EncodeArrayBufferTobase64(url);
  5383. }
  5384. url = Tools.CleanUrl(url);
  5385. var img = new Image();
  5386. if (url.substr(0, 5) !== "data:") {
  5387. Tools.SetCorsBehavior(url, img);
  5388. }
  5389. img.onload = function () {
  5390. onload(img);
  5391. };
  5392. img.onerror = function (err) {
  5393. Tools.Error("Error while trying to load image: " + url);
  5394. if (Tools.UseFallbackTexture) {
  5395. img.src = Tools.fallbackTexture;
  5396. onload(img);
  5397. }
  5398. else {
  5399. onerror();
  5400. }
  5401. };
  5402. var noIndexedDB = function () {
  5403. img.src = url;
  5404. };
  5405. var loadFromIndexedDB = function () {
  5406. database.loadImageFromDB(url, img);
  5407. };
  5408. //ANY database to do!
  5409. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5410. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5411. }
  5412. else {
  5413. if (url.indexOf("file:") === -1) {
  5414. noIndexedDB();
  5415. }
  5416. else {
  5417. var textureName = url.substring(5).toLowerCase();
  5418. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5419. try {
  5420. var blobURL;
  5421. try {
  5422. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5423. }
  5424. catch (ex) {
  5425. // Chrome doesn't support oneTimeOnly parameter
  5426. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5427. }
  5428. img.src = blobURL;
  5429. }
  5430. catch (e) {
  5431. img.src = null;
  5432. }
  5433. }
  5434. else {
  5435. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5436. img.src = Tools.fallbackTexture;
  5437. }
  5438. }
  5439. }
  5440. return img;
  5441. };
  5442. //ANY
  5443. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5444. url = Tools.CleanUrl(url);
  5445. var noIndexedDB = function () {
  5446. var request = new XMLHttpRequest();
  5447. var loadUrl = Tools.BaseUrl + url;
  5448. request.open('GET', loadUrl, true);
  5449. if (useArrayBuffer) {
  5450. request.responseType = "arraybuffer";
  5451. }
  5452. request.onprogress = progressCallBack;
  5453. request.onreadystatechange = function () {
  5454. if (request.readyState === 4) {
  5455. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5456. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5457. callback(!useArrayBuffer ? request.responseText : request.response);
  5458. }
  5459. else {
  5460. if (onError) {
  5461. onError();
  5462. }
  5463. else {
  5464. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5465. }
  5466. }
  5467. }
  5468. };
  5469. request.send(null);
  5470. };
  5471. var loadFromIndexedDB = function () {
  5472. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5473. };
  5474. if (url.indexOf("file:") !== -1) {
  5475. var fileName = url.substring(5).toLowerCase();
  5476. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5477. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5478. }
  5479. else {
  5480. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5481. }
  5482. }
  5483. else {
  5484. // Caching all files
  5485. if (database && database.enableSceneOffline) {
  5486. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5487. }
  5488. else {
  5489. noIndexedDB();
  5490. }
  5491. }
  5492. };
  5493. /**
  5494. * Load a script (identified by an url). When the url returns, the
  5495. * content of this file is added into a new script element, attached to the DOM (body element)
  5496. */
  5497. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5498. var head = document.getElementsByTagName('head')[0];
  5499. var script = document.createElement('script');
  5500. script.type = 'text/javascript';
  5501. script.src = scriptUrl;
  5502. var self = this;
  5503. script.onload = function () {
  5504. if (onSuccess) {
  5505. onSuccess();
  5506. }
  5507. };
  5508. script.onerror = function () {
  5509. if (onError) {
  5510. onError();
  5511. }
  5512. };
  5513. head.appendChild(script);
  5514. };
  5515. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5516. var reader = new FileReader();
  5517. reader.onload = function (e) {
  5518. //target doesn't have result from ts 1.3
  5519. callback(e.target['result']);
  5520. };
  5521. reader.onprogress = progressCallback;
  5522. reader.readAsDataURL(fileToLoad);
  5523. };
  5524. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5525. var reader = new FileReader();
  5526. reader.onerror = function (e) {
  5527. Tools.Log("Error while reading file: " + fileToLoad.name);
  5528. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5529. };
  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. if (!useArrayBuffer) {
  5536. // Asynchronous read
  5537. reader.readAsText(fileToLoad);
  5538. }
  5539. else {
  5540. reader.readAsArrayBuffer(fileToLoad);
  5541. }
  5542. };
  5543. //returns a downloadable url to a file content.
  5544. Tools.FileAsURL = function (content) {
  5545. var fileBlob = new Blob([content]);
  5546. var url = window.URL || window.webkitURL;
  5547. var link = url.createObjectURL(fileBlob);
  5548. return link;
  5549. };
  5550. // Misc.
  5551. Tools.Format = function (value, decimals) {
  5552. if (decimals === void 0) { decimals = 2; }
  5553. return value.toFixed(decimals);
  5554. };
  5555. Tools.CheckExtends = function (v, min, max) {
  5556. if (v.x < min.x)
  5557. min.x = v.x;
  5558. if (v.y < min.y)
  5559. min.y = v.y;
  5560. if (v.z < min.z)
  5561. min.z = v.z;
  5562. if (v.x > max.x)
  5563. max.x = v.x;
  5564. if (v.y > max.y)
  5565. max.y = v.y;
  5566. if (v.z > max.z)
  5567. max.z = v.z;
  5568. };
  5569. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5570. for (var prop in source) {
  5571. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5572. continue;
  5573. }
  5574. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5575. continue;
  5576. }
  5577. var sourceValue = source[prop];
  5578. var typeOfSourceValue = typeof sourceValue;
  5579. if (typeOfSourceValue === "function") {
  5580. continue;
  5581. }
  5582. if (typeOfSourceValue === "object") {
  5583. if (sourceValue instanceof Array) {
  5584. destination[prop] = [];
  5585. if (sourceValue.length > 0) {
  5586. if (typeof sourceValue[0] == "object") {
  5587. for (var index = 0; index < sourceValue.length; index++) {
  5588. var clonedValue = cloneValue(sourceValue[index], destination);
  5589. if (destination[prop].indexOf(clonedValue) === -1) {
  5590. destination[prop].push(clonedValue);
  5591. }
  5592. }
  5593. }
  5594. else {
  5595. destination[prop] = sourceValue.slice(0);
  5596. }
  5597. }
  5598. }
  5599. else {
  5600. destination[prop] = cloneValue(sourceValue, destination);
  5601. }
  5602. }
  5603. else {
  5604. destination[prop] = sourceValue;
  5605. }
  5606. }
  5607. };
  5608. Tools.IsEmpty = function (obj) {
  5609. for (var i in obj) {
  5610. return false;
  5611. }
  5612. return true;
  5613. };
  5614. Tools.RegisterTopRootEvents = function (events) {
  5615. for (var index = 0; index < events.length; index++) {
  5616. var event = events[index];
  5617. window.addEventListener(event.name, event.handler, false);
  5618. try {
  5619. if (window.parent) {
  5620. window.parent.addEventListener(event.name, event.handler, false);
  5621. }
  5622. }
  5623. catch (e) {
  5624. // Silently fails...
  5625. }
  5626. }
  5627. };
  5628. Tools.UnregisterTopRootEvents = function (events) {
  5629. for (var index = 0; index < events.length; index++) {
  5630. var event = events[index];
  5631. window.removeEventListener(event.name, event.handler);
  5632. try {
  5633. if (window.parent) {
  5634. window.parent.removeEventListener(event.name, event.handler);
  5635. }
  5636. }
  5637. catch (e) {
  5638. // Silently fails...
  5639. }
  5640. }
  5641. };
  5642. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5643. if (mimeType === void 0) { mimeType = "image/png"; }
  5644. // Read the contents of the framebuffer
  5645. var numberOfChannelsByLine = width * 4;
  5646. var halfHeight = height / 2;
  5647. //Reading datas from WebGL
  5648. var data = engine.readPixels(0, 0, width, height);
  5649. //To flip image on Y axis.
  5650. for (var i = 0; i < halfHeight; i++) {
  5651. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5652. var currentCell = j + i * numberOfChannelsByLine;
  5653. var targetLine = height - i - 1;
  5654. var targetCell = j + targetLine * numberOfChannelsByLine;
  5655. var temp = data[currentCell];
  5656. data[currentCell] = data[targetCell];
  5657. data[targetCell] = temp;
  5658. }
  5659. }
  5660. // Create a 2D canvas to store the result
  5661. if (!screenshotCanvas) {
  5662. screenshotCanvas = document.createElement('canvas');
  5663. }
  5664. screenshotCanvas.width = width;
  5665. screenshotCanvas.height = height;
  5666. var context = screenshotCanvas.getContext('2d');
  5667. // Copy the pixels to a 2D canvas
  5668. var imageData = context.createImageData(width, height);
  5669. var castData = (imageData.data);
  5670. castData.set(data);
  5671. context.putImageData(imageData, 0, 0);
  5672. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5673. };
  5674. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5675. if (mimeType === void 0) { mimeType = "image/png"; }
  5676. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5677. if (successCallback) {
  5678. successCallback(base64Image);
  5679. }
  5680. else {
  5681. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5682. if (("download" in document.createElement("a"))) {
  5683. var a = window.document.createElement("a");
  5684. a.href = base64Image;
  5685. var date = new Date();
  5686. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5687. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5688. window.document.body.appendChild(a);
  5689. a.addEventListener("click", function () {
  5690. a.parentElement.removeChild(a);
  5691. });
  5692. a.click();
  5693. //Or opening a new tab with the image if it is not possible to automatically start download.
  5694. }
  5695. else {
  5696. var newWindow = window.open("");
  5697. var img = newWindow.document.createElement("img");
  5698. img.src = base64Image;
  5699. newWindow.document.body.appendChild(img);
  5700. }
  5701. }
  5702. };
  5703. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5704. if (mimeType === void 0) { mimeType = "image/png"; }
  5705. var width;
  5706. var height;
  5707. // If a precision value is specified
  5708. if (size.precision) {
  5709. width = Math.round(engine.getRenderWidth() * size.precision);
  5710. height = Math.round(width / engine.getAspectRatio(camera));
  5711. }
  5712. else if (size.width && size.height) {
  5713. width = size.width;
  5714. height = size.height;
  5715. }
  5716. else if (size.width && !size.height) {
  5717. width = size.width;
  5718. height = Math.round(width / engine.getAspectRatio(camera));
  5719. }
  5720. else if (size.height && !size.width) {
  5721. height = size.height;
  5722. width = Math.round(height * engine.getAspectRatio(camera));
  5723. }
  5724. else if (!isNaN(size)) {
  5725. height = size;
  5726. width = size;
  5727. }
  5728. else {
  5729. Tools.Error("Invalid 'size' parameter !");
  5730. return;
  5731. }
  5732. if (!screenshotCanvas) {
  5733. screenshotCanvas = document.createElement('canvas');
  5734. }
  5735. screenshotCanvas.width = width;
  5736. screenshotCanvas.height = height;
  5737. var renderContext = screenshotCanvas.getContext("2d");
  5738. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5739. var newWidth = width;
  5740. var newHeight = newWidth / ratio;
  5741. if (newHeight > height) {
  5742. newHeight = height;
  5743. newWidth = newHeight * ratio;
  5744. }
  5745. var offsetX = Math.max(0, width - newWidth) / 2;
  5746. var offsetY = Math.max(0, height - newHeight) / 2;
  5747. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5748. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5749. };
  5750. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  5751. if (mimeType === void 0) { mimeType = "image/png"; }
  5752. if (samples === void 0) { samples = 1; }
  5753. var width;
  5754. var height;
  5755. //If a precision value is specified
  5756. if (size.precision) {
  5757. width = Math.round(engine.getRenderWidth() * size.precision);
  5758. height = Math.round(width / engine.getAspectRatio(camera));
  5759. size = { width: width, height: height };
  5760. }
  5761. else if (size.width && size.height) {
  5762. width = size.width;
  5763. height = size.height;
  5764. }
  5765. else if (size.width && !size.height) {
  5766. width = size.width;
  5767. height = Math.round(width / engine.getAspectRatio(camera));
  5768. size = { width: width, height: height };
  5769. }
  5770. else if (size.height && !size.width) {
  5771. height = size.height;
  5772. width = Math.round(height * engine.getAspectRatio(camera));
  5773. size = { width: width, height: height };
  5774. }
  5775. else if (!isNaN(size)) {
  5776. height = size;
  5777. width = size;
  5778. }
  5779. else {
  5780. Tools.Error("Invalid 'size' parameter !");
  5781. return;
  5782. }
  5783. var scene = camera.getScene();
  5784. var previousCamera = null;
  5785. if (scene.activeCamera !== camera) {
  5786. previousCamera = scene.activeCamera;
  5787. scene.activeCamera = camera;
  5788. }
  5789. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5790. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5791. texture.renderList = scene.meshes;
  5792. texture.samples = samples;
  5793. texture.onAfterRenderObservable.add(function () {
  5794. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5795. });
  5796. scene.incrementRenderId();
  5797. scene.resetCachedMaterial();
  5798. texture.render(true);
  5799. texture.dispose();
  5800. if (previousCamera) {
  5801. scene.activeCamera = previousCamera;
  5802. }
  5803. camera.getProjectionMatrix(true); // Force cache refresh;
  5804. };
  5805. // XHR response validator for local file scenario
  5806. Tools.ValidateXHRData = function (xhr, dataType) {
  5807. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5808. if (dataType === void 0) { dataType = 7; }
  5809. try {
  5810. if (dataType & 1) {
  5811. if (xhr.responseText && xhr.responseText.length > 0) {
  5812. return true;
  5813. }
  5814. else if (dataType === 1) {
  5815. return false;
  5816. }
  5817. }
  5818. if (dataType & 2) {
  5819. // Check header width and height since there is no "TGA" magic number
  5820. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5821. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5822. return true;
  5823. }
  5824. else if (dataType === 2) {
  5825. return false;
  5826. }
  5827. }
  5828. if (dataType & 4) {
  5829. // Check for the "DDS" magic number
  5830. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5831. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5832. return true;
  5833. }
  5834. else {
  5835. return false;
  5836. }
  5837. }
  5838. }
  5839. catch (e) {
  5840. // Global protection
  5841. }
  5842. return false;
  5843. };
  5844. /**
  5845. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5846. * Be aware Math.random() could cause collisions, but:
  5847. * "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"
  5848. */
  5849. Tools.RandomId = function () {
  5850. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5851. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5852. return v.toString(16);
  5853. });
  5854. };
  5855. Object.defineProperty(Tools, "NoneLogLevel", {
  5856. get: function () {
  5857. return Tools._NoneLogLevel;
  5858. },
  5859. enumerable: true,
  5860. configurable: true
  5861. });
  5862. Object.defineProperty(Tools, "MessageLogLevel", {
  5863. get: function () {
  5864. return Tools._MessageLogLevel;
  5865. },
  5866. enumerable: true,
  5867. configurable: true
  5868. });
  5869. Object.defineProperty(Tools, "WarningLogLevel", {
  5870. get: function () {
  5871. return Tools._WarningLogLevel;
  5872. },
  5873. enumerable: true,
  5874. configurable: true
  5875. });
  5876. Object.defineProperty(Tools, "ErrorLogLevel", {
  5877. get: function () {
  5878. return Tools._ErrorLogLevel;
  5879. },
  5880. enumerable: true,
  5881. configurable: true
  5882. });
  5883. Object.defineProperty(Tools, "AllLogLevel", {
  5884. get: function () {
  5885. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5886. },
  5887. enumerable: true,
  5888. configurable: true
  5889. });
  5890. Tools._AddLogEntry = function (entry) {
  5891. Tools._LogCache = entry + Tools._LogCache;
  5892. if (Tools.OnNewCacheEntry) {
  5893. Tools.OnNewCacheEntry(entry);
  5894. }
  5895. };
  5896. Tools._FormatMessage = function (message) {
  5897. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5898. var date = new Date();
  5899. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5900. };
  5901. Tools._LogDisabled = function (message) {
  5902. // nothing to do
  5903. };
  5904. Tools._LogEnabled = function (message) {
  5905. var formattedMessage = Tools._FormatMessage(message);
  5906. console.log("BJS - " + formattedMessage);
  5907. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5908. Tools._AddLogEntry(entry);
  5909. };
  5910. Tools._WarnDisabled = function (message) {
  5911. // nothing to do
  5912. };
  5913. Tools._WarnEnabled = function (message) {
  5914. var formattedMessage = Tools._FormatMessage(message);
  5915. console.warn("BJS - " + formattedMessage);
  5916. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5917. Tools._AddLogEntry(entry);
  5918. };
  5919. Tools._ErrorDisabled = function (message) {
  5920. // nothing to do
  5921. };
  5922. Tools._ErrorEnabled = function (message) {
  5923. Tools.errorsCount++;
  5924. var formattedMessage = Tools._FormatMessage(message);
  5925. console.error("BJS - " + formattedMessage);
  5926. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5927. Tools._AddLogEntry(entry);
  5928. };
  5929. Object.defineProperty(Tools, "LogCache", {
  5930. get: function () {
  5931. return Tools._LogCache;
  5932. },
  5933. enumerable: true,
  5934. configurable: true
  5935. });
  5936. Tools.ClearLogCache = function () {
  5937. Tools._LogCache = "";
  5938. Tools.errorsCount = 0;
  5939. };
  5940. Object.defineProperty(Tools, "LogLevels", {
  5941. set: function (level) {
  5942. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5943. Tools.Log = Tools._LogEnabled;
  5944. }
  5945. else {
  5946. Tools.Log = Tools._LogDisabled;
  5947. }
  5948. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5949. Tools.Warn = Tools._WarnEnabled;
  5950. }
  5951. else {
  5952. Tools.Warn = Tools._WarnDisabled;
  5953. }
  5954. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5955. Tools.Error = Tools._ErrorEnabled;
  5956. }
  5957. else {
  5958. Tools.Error = Tools._ErrorDisabled;
  5959. }
  5960. },
  5961. enumerable: true,
  5962. configurable: true
  5963. });
  5964. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5965. get: function () {
  5966. return Tools._PerformanceNoneLogLevel;
  5967. },
  5968. enumerable: true,
  5969. configurable: true
  5970. });
  5971. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5972. get: function () {
  5973. return Tools._PerformanceUserMarkLogLevel;
  5974. },
  5975. enumerable: true,
  5976. configurable: true
  5977. });
  5978. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5979. get: function () {
  5980. return Tools._PerformanceConsoleLogLevel;
  5981. },
  5982. enumerable: true,
  5983. configurable: true
  5984. });
  5985. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5986. set: function (level) {
  5987. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5988. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5989. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5990. return;
  5991. }
  5992. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5993. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5994. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5995. return;
  5996. }
  5997. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5998. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5999. },
  6000. enumerable: true,
  6001. configurable: true
  6002. });
  6003. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6004. };
  6005. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6006. };
  6007. Tools._StartUserMark = function (counterName, condition) {
  6008. if (condition === void 0) { condition = true; }
  6009. if (!condition || !Tools._performance.mark) {
  6010. return;
  6011. }
  6012. Tools._performance.mark(counterName + "-Begin");
  6013. };
  6014. Tools._EndUserMark = function (counterName, condition) {
  6015. if (condition === void 0) { condition = true; }
  6016. if (!condition || !Tools._performance.mark) {
  6017. return;
  6018. }
  6019. Tools._performance.mark(counterName + "-End");
  6020. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6021. };
  6022. Tools._StartPerformanceConsole = function (counterName, condition) {
  6023. if (condition === void 0) { condition = true; }
  6024. if (!condition) {
  6025. return;
  6026. }
  6027. Tools._StartUserMark(counterName, condition);
  6028. if (console.time) {
  6029. console.time(counterName);
  6030. }
  6031. };
  6032. Tools._EndPerformanceConsole = function (counterName, condition) {
  6033. if (condition === void 0) { condition = true; }
  6034. if (!condition) {
  6035. return;
  6036. }
  6037. Tools._EndUserMark(counterName, condition);
  6038. if (console.time) {
  6039. console.timeEnd(counterName);
  6040. }
  6041. };
  6042. Object.defineProperty(Tools, "Now", {
  6043. get: function () {
  6044. if (window.performance && window.performance.now) {
  6045. return window.performance.now();
  6046. }
  6047. return new Date().getTime();
  6048. },
  6049. enumerable: true,
  6050. configurable: true
  6051. });
  6052. /**
  6053. * This method will return the name of the class used to create the instance of the given object.
  6054. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6055. * @param object the object to get the class name from
  6056. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6057. */
  6058. Tools.getClassName = function (object, isType) {
  6059. if (isType === void 0) { isType = false; }
  6060. var name = null;
  6061. if (!isType && object.getClassName) {
  6062. name = object.getClassName();
  6063. }
  6064. else {
  6065. if (object instanceof Object) {
  6066. var classObj = isType ? object : Object.getPrototypeOf(object);
  6067. name = classObj.constructor["__bjsclassName__"];
  6068. }
  6069. if (!name) {
  6070. name = typeof object;
  6071. }
  6072. }
  6073. return name;
  6074. };
  6075. Tools.first = function (array, predicate) {
  6076. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6077. var el = array_1[_i];
  6078. if (predicate(el)) {
  6079. return el;
  6080. }
  6081. }
  6082. };
  6083. /**
  6084. * This method will return the name of the full name of the class, including its owning module (if any).
  6085. * 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).
  6086. * @param object the object to get the class name from
  6087. * @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.
  6088. */
  6089. Tools.getFullClassName = function (object, isType) {
  6090. if (isType === void 0) { isType = false; }
  6091. var className = null;
  6092. var moduleName = null;
  6093. if (!isType && object.getClassName) {
  6094. className = object.getClassName();
  6095. }
  6096. else {
  6097. if (object instanceof Object) {
  6098. var classObj = isType ? object : Object.getPrototypeOf(object);
  6099. className = classObj.constructor["__bjsclassName__"];
  6100. moduleName = classObj.constructor["__bjsmoduleName__"];
  6101. }
  6102. if (!className) {
  6103. className = typeof object;
  6104. }
  6105. }
  6106. if (!className) {
  6107. return null;
  6108. }
  6109. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6110. };
  6111. /**
  6112. * 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.
  6113. * @param array
  6114. */
  6115. Tools.arrayOrStringFeeder = function (array) {
  6116. return function (index) {
  6117. if (index >= array.length) {
  6118. return null;
  6119. }
  6120. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6121. if (val && val.getHashCode) {
  6122. val = val.getHashCode();
  6123. }
  6124. if (typeof val === "string") {
  6125. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6126. }
  6127. return val;
  6128. };
  6129. };
  6130. /**
  6131. * Compute the hashCode of a stream of number
  6132. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6133. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6134. * @return the hash code computed
  6135. */
  6136. Tools.hashCodeFromStream = function (feeder) {
  6137. // Based from here: http://stackoverflow.com/a/7616484/802124
  6138. var hash = 0;
  6139. var index = 0;
  6140. var chr = feeder(index++);
  6141. while (chr != null) {
  6142. hash = ((hash << 5) - hash) + chr;
  6143. hash |= 0; // Convert to 32bit integer
  6144. chr = feeder(index++);
  6145. }
  6146. return hash;
  6147. };
  6148. return Tools;
  6149. }());
  6150. Tools.BaseUrl = "";
  6151. Tools.CorsBehavior = "anonymous";
  6152. Tools.UseFallbackTexture = true;
  6153. // Used in case of a texture loading problem
  6154. 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";
  6155. // Logs
  6156. Tools._NoneLogLevel = 0;
  6157. Tools._MessageLogLevel = 1;
  6158. Tools._WarningLogLevel = 2;
  6159. Tools._ErrorLogLevel = 4;
  6160. Tools._LogCache = "";
  6161. Tools.errorsCount = 0;
  6162. Tools.Log = Tools._LogEnabled;
  6163. Tools.Warn = Tools._WarnEnabled;
  6164. Tools.Error = Tools._ErrorEnabled;
  6165. // Performances
  6166. Tools._PerformanceNoneLogLevel = 0;
  6167. Tools._PerformanceUserMarkLogLevel = 1;
  6168. Tools._PerformanceConsoleLogLevel = 2;
  6169. Tools._performance = window.performance;
  6170. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6171. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6172. BABYLON.Tools = Tools;
  6173. /**
  6174. * This class is used to track a performance counter which is number based.
  6175. * The user has access to many properties which give statistics of different nature
  6176. *
  6177. * The implementer can track two kinds of Performance Counter: time and count
  6178. * 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.
  6179. * 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.
  6180. */
  6181. var PerfCounter = (function () {
  6182. function PerfCounter() {
  6183. this._startMonitoringTime = 0;
  6184. this._min = 0;
  6185. this._max = 0;
  6186. this._average = 0;
  6187. this._lastSecAverage = 0;
  6188. this._current = 0;
  6189. this._totalValueCount = 0;
  6190. this._totalAccumulated = 0;
  6191. this._lastSecAccumulated = 0;
  6192. this._lastSecTime = 0;
  6193. this._lastSecValueCount = 0;
  6194. }
  6195. Object.defineProperty(PerfCounter.prototype, "min", {
  6196. /**
  6197. * Returns the smallest value ever
  6198. */
  6199. get: function () {
  6200. return this._min;
  6201. },
  6202. enumerable: true,
  6203. configurable: true
  6204. });
  6205. Object.defineProperty(PerfCounter.prototype, "max", {
  6206. /**
  6207. * Returns the biggest value ever
  6208. */
  6209. get: function () {
  6210. return this._max;
  6211. },
  6212. enumerable: true,
  6213. configurable: true
  6214. });
  6215. Object.defineProperty(PerfCounter.prototype, "average", {
  6216. /**
  6217. * Returns the average value since the performance counter is running
  6218. */
  6219. get: function () {
  6220. return this._average;
  6221. },
  6222. enumerable: true,
  6223. configurable: true
  6224. });
  6225. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6226. /**
  6227. * Returns the average value of the last second the counter was monitored
  6228. */
  6229. get: function () {
  6230. return this._lastSecAverage;
  6231. },
  6232. enumerable: true,
  6233. configurable: true
  6234. });
  6235. Object.defineProperty(PerfCounter.prototype, "current", {
  6236. /**
  6237. * Returns the current value
  6238. */
  6239. get: function () {
  6240. return this._current;
  6241. },
  6242. enumerable: true,
  6243. configurable: true
  6244. });
  6245. Object.defineProperty(PerfCounter.prototype, "total", {
  6246. get: function () {
  6247. return this._totalAccumulated;
  6248. },
  6249. enumerable: true,
  6250. configurable: true
  6251. });
  6252. /**
  6253. * Call this method to start monitoring a new frame.
  6254. * 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.
  6255. */
  6256. PerfCounter.prototype.fetchNewFrame = function () {
  6257. this._totalValueCount++;
  6258. this._current = 0;
  6259. this._lastSecValueCount++;
  6260. };
  6261. /**
  6262. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6263. * @param newCount the count value to add to the monitored count
  6264. * @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.
  6265. */
  6266. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6267. if (!PerfCounter.Enabled) {
  6268. return;
  6269. }
  6270. this._current += newCount;
  6271. if (fetchResult) {
  6272. this._fetchResult();
  6273. }
  6274. };
  6275. /**
  6276. * Start monitoring this performance counter
  6277. */
  6278. PerfCounter.prototype.beginMonitoring = function () {
  6279. if (!PerfCounter.Enabled) {
  6280. return;
  6281. }
  6282. this._startMonitoringTime = Tools.Now;
  6283. };
  6284. /**
  6285. * Compute the time lapsed since the previous beginMonitoring() call.
  6286. * @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
  6287. */
  6288. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6289. if (newFrame === void 0) { newFrame = true; }
  6290. if (!PerfCounter.Enabled) {
  6291. return;
  6292. }
  6293. if (newFrame) {
  6294. this.fetchNewFrame();
  6295. }
  6296. var currentTime = Tools.Now;
  6297. this._current = currentTime - this._startMonitoringTime;
  6298. if (newFrame) {
  6299. this._fetchResult();
  6300. }
  6301. };
  6302. PerfCounter.prototype._fetchResult = function () {
  6303. this._totalAccumulated += this._current;
  6304. this._lastSecAccumulated += this._current;
  6305. // Min/Max update
  6306. this._min = Math.min(this._min, this._current);
  6307. this._max = Math.max(this._max, this._current);
  6308. this._average = this._totalAccumulated / this._totalValueCount;
  6309. // Reset last sec?
  6310. var now = Tools.Now;
  6311. if ((now - this._lastSecTime) > 1000) {
  6312. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6313. this._lastSecTime = now;
  6314. this._lastSecAccumulated = 0;
  6315. this._lastSecValueCount = 0;
  6316. }
  6317. };
  6318. return PerfCounter;
  6319. }());
  6320. PerfCounter.Enabled = true;
  6321. BABYLON.PerfCounter = PerfCounter;
  6322. /**
  6323. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6324. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6325. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6326. * @param name The name of the class, case should be preserved
  6327. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6328. */
  6329. function className(name, module) {
  6330. return function (target) {
  6331. target["__bjsclassName__"] = name;
  6332. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6333. };
  6334. }
  6335. BABYLON.className = className;
  6336. /**
  6337. * An implementation of a loop for asynchronous functions.
  6338. */
  6339. var AsyncLoop = (function () {
  6340. /**
  6341. * Constroctor.
  6342. * @param iterations the number of iterations.
  6343. * @param _fn the function to run each iteration
  6344. * @param _successCallback the callback that will be called upon succesful execution
  6345. * @param offset starting offset.
  6346. */
  6347. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6348. if (offset === void 0) { offset = 0; }
  6349. this.iterations = iterations;
  6350. this._fn = _fn;
  6351. this._successCallback = _successCallback;
  6352. this.index = offset - 1;
  6353. this._done = false;
  6354. }
  6355. /**
  6356. * Execute the next iteration. Must be called after the last iteration was finished.
  6357. */
  6358. AsyncLoop.prototype.executeNext = function () {
  6359. if (!this._done) {
  6360. if (this.index + 1 < this.iterations) {
  6361. ++this.index;
  6362. this._fn(this);
  6363. }
  6364. else {
  6365. this.breakLoop();
  6366. }
  6367. }
  6368. };
  6369. /**
  6370. * Break the loop and run the success callback.
  6371. */
  6372. AsyncLoop.prototype.breakLoop = function () {
  6373. this._done = true;
  6374. this._successCallback();
  6375. };
  6376. /**
  6377. * Helper function
  6378. */
  6379. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6380. if (offset === void 0) { offset = 0; }
  6381. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6382. loop.executeNext();
  6383. return loop;
  6384. };
  6385. /**
  6386. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6387. * @param iterations total number of iterations
  6388. * @param syncedIterations number of synchronous iterations in each async iteration.
  6389. * @param fn the function to call each iteration.
  6390. * @param callback a success call back that will be called when iterating stops.
  6391. * @param breakFunction a break condition (optional)
  6392. * @param timeout timeout settings for the setTimeout function. default - 0.
  6393. * @constructor
  6394. */
  6395. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6396. if (timeout === void 0) { timeout = 0; }
  6397. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6398. if (breakFunction && breakFunction())
  6399. loop.breakLoop();
  6400. else {
  6401. setTimeout(function () {
  6402. for (var i = 0; i < syncedIterations; ++i) {
  6403. var iteration = (loop.index * syncedIterations) + i;
  6404. if (iteration >= iterations)
  6405. break;
  6406. fn(iteration);
  6407. if (breakFunction && breakFunction()) {
  6408. loop.breakLoop();
  6409. break;
  6410. }
  6411. }
  6412. loop.executeNext();
  6413. }, timeout);
  6414. }
  6415. }, callback);
  6416. };
  6417. return AsyncLoop;
  6418. }());
  6419. BABYLON.AsyncLoop = AsyncLoop;
  6420. })(BABYLON || (BABYLON = {}));
  6421. //# sourceMappingURL=babylon.tools.js.map
  6422. var BABYLON;
  6423. (function (BABYLON) {
  6424. var Internals;
  6425. (function (Internals) {
  6426. var _AlphaState = (function () {
  6427. /**
  6428. * Initializes the state.
  6429. */
  6430. function _AlphaState() {
  6431. this._isAlphaBlendDirty = false;
  6432. this._isBlendFunctionParametersDirty = false;
  6433. this._alphaBlend = false;
  6434. this._blendFunctionParameters = new Array(4);
  6435. this.reset();
  6436. }
  6437. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6438. get: function () {
  6439. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6440. },
  6441. enumerable: true,
  6442. configurable: true
  6443. });
  6444. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6445. get: function () {
  6446. return this._alphaBlend;
  6447. },
  6448. set: function (value) {
  6449. if (this._alphaBlend === value) {
  6450. return;
  6451. }
  6452. this._alphaBlend = value;
  6453. this._isAlphaBlendDirty = true;
  6454. },
  6455. enumerable: true,
  6456. configurable: true
  6457. });
  6458. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6459. if (this._blendFunctionParameters[0] === value0 &&
  6460. this._blendFunctionParameters[1] === value1 &&
  6461. this._blendFunctionParameters[2] === value2 &&
  6462. this._blendFunctionParameters[3] === value3) {
  6463. return;
  6464. }
  6465. this._blendFunctionParameters[0] = value0;
  6466. this._blendFunctionParameters[1] = value1;
  6467. this._blendFunctionParameters[2] = value2;
  6468. this._blendFunctionParameters[3] = value3;
  6469. this._isBlendFunctionParametersDirty = true;
  6470. };
  6471. _AlphaState.prototype.reset = function () {
  6472. this._alphaBlend = false;
  6473. this._blendFunctionParameters[0] = null;
  6474. this._blendFunctionParameters[1] = null;
  6475. this._blendFunctionParameters[2] = null;
  6476. this._blendFunctionParameters[3] = null;
  6477. this._isAlphaBlendDirty = true;
  6478. this._isBlendFunctionParametersDirty = false;
  6479. };
  6480. _AlphaState.prototype.apply = function (gl) {
  6481. if (!this.isDirty) {
  6482. return;
  6483. }
  6484. // Alpha blend
  6485. if (this._isAlphaBlendDirty) {
  6486. if (this._alphaBlend) {
  6487. gl.enable(gl.BLEND);
  6488. }
  6489. else {
  6490. gl.disable(gl.BLEND);
  6491. }
  6492. this._isAlphaBlendDirty = false;
  6493. }
  6494. // Alpha function
  6495. if (this._isBlendFunctionParametersDirty) {
  6496. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6497. this._isBlendFunctionParametersDirty = false;
  6498. }
  6499. };
  6500. return _AlphaState;
  6501. }());
  6502. Internals._AlphaState = _AlphaState;
  6503. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6504. })(BABYLON || (BABYLON = {}));
  6505. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6506. var BABYLON;
  6507. (function (BABYLON) {
  6508. var Internals;
  6509. (function (Internals) {
  6510. var _DepthCullingState = (function () {
  6511. /**
  6512. * Initializes the state.
  6513. */
  6514. function _DepthCullingState() {
  6515. this._isDepthTestDirty = false;
  6516. this._isDepthMaskDirty = false;
  6517. this._isDepthFuncDirty = false;
  6518. this._isCullFaceDirty = false;
  6519. this._isCullDirty = false;
  6520. this._isZOffsetDirty = false;
  6521. this.reset();
  6522. }
  6523. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6524. get: function () {
  6525. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6526. },
  6527. enumerable: true,
  6528. configurable: true
  6529. });
  6530. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6531. get: function () {
  6532. return this._zOffset;
  6533. },
  6534. set: function (value) {
  6535. if (this._zOffset === value) {
  6536. return;
  6537. }
  6538. this._zOffset = value;
  6539. this._isZOffsetDirty = true;
  6540. },
  6541. enumerable: true,
  6542. configurable: true
  6543. });
  6544. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6545. get: function () {
  6546. return this._cullFace;
  6547. },
  6548. set: function (value) {
  6549. if (this._cullFace === value) {
  6550. return;
  6551. }
  6552. this._cullFace = value;
  6553. this._isCullFaceDirty = true;
  6554. },
  6555. enumerable: true,
  6556. configurable: true
  6557. });
  6558. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6559. get: function () {
  6560. return this._cull;
  6561. },
  6562. set: function (value) {
  6563. if (this._cull === value) {
  6564. return;
  6565. }
  6566. this._cull = value;
  6567. this._isCullDirty = true;
  6568. },
  6569. enumerable: true,
  6570. configurable: true
  6571. });
  6572. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6573. get: function () {
  6574. return this._depthFunc;
  6575. },
  6576. set: function (value) {
  6577. if (this._depthFunc === value) {
  6578. return;
  6579. }
  6580. this._depthFunc = value;
  6581. this._isDepthFuncDirty = true;
  6582. },
  6583. enumerable: true,
  6584. configurable: true
  6585. });
  6586. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6587. get: function () {
  6588. return this._depthMask;
  6589. },
  6590. set: function (value) {
  6591. if (this._depthMask === value) {
  6592. return;
  6593. }
  6594. this._depthMask = value;
  6595. this._isDepthMaskDirty = true;
  6596. },
  6597. enumerable: true,
  6598. configurable: true
  6599. });
  6600. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6601. get: function () {
  6602. return this._depthTest;
  6603. },
  6604. set: function (value) {
  6605. if (this._depthTest === value) {
  6606. return;
  6607. }
  6608. this._depthTest = value;
  6609. this._isDepthTestDirty = true;
  6610. },
  6611. enumerable: true,
  6612. configurable: true
  6613. });
  6614. _DepthCullingState.prototype.reset = function () {
  6615. this._depthMask = true;
  6616. this._depthTest = true;
  6617. this._depthFunc = null;
  6618. this._cullFace = null;
  6619. this._cull = null;
  6620. this._zOffset = 0;
  6621. this._isDepthTestDirty = true;
  6622. this._isDepthMaskDirty = true;
  6623. this._isDepthFuncDirty = false;
  6624. this._isCullFaceDirty = false;
  6625. this._isCullDirty = false;
  6626. this._isZOffsetDirty = false;
  6627. };
  6628. _DepthCullingState.prototype.apply = function (gl) {
  6629. if (!this.isDirty) {
  6630. return;
  6631. }
  6632. // Cull
  6633. if (this._isCullDirty) {
  6634. if (this.cull) {
  6635. gl.enable(gl.CULL_FACE);
  6636. }
  6637. else {
  6638. gl.disable(gl.CULL_FACE);
  6639. }
  6640. this._isCullDirty = false;
  6641. }
  6642. // Cull face
  6643. if (this._isCullFaceDirty) {
  6644. gl.cullFace(this.cullFace);
  6645. this._isCullFaceDirty = false;
  6646. }
  6647. // Depth mask
  6648. if (this._isDepthMaskDirty) {
  6649. gl.depthMask(this.depthMask);
  6650. this._isDepthMaskDirty = false;
  6651. }
  6652. // Depth test
  6653. if (this._isDepthTestDirty) {
  6654. if (this.depthTest) {
  6655. gl.enable(gl.DEPTH_TEST);
  6656. }
  6657. else {
  6658. gl.disable(gl.DEPTH_TEST);
  6659. }
  6660. this._isDepthTestDirty = false;
  6661. }
  6662. // Depth func
  6663. if (this._isDepthFuncDirty) {
  6664. gl.depthFunc(this.depthFunc);
  6665. this._isDepthFuncDirty = false;
  6666. }
  6667. // zOffset
  6668. if (this._isZOffsetDirty) {
  6669. if (this.zOffset) {
  6670. gl.enable(gl.POLYGON_OFFSET_FILL);
  6671. gl.polygonOffset(this.zOffset, 0);
  6672. }
  6673. else {
  6674. gl.disable(gl.POLYGON_OFFSET_FILL);
  6675. }
  6676. this._isZOffsetDirty = false;
  6677. }
  6678. };
  6679. return _DepthCullingState;
  6680. }());
  6681. Internals._DepthCullingState = _DepthCullingState;
  6682. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6683. })(BABYLON || (BABYLON = {}));
  6684. //# sourceMappingURL=babylon.depthCullingState.js.map
  6685. var BABYLON;
  6686. (function (BABYLON) {
  6687. var Internals;
  6688. (function (Internals) {
  6689. var _StencilState = (function () {
  6690. function _StencilState() {
  6691. this._isStencilTestDirty = false;
  6692. this._isStencilMaskDirty = false;
  6693. this._isStencilFuncDirty = false;
  6694. this._isStencilOpDirty = false;
  6695. this.reset();
  6696. }
  6697. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6698. get: function () {
  6699. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6700. },
  6701. enumerable: true,
  6702. configurable: true
  6703. });
  6704. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6705. get: function () {
  6706. return this._stencilFunc;
  6707. },
  6708. set: function (value) {
  6709. if (this._stencilFunc === value) {
  6710. return;
  6711. }
  6712. this._stencilFunc = value;
  6713. this._isStencilFuncDirty = true;
  6714. },
  6715. enumerable: true,
  6716. configurable: true
  6717. });
  6718. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6719. get: function () {
  6720. return this._stencilFuncRef;
  6721. },
  6722. set: function (value) {
  6723. if (this._stencilFuncRef === value) {
  6724. return;
  6725. }
  6726. this._stencilFuncRef = value;
  6727. this._isStencilFuncDirty = true;
  6728. },
  6729. enumerable: true,
  6730. configurable: true
  6731. });
  6732. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6733. get: function () {
  6734. return this._stencilFuncMask;
  6735. },
  6736. set: function (value) {
  6737. if (this._stencilFuncMask === value) {
  6738. return;
  6739. }
  6740. this._stencilFuncMask = value;
  6741. this._isStencilFuncDirty = true;
  6742. },
  6743. enumerable: true,
  6744. configurable: true
  6745. });
  6746. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6747. get: function () {
  6748. return this._stencilOpStencilFail;
  6749. },
  6750. set: function (value) {
  6751. if (this._stencilOpStencilFail === value) {
  6752. return;
  6753. }
  6754. this._stencilOpStencilFail = value;
  6755. this._isStencilOpDirty = true;
  6756. },
  6757. enumerable: true,
  6758. configurable: true
  6759. });
  6760. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6761. get: function () {
  6762. return this._stencilOpDepthFail;
  6763. },
  6764. set: function (value) {
  6765. if (this._stencilOpDepthFail === value) {
  6766. return;
  6767. }
  6768. this._stencilOpDepthFail = value;
  6769. this._isStencilOpDirty = true;
  6770. },
  6771. enumerable: true,
  6772. configurable: true
  6773. });
  6774. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6775. get: function () {
  6776. return this._stencilOpStencilDepthPass;
  6777. },
  6778. set: function (value) {
  6779. if (this._stencilOpStencilDepthPass === value) {
  6780. return;
  6781. }
  6782. this._stencilOpStencilDepthPass = value;
  6783. this._isStencilOpDirty = true;
  6784. },
  6785. enumerable: true,
  6786. configurable: true
  6787. });
  6788. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6789. get: function () {
  6790. return this._stencilMask;
  6791. },
  6792. set: function (value) {
  6793. if (this._stencilMask === value) {
  6794. return;
  6795. }
  6796. this._stencilMask = value;
  6797. this._isStencilMaskDirty = true;
  6798. },
  6799. enumerable: true,
  6800. configurable: true
  6801. });
  6802. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6803. get: function () {
  6804. return this._stencilTest;
  6805. },
  6806. set: function (value) {
  6807. if (this._stencilTest === value) {
  6808. return;
  6809. }
  6810. this._stencilTest = value;
  6811. this._isStencilTestDirty = true;
  6812. },
  6813. enumerable: true,
  6814. configurable: true
  6815. });
  6816. _StencilState.prototype.reset = function () {
  6817. this._stencilTest = false;
  6818. this._stencilMask = 0xFF;
  6819. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6820. this._stencilFuncRef = 1;
  6821. this._stencilFuncMask = 0xFF;
  6822. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6823. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6824. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6825. this._isStencilTestDirty = true;
  6826. this._isStencilMaskDirty = true;
  6827. this._isStencilFuncDirty = true;
  6828. this._isStencilOpDirty = true;
  6829. };
  6830. _StencilState.prototype.apply = function (gl) {
  6831. if (!this.isDirty) {
  6832. return;
  6833. }
  6834. // Stencil test
  6835. if (this._isStencilTestDirty) {
  6836. if (this.stencilTest) {
  6837. gl.enable(gl.STENCIL_TEST);
  6838. }
  6839. else {
  6840. gl.disable(gl.STENCIL_TEST);
  6841. }
  6842. this._isStencilTestDirty = false;
  6843. }
  6844. // Stencil mask
  6845. if (this._isStencilMaskDirty) {
  6846. gl.stencilMask(this.stencilMask);
  6847. this._isStencilMaskDirty = false;
  6848. }
  6849. // Stencil func
  6850. if (this._isStencilFuncDirty) {
  6851. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6852. this._isStencilFuncDirty = false;
  6853. }
  6854. // Stencil op
  6855. if (this._isStencilOpDirty) {
  6856. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6857. this._isStencilOpDirty = false;
  6858. }
  6859. };
  6860. return _StencilState;
  6861. }());
  6862. Internals._StencilState = _StencilState;
  6863. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6864. })(BABYLON || (BABYLON = {}));
  6865. //# sourceMappingURL=babylon.stencilState.js.map
  6866. var BABYLON;
  6867. (function (BABYLON) {
  6868. var compileShader = function (gl, source, type, defines, shaderVersion) {
  6869. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6870. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  6871. gl.compileShader(shader);
  6872. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6873. throw new Error(gl.getShaderInfoLog(shader));
  6874. }
  6875. return shader;
  6876. };
  6877. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6878. var magFilter = gl.NEAREST;
  6879. var minFilter = gl.NEAREST;
  6880. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6881. magFilter = gl.LINEAR;
  6882. if (generateMipMaps) {
  6883. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6884. }
  6885. else {
  6886. minFilter = gl.LINEAR;
  6887. }
  6888. }
  6889. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6890. magFilter = gl.LINEAR;
  6891. if (generateMipMaps) {
  6892. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6893. }
  6894. else {
  6895. minFilter = gl.LINEAR;
  6896. }
  6897. }
  6898. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6899. magFilter = gl.NEAREST;
  6900. if (generateMipMaps) {
  6901. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6902. }
  6903. else {
  6904. minFilter = gl.NEAREST;
  6905. }
  6906. }
  6907. return {
  6908. min: minFilter,
  6909. mag: magFilter
  6910. };
  6911. };
  6912. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6913. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6914. var engine = scene.getEngine();
  6915. if (!engine) {
  6916. return;
  6917. }
  6918. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6919. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6920. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6921. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6922. texture._baseWidth = width;
  6923. texture._baseHeight = height;
  6924. texture._width = potWidth;
  6925. texture._height = potHeight;
  6926. texture.isReady = true;
  6927. processFunction(potWidth, potHeight);
  6928. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6929. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6930. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6931. if (!noMipmap && !isCompressed) {
  6932. gl.generateMipmap(gl.TEXTURE_2D);
  6933. }
  6934. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6935. engine.resetTextureCache();
  6936. scene._removePendingData(texture);
  6937. texture.onLoadedCallbacks.forEach(function (callback) {
  6938. callback();
  6939. });
  6940. texture.onLoadedCallbacks = [];
  6941. };
  6942. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6943. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6944. var img;
  6945. var onload = function () {
  6946. loadedImages[index] = img;
  6947. loadedImages._internalCount++;
  6948. scene._removePendingData(img);
  6949. if (loadedImages._internalCount === 6) {
  6950. onfinish(loadedImages);
  6951. }
  6952. };
  6953. var onerror = function () {
  6954. scene._removePendingData(img);
  6955. if (onErrorCallBack) {
  6956. onErrorCallBack();
  6957. }
  6958. };
  6959. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6960. scene._addPendingData(img);
  6961. };
  6962. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6963. if (onError === void 0) { onError = null; }
  6964. var loadedImages = [];
  6965. loadedImages._internalCount = 0;
  6966. for (var index = 0; index < 6; index++) {
  6967. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6968. }
  6969. };
  6970. var InstancingAttributeInfo = (function () {
  6971. function InstancingAttributeInfo() {
  6972. }
  6973. return InstancingAttributeInfo;
  6974. }());
  6975. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6976. var EngineCapabilities = (function () {
  6977. function EngineCapabilities() {
  6978. }
  6979. return EngineCapabilities;
  6980. }());
  6981. BABYLON.EngineCapabilities = EngineCapabilities;
  6982. /**
  6983. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6984. */
  6985. var Engine = (function () {
  6986. /**
  6987. * @constructor
  6988. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6989. * @param {boolean} [antialias] - enable antialias
  6990. * @param options - further options to be sent to the getContext function
  6991. */
  6992. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6993. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  6994. var _this = this;
  6995. // Public members
  6996. this.isFullscreen = false;
  6997. this.isPointerLock = false;
  6998. this.cullBackFaces = true;
  6999. this.renderEvenInBackground = true;
  7000. this.preventCacheWipeBetweenFrames = true;
  7001. // To enable/disable IDB support and avoid XHR on .manifest
  7002. this.enableOfflineSupport = BABYLON.Database;
  7003. this.scenes = new Array();
  7004. this._windowIsBackground = false;
  7005. this._webGLVersion = 1.0;
  7006. this._badOS = false;
  7007. this._drawCalls = new BABYLON.PerfCounter();
  7008. this._renderingQueueLaunched = false;
  7009. this._activeRenderLoops = [];
  7010. // FPS
  7011. this.fpsRange = 60;
  7012. this.previousFramesDuration = [];
  7013. this.fps = 60;
  7014. this.deltaTime = 0;
  7015. // States
  7016. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7017. this._stencilState = new BABYLON.Internals._StencilState();
  7018. this._alphaState = new BABYLON.Internals._AlphaState();
  7019. this._alphaMode = Engine.ALPHA_DISABLE;
  7020. // Cache
  7021. this._loadedTexturesCache = new Array();
  7022. this._maxTextureChannels = 16;
  7023. this._activeTexturesCache = new Array(this._maxTextureChannels);
  7024. this._compiledEffects = {};
  7025. this._vertexAttribArraysEnabled = [];
  7026. this._uintIndicesCurrentlySet = false;
  7027. this._currentBoundBuffer = new Array();
  7028. this._currentBufferPointers = [];
  7029. this._currentInstanceLocations = new Array();
  7030. this._currentInstanceBuffers = new Array();
  7031. this._vaoRecordInProgress = false;
  7032. this._mustWipeVertexAttributes = false;
  7033. // Hardware supported Compressed Textures
  7034. this._texturesSupported = new Array();
  7035. this._onVRFullScreenTriggered = function () {
  7036. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7037. //get the old size before we change
  7038. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7039. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7040. //get the width and height, change the render size
  7041. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7042. var width, height;
  7043. _this.setHardwareScalingLevel(1);
  7044. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7045. }
  7046. else {
  7047. //When the specs are implemented, need to uncomment this.
  7048. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7049. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7050. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7051. _this._vrDisplayEnabled = undefined;
  7052. }
  7053. };
  7054. this._renderingCanvas = canvas;
  7055. Engine.Instances.push(this);
  7056. options = options || {};
  7057. if (antialias != null) {
  7058. options.antialias = antialias;
  7059. }
  7060. if (options.preserveDrawingBuffer === undefined) {
  7061. options.preserveDrawingBuffer = false;
  7062. }
  7063. if (options.audioEngine === undefined) {
  7064. options.audioEngine = true;
  7065. }
  7066. if (options.stencil === undefined) {
  7067. options.stencil = true;
  7068. }
  7069. // GL
  7070. if (!options.disableWebGL2Support) {
  7071. try {
  7072. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7073. if (this._gl) {
  7074. this._webGLVersion = 2.0;
  7075. }
  7076. }
  7077. catch (e) {
  7078. // Do nothing
  7079. }
  7080. }
  7081. if (!this._gl) {
  7082. if (!canvas) {
  7083. throw new Error("The provided canvas is null or undefined.");
  7084. }
  7085. try {
  7086. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7087. }
  7088. catch (e) {
  7089. throw new Error("WebGL not supported");
  7090. }
  7091. }
  7092. if (!this._gl) {
  7093. throw new Error("WebGL not supported");
  7094. }
  7095. this._onBlur = function () {
  7096. _this._windowIsBackground = true;
  7097. };
  7098. this._onFocus = function () {
  7099. _this._windowIsBackground = false;
  7100. };
  7101. window.addEventListener("blur", this._onBlur);
  7102. window.addEventListener("focus", this._onFocus);
  7103. // Viewport
  7104. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7105. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7106. this.resize();
  7107. // Caps
  7108. this._isStencilEnable = options.stencil;
  7109. this._caps = new EngineCapabilities();
  7110. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  7111. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  7112. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  7113. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  7114. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  7115. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  7116. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  7117. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  7118. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  7119. // Infos
  7120. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  7121. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  7122. if (rendererInfo != null) {
  7123. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  7124. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  7125. }
  7126. if (!this._glVendor) {
  7127. this._glVendor = "Unknown vendor";
  7128. }
  7129. if (!this._glRenderer) {
  7130. this._glRenderer = "Unknown renderer";
  7131. }
  7132. // Extensions
  7133. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  7134. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  7135. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  7136. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  7137. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  7138. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  7139. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  7140. 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');
  7141. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  7142. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  7143. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  7144. this._caps.highPrecisionShaderSupported = true;
  7145. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  7146. // Checks if some of the format renders first to allow the use of webgl inspector.
  7147. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  7148. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  7149. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  7150. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  7151. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  7152. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  7153. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  7154. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  7155. // Vertex array object
  7156. if (this._webGLVersion > 1) {
  7157. this._caps.vertexArrayObject = true;
  7158. }
  7159. else {
  7160. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  7161. if (vertexArrayObjectExtension != null) {
  7162. this._caps.vertexArrayObject = true;
  7163. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  7164. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  7165. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  7166. }
  7167. else {
  7168. this._caps.vertexArrayObject = false;
  7169. }
  7170. }
  7171. // Instances count
  7172. if (this._webGLVersion > 1) {
  7173. this._caps.instancedArrays = true;
  7174. }
  7175. else {
  7176. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  7177. if (instanceExtension != null) {
  7178. this._caps.instancedArrays = true;
  7179. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  7180. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  7181. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  7182. }
  7183. else {
  7184. this._caps.instancedArrays = false;
  7185. }
  7186. }
  7187. // Intelligently add supported compressed formats in order to check for.
  7188. // Check for ASTC support first as it is most powerful and to be very cross platform.
  7189. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  7190. // Likely no hardware which supports both PVR & DXT, so order matters little.
  7191. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  7192. if (this._caps.astc)
  7193. this.texturesSupported.push('-astc.ktx');
  7194. if (this._caps.s3tc)
  7195. this.texturesSupported.push('-dxt.ktx');
  7196. if (this._caps.pvrtc)
  7197. this.texturesSupported.push('-pvrtc.ktx');
  7198. if (this._caps.etc2)
  7199. this.texturesSupported.push('-etc2.ktx');
  7200. if (this._caps.etc1)
  7201. this.texturesSupported.push('-etc1.ktx');
  7202. if (this._gl.getShaderPrecisionFormat) {
  7203. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  7204. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  7205. }
  7206. // Depth buffer
  7207. this.setDepthBuffer(true);
  7208. this.setDepthFunctionToLessOrEqual();
  7209. this.setDepthWrite(true);
  7210. // Fullscreen
  7211. this._onFullscreenChange = function () {
  7212. if (document.fullscreen !== undefined) {
  7213. _this.isFullscreen = document.fullscreen;
  7214. }
  7215. else if (document.mozFullScreen !== undefined) {
  7216. _this.isFullscreen = document.mozFullScreen;
  7217. }
  7218. else if (document.webkitIsFullScreen !== undefined) {
  7219. _this.isFullscreen = document.webkitIsFullScreen;
  7220. }
  7221. else if (document.msIsFullScreen !== undefined) {
  7222. _this.isFullscreen = document.msIsFullScreen;
  7223. }
  7224. // Pointer lock
  7225. if (_this.isFullscreen && _this._pointerLockRequested) {
  7226. canvas.requestPointerLock = canvas.requestPointerLock ||
  7227. canvas.msRequestPointerLock ||
  7228. canvas.mozRequestPointerLock ||
  7229. canvas.webkitRequestPointerLock;
  7230. if (canvas.requestPointerLock) {
  7231. canvas.requestPointerLock();
  7232. }
  7233. }
  7234. };
  7235. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7236. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7237. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7238. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7239. // Pointer lock
  7240. this._onPointerLockChange = function () {
  7241. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7242. document.webkitPointerLockElement === canvas ||
  7243. document.msPointerLockElement === canvas ||
  7244. document.pointerLockElement === canvas);
  7245. };
  7246. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7247. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7248. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7249. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7250. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7251. Engine.audioEngine = new BABYLON.AudioEngine();
  7252. }
  7253. //Load WebVR Devices
  7254. if (options.autoEnableWebVR) {
  7255. this.initWebVR();
  7256. }
  7257. //Detect if we are running on a faulty buggy OS.
  7258. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  7259. //ua sniffing is the tool of the devil.
  7260. this._badOS = regexp.test(navigator.userAgent);
  7261. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7262. }
  7263. Object.defineProperty(Engine, "LastCreatedEngine", {
  7264. get: function () {
  7265. if (Engine.Instances.length === 0) {
  7266. return null;
  7267. }
  7268. return Engine.Instances[Engine.Instances.length - 1];
  7269. },
  7270. enumerable: true,
  7271. configurable: true
  7272. });
  7273. Object.defineProperty(Engine, "LastCreatedScene", {
  7274. get: function () {
  7275. var lastCreatedEngine = Engine.LastCreatedEngine;
  7276. if (!lastCreatedEngine) {
  7277. return null;
  7278. }
  7279. if (lastCreatedEngine.scenes.length === 0) {
  7280. return null;
  7281. }
  7282. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7283. },
  7284. enumerable: true,
  7285. configurable: true
  7286. });
  7287. /**
  7288. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7289. */
  7290. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7291. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7292. var engine = Engine.Instances[engineIndex];
  7293. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7294. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7295. }
  7296. }
  7297. };
  7298. Object.defineProperty(Engine, "NEVER", {
  7299. get: function () {
  7300. return Engine._NEVER;
  7301. },
  7302. enumerable: true,
  7303. configurable: true
  7304. });
  7305. Object.defineProperty(Engine, "ALWAYS", {
  7306. get: function () {
  7307. return Engine._ALWAYS;
  7308. },
  7309. enumerable: true,
  7310. configurable: true
  7311. });
  7312. Object.defineProperty(Engine, "LESS", {
  7313. get: function () {
  7314. return Engine._LESS;
  7315. },
  7316. enumerable: true,
  7317. configurable: true
  7318. });
  7319. Object.defineProperty(Engine, "EQUAL", {
  7320. get: function () {
  7321. return Engine._EQUAL;
  7322. },
  7323. enumerable: true,
  7324. configurable: true
  7325. });
  7326. Object.defineProperty(Engine, "LEQUAL", {
  7327. get: function () {
  7328. return Engine._LEQUAL;
  7329. },
  7330. enumerable: true,
  7331. configurable: true
  7332. });
  7333. Object.defineProperty(Engine, "GREATER", {
  7334. get: function () {
  7335. return Engine._GREATER;
  7336. },
  7337. enumerable: true,
  7338. configurable: true
  7339. });
  7340. Object.defineProperty(Engine, "GEQUAL", {
  7341. get: function () {
  7342. return Engine._GEQUAL;
  7343. },
  7344. enumerable: true,
  7345. configurable: true
  7346. });
  7347. Object.defineProperty(Engine, "NOTEQUAL", {
  7348. get: function () {
  7349. return Engine._NOTEQUAL;
  7350. },
  7351. enumerable: true,
  7352. configurable: true
  7353. });
  7354. Object.defineProperty(Engine, "KEEP", {
  7355. get: function () {
  7356. return Engine._KEEP;
  7357. },
  7358. enumerable: true,
  7359. configurable: true
  7360. });
  7361. Object.defineProperty(Engine, "REPLACE", {
  7362. get: function () {
  7363. return Engine._REPLACE;
  7364. },
  7365. enumerable: true,
  7366. configurable: true
  7367. });
  7368. Object.defineProperty(Engine, "INCR", {
  7369. get: function () {
  7370. return Engine._INCR;
  7371. },
  7372. enumerable: true,
  7373. configurable: true
  7374. });
  7375. Object.defineProperty(Engine, "DECR", {
  7376. get: function () {
  7377. return Engine._DECR;
  7378. },
  7379. enumerable: true,
  7380. configurable: true
  7381. });
  7382. Object.defineProperty(Engine, "INVERT", {
  7383. get: function () {
  7384. return Engine._INVERT;
  7385. },
  7386. enumerable: true,
  7387. configurable: true
  7388. });
  7389. Object.defineProperty(Engine, "INCR_WRAP", {
  7390. get: function () {
  7391. return Engine._INCR_WRAP;
  7392. },
  7393. enumerable: true,
  7394. configurable: true
  7395. });
  7396. Object.defineProperty(Engine, "DECR_WRAP", {
  7397. get: function () {
  7398. return Engine._DECR_WRAP;
  7399. },
  7400. enumerable: true,
  7401. configurable: true
  7402. });
  7403. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7404. get: function () {
  7405. return Engine._ALPHA_DISABLE;
  7406. },
  7407. enumerable: true,
  7408. configurable: true
  7409. });
  7410. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7411. get: function () {
  7412. return Engine._ALPHA_ONEONE;
  7413. },
  7414. enumerable: true,
  7415. configurable: true
  7416. });
  7417. Object.defineProperty(Engine, "ALPHA_ADD", {
  7418. get: function () {
  7419. return Engine._ALPHA_ADD;
  7420. },
  7421. enumerable: true,
  7422. configurable: true
  7423. });
  7424. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7425. get: function () {
  7426. return Engine._ALPHA_COMBINE;
  7427. },
  7428. enumerable: true,
  7429. configurable: true
  7430. });
  7431. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7432. get: function () {
  7433. return Engine._ALPHA_SUBTRACT;
  7434. },
  7435. enumerable: true,
  7436. configurable: true
  7437. });
  7438. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7439. get: function () {
  7440. return Engine._ALPHA_MULTIPLY;
  7441. },
  7442. enumerable: true,
  7443. configurable: true
  7444. });
  7445. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7446. get: function () {
  7447. return Engine._ALPHA_MAXIMIZED;
  7448. },
  7449. enumerable: true,
  7450. configurable: true
  7451. });
  7452. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7453. get: function () {
  7454. return Engine._ALPHA_PREMULTIPLIED;
  7455. },
  7456. enumerable: true,
  7457. configurable: true
  7458. });
  7459. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7460. get: function () {
  7461. return Engine._DELAYLOADSTATE_NONE;
  7462. },
  7463. enumerable: true,
  7464. configurable: true
  7465. });
  7466. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7467. get: function () {
  7468. return Engine._DELAYLOADSTATE_LOADED;
  7469. },
  7470. enumerable: true,
  7471. configurable: true
  7472. });
  7473. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7474. get: function () {
  7475. return Engine._DELAYLOADSTATE_LOADING;
  7476. },
  7477. enumerable: true,
  7478. configurable: true
  7479. });
  7480. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7481. get: function () {
  7482. return Engine._DELAYLOADSTATE_NOTLOADED;
  7483. },
  7484. enumerable: true,
  7485. configurable: true
  7486. });
  7487. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7488. get: function () {
  7489. return Engine._TEXTUREFORMAT_ALPHA;
  7490. },
  7491. enumerable: true,
  7492. configurable: true
  7493. });
  7494. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7495. get: function () {
  7496. return Engine._TEXTUREFORMAT_LUMINANCE;
  7497. },
  7498. enumerable: true,
  7499. configurable: true
  7500. });
  7501. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7502. get: function () {
  7503. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7504. },
  7505. enumerable: true,
  7506. configurable: true
  7507. });
  7508. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7509. get: function () {
  7510. return Engine._TEXTUREFORMAT_RGB;
  7511. },
  7512. enumerable: true,
  7513. configurable: true
  7514. });
  7515. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7516. get: function () {
  7517. return Engine._TEXTUREFORMAT_RGBA;
  7518. },
  7519. enumerable: true,
  7520. configurable: true
  7521. });
  7522. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7523. get: function () {
  7524. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7525. },
  7526. enumerable: true,
  7527. configurable: true
  7528. });
  7529. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7530. get: function () {
  7531. return Engine._TEXTURETYPE_FLOAT;
  7532. },
  7533. enumerable: true,
  7534. configurable: true
  7535. });
  7536. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7537. get: function () {
  7538. return Engine._TEXTURETYPE_HALF_FLOAT;
  7539. },
  7540. enumerable: true,
  7541. configurable: true
  7542. });
  7543. Object.defineProperty(Engine, "Version", {
  7544. get: function () {
  7545. return "3.0-alpha";
  7546. },
  7547. enumerable: true,
  7548. configurable: true
  7549. });
  7550. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7551. get: function () {
  7552. return this._texturesSupported;
  7553. },
  7554. enumerable: true,
  7555. configurable: true
  7556. });
  7557. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7558. get: function () {
  7559. return this._textureFormatInUse;
  7560. },
  7561. enumerable: true,
  7562. configurable: true
  7563. });
  7564. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7565. get: function () {
  7566. return this._webGLVersion;
  7567. },
  7568. enumerable: true,
  7569. configurable: true
  7570. });
  7571. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7572. /**
  7573. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7574. */
  7575. get: function () {
  7576. return this._isStencilEnable;
  7577. },
  7578. enumerable: true,
  7579. configurable: true
  7580. });
  7581. Engine.prototype._prepareWorkingCanvas = function () {
  7582. if (this._workingCanvas) {
  7583. return;
  7584. }
  7585. this._workingCanvas = document.createElement("canvas");
  7586. this._workingContext = this._workingCanvas.getContext("2d");
  7587. };
  7588. Engine.prototype.resetTextureCache = function () {
  7589. for (var index = 0; index < this._maxTextureChannels; index++) {
  7590. this._activeTexturesCache[index] = null;
  7591. }
  7592. };
  7593. Engine.prototype.getGlInfo = function () {
  7594. return {
  7595. vendor: this._glVendor,
  7596. renderer: this._glRenderer,
  7597. version: this._glVersion
  7598. };
  7599. };
  7600. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7601. if (useScreen === void 0) { useScreen = false; }
  7602. var viewport = camera.viewport;
  7603. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7604. };
  7605. Engine.prototype.getRenderWidth = function (useScreen) {
  7606. if (useScreen === void 0) { useScreen = false; }
  7607. if (!useScreen && this._currentRenderTarget) {
  7608. return this._currentRenderTarget._width;
  7609. }
  7610. return this._renderingCanvas.width;
  7611. };
  7612. Engine.prototype.getRenderHeight = function (useScreen) {
  7613. if (useScreen === void 0) { useScreen = false; }
  7614. if (!useScreen && this._currentRenderTarget) {
  7615. return this._currentRenderTarget._height;
  7616. }
  7617. return this._renderingCanvas.height;
  7618. };
  7619. Engine.prototype.getRenderingCanvas = function () {
  7620. return this._renderingCanvas;
  7621. };
  7622. Engine.prototype.getRenderingCanvasClientRect = function () {
  7623. return this._renderingCanvas.getBoundingClientRect();
  7624. };
  7625. Engine.prototype.setHardwareScalingLevel = function (level) {
  7626. this._hardwareScalingLevel = level;
  7627. this.resize();
  7628. };
  7629. Engine.prototype.getHardwareScalingLevel = function () {
  7630. return this._hardwareScalingLevel;
  7631. };
  7632. Engine.prototype.getLoadedTexturesCache = function () {
  7633. return this._loadedTexturesCache;
  7634. };
  7635. Engine.prototype.getCaps = function () {
  7636. return this._caps;
  7637. };
  7638. Object.defineProperty(Engine.prototype, "drawCalls", {
  7639. get: function () {
  7640. return this._drawCalls.current;
  7641. },
  7642. enumerable: true,
  7643. configurable: true
  7644. });
  7645. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7646. get: function () {
  7647. return this._drawCalls;
  7648. },
  7649. enumerable: true,
  7650. configurable: true
  7651. });
  7652. Engine.prototype.getDepthFunction = function () {
  7653. return this._depthCullingState.depthFunc;
  7654. };
  7655. Engine.prototype.setDepthFunction = function (depthFunc) {
  7656. this._depthCullingState.depthFunc = depthFunc;
  7657. };
  7658. Engine.prototype.setDepthFunctionToGreater = function () {
  7659. this._depthCullingState.depthFunc = this._gl.GREATER;
  7660. };
  7661. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7662. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7663. };
  7664. Engine.prototype.setDepthFunctionToLess = function () {
  7665. this._depthCullingState.depthFunc = this._gl.LESS;
  7666. };
  7667. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7668. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7669. };
  7670. Engine.prototype.getStencilBuffer = function () {
  7671. return this._stencilState.stencilTest;
  7672. };
  7673. Engine.prototype.setStencilBuffer = function (enable) {
  7674. this._stencilState.stencilTest = enable;
  7675. };
  7676. Engine.prototype.getStencilMask = function () {
  7677. return this._stencilState.stencilMask;
  7678. };
  7679. Engine.prototype.setStencilMask = function (mask) {
  7680. this._stencilState.stencilMask = mask;
  7681. };
  7682. Engine.prototype.getStencilFunction = function () {
  7683. return this._stencilState.stencilFunc;
  7684. };
  7685. Engine.prototype.getStencilFunctionReference = function () {
  7686. return this._stencilState.stencilFuncRef;
  7687. };
  7688. Engine.prototype.getStencilFunctionMask = function () {
  7689. return this._stencilState.stencilFuncMask;
  7690. };
  7691. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7692. this._stencilState.stencilFunc = stencilFunc;
  7693. };
  7694. Engine.prototype.setStencilFunctionReference = function (reference) {
  7695. this._stencilState.stencilFuncRef = reference;
  7696. };
  7697. Engine.prototype.setStencilFunctionMask = function (mask) {
  7698. this._stencilState.stencilFuncMask = mask;
  7699. };
  7700. Engine.prototype.getStencilOperationFail = function () {
  7701. return this._stencilState.stencilOpStencilFail;
  7702. };
  7703. Engine.prototype.getStencilOperationDepthFail = function () {
  7704. return this._stencilState.stencilOpDepthFail;
  7705. };
  7706. Engine.prototype.getStencilOperationPass = function () {
  7707. return this._stencilState.stencilOpStencilDepthPass;
  7708. };
  7709. Engine.prototype.setStencilOperationFail = function (operation) {
  7710. this._stencilState.stencilOpStencilFail = operation;
  7711. };
  7712. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7713. this._stencilState.stencilOpDepthFail = operation;
  7714. };
  7715. Engine.prototype.setStencilOperationPass = function (operation) {
  7716. this._stencilState.stencilOpStencilDepthPass = operation;
  7717. };
  7718. /**
  7719. * stop executing a render loop function and remove it from the execution array
  7720. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7721. */
  7722. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7723. if (!renderFunction) {
  7724. this._activeRenderLoops = [];
  7725. return;
  7726. }
  7727. var index = this._activeRenderLoops.indexOf(renderFunction);
  7728. if (index >= 0) {
  7729. this._activeRenderLoops.splice(index, 1);
  7730. }
  7731. };
  7732. Engine.prototype._renderLoop = function () {
  7733. var shouldRender = true;
  7734. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7735. shouldRender = false;
  7736. }
  7737. if (shouldRender) {
  7738. // Start new frame
  7739. this.beginFrame();
  7740. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7741. var renderFunction = this._activeRenderLoops[index];
  7742. renderFunction();
  7743. }
  7744. // Present
  7745. this.endFrame();
  7746. }
  7747. if (this._activeRenderLoops.length > 0) {
  7748. // Register new frame
  7749. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7750. }
  7751. else {
  7752. this._renderingQueueLaunched = false;
  7753. }
  7754. };
  7755. /**
  7756. * Register and execute a render loop. The engine can have more than one render function.
  7757. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7758. * @example
  7759. * engine.runRenderLoop(function () {
  7760. * scene.render()
  7761. * })
  7762. */
  7763. Engine.prototype.runRenderLoop = function (renderFunction) {
  7764. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7765. return;
  7766. }
  7767. this._activeRenderLoops.push(renderFunction);
  7768. if (!this._renderingQueueLaunched) {
  7769. this._renderingQueueLaunched = true;
  7770. this._bindedRenderFunction = this._renderLoop.bind(this);
  7771. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7772. }
  7773. };
  7774. /**
  7775. * Toggle full screen mode.
  7776. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7777. * @param {any} options - an options object to be sent to the requestFullscreen function
  7778. */
  7779. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7780. if (this.isFullscreen) {
  7781. BABYLON.Tools.ExitFullscreen();
  7782. }
  7783. else {
  7784. this._pointerLockRequested = requestPointerLock;
  7785. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7786. }
  7787. };
  7788. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7789. if (stencil === void 0) { stencil = false; }
  7790. this.applyStates();
  7791. var mode = 0;
  7792. if (backBuffer && color) {
  7793. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7794. mode |= this._gl.COLOR_BUFFER_BIT;
  7795. }
  7796. if (depth) {
  7797. this._gl.clearDepth(1.0);
  7798. mode |= this._gl.DEPTH_BUFFER_BIT;
  7799. }
  7800. if (stencil) {
  7801. this._gl.clearStencil(0);
  7802. mode |= this._gl.STENCIL_BUFFER_BIT;
  7803. }
  7804. this._gl.clear(mode);
  7805. };
  7806. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7807. var gl = this._gl;
  7808. // Save state
  7809. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7810. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7811. // Change state
  7812. gl.enable(gl.SCISSOR_TEST);
  7813. gl.scissor(x, y, width, height);
  7814. // Clear
  7815. this.clear(clearColor, true, true, true);
  7816. // Restore state
  7817. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7818. if (curScissor === true) {
  7819. gl.enable(gl.SCISSOR_TEST);
  7820. }
  7821. else {
  7822. gl.disable(gl.SCISSOR_TEST);
  7823. }
  7824. };
  7825. /**
  7826. * Set the WebGL's viewport
  7827. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7828. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7829. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7830. */
  7831. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7832. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7833. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7834. var x = viewport.x || 0;
  7835. var y = viewport.y || 0;
  7836. this._cachedViewport = viewport;
  7837. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7838. };
  7839. /**
  7840. * Directly set the WebGL Viewport
  7841. * The x, y, width & height are directly passed to the WebGL call
  7842. * @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.
  7843. */
  7844. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7845. var currentViewport = this._cachedViewport;
  7846. this._cachedViewport = null;
  7847. this._gl.viewport(x, y, width, height);
  7848. return currentViewport;
  7849. };
  7850. Engine.prototype.beginFrame = function () {
  7851. this._measureFps();
  7852. };
  7853. Engine.prototype.endFrame = function () {
  7854. //force a flush in case we are using a bad OS.
  7855. if (this._badOS) {
  7856. this.flushFramebuffer();
  7857. }
  7858. //submit frame to the vr device, if enabled
  7859. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7860. this._vrDisplayEnabled.submitFrame();
  7861. }
  7862. };
  7863. /**
  7864. * resize the view according to the canvas' size.
  7865. * @example
  7866. * window.addEventListener("resize", function () {
  7867. * engine.resize();
  7868. * });
  7869. */
  7870. Engine.prototype.resize = function () {
  7871. // We're not resizing the size of the canvas while in VR mode & presenting
  7872. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  7873. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7874. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7875. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7876. }
  7877. };
  7878. /**
  7879. * force a specific size of the canvas
  7880. * @param {number} width - the new canvas' width
  7881. * @param {number} height - the new canvas' height
  7882. */
  7883. Engine.prototype.setSize = function (width, height) {
  7884. this._renderingCanvas.width = width;
  7885. this._renderingCanvas.height = height;
  7886. for (var index = 0; index < this.scenes.length; index++) {
  7887. var scene = this.scenes[index];
  7888. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7889. var cam = scene.cameras[camIndex];
  7890. cam._currentRenderId = 0;
  7891. }
  7892. }
  7893. };
  7894. //WebVR functions
  7895. Engine.prototype.initWebVR = function () {
  7896. if (!this.vrDisplaysPromise) {
  7897. this._getVRDisplays();
  7898. }
  7899. };
  7900. Engine.prototype.enableVR = function (vrDevice) {
  7901. this._vrDisplayEnabled = vrDevice;
  7902. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7903. };
  7904. Engine.prototype.disableVR = function () {
  7905. if (this._vrDisplayEnabled) {
  7906. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7907. }
  7908. };
  7909. Engine.prototype._getVRDisplays = function () {
  7910. var _this = this;
  7911. var getWebVRDevices = function (devices) {
  7912. var size = devices.length;
  7913. var i = 0;
  7914. _this._vrDisplays = devices.filter(function (device) {
  7915. return devices[i] instanceof VRDisplay;
  7916. });
  7917. return _this._vrDisplays;
  7918. };
  7919. //using a key due to typescript
  7920. if (navigator.getVRDisplays) {
  7921. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7922. }
  7923. };
  7924. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7925. this._currentRenderTarget = texture;
  7926. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  7927. var gl = this._gl;
  7928. if (texture.isCube) {
  7929. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7930. }
  7931. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7932. this.wipeCaches();
  7933. };
  7934. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7935. if (this._currentFramebuffer !== framebuffer) {
  7936. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7937. this._currentFramebuffer = framebuffer;
  7938. }
  7939. };
  7940. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  7941. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7942. this._currentRenderTarget = null;
  7943. // If MSAA, we need to bitblt back to main texture
  7944. var gl = this._gl;
  7945. if (texture._MSAAFramebuffer) {
  7946. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  7947. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  7948. gl.blitFramebuffer(0, 0, texture._width, texture._height, 0, 0, texture._width, texture._height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  7949. }
  7950. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7951. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7952. gl.generateMipmap(gl.TEXTURE_2D);
  7953. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7954. }
  7955. if (onBeforeUnbind) {
  7956. if (texture._MSAAFramebuffer) {
  7957. // Bind the correct framebuffer
  7958. this.bindUnboundFramebuffer(texture._framebuffer);
  7959. }
  7960. onBeforeUnbind();
  7961. }
  7962. this.bindUnboundFramebuffer(null);
  7963. };
  7964. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7965. if (texture.generateMipMaps) {
  7966. var gl = this._gl;
  7967. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7968. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7969. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7970. }
  7971. };
  7972. Engine.prototype.flushFramebuffer = function () {
  7973. this._gl.flush();
  7974. };
  7975. Engine.prototype.restoreDefaultFramebuffer = function () {
  7976. this._currentRenderTarget = null;
  7977. this.bindUnboundFramebuffer(null);
  7978. this.setViewport(this._cachedViewport);
  7979. this.wipeCaches();
  7980. };
  7981. // UBOs
  7982. Engine.prototype.createUniformBuffer = function (elements) {
  7983. var ubo = this._gl.createBuffer();
  7984. this.bindUniformBuffer(ubo);
  7985. if (elements instanceof Float32Array) {
  7986. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  7987. }
  7988. else {
  7989. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  7990. }
  7991. this.bindUniformBuffer(null);
  7992. ubo.references = 1;
  7993. return ubo;
  7994. };
  7995. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  7996. var ubo = this._gl.createBuffer();
  7997. this.bindUniformBuffer(ubo);
  7998. if (elements instanceof Float32Array) {
  7999. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8000. }
  8001. else {
  8002. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8003. }
  8004. this.bindUniformBuffer(null);
  8005. ubo.references = 1;
  8006. return ubo;
  8007. };
  8008. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8009. this.bindUniformBuffer(uniformBuffer);
  8010. if (offset === undefined) {
  8011. offset = 0;
  8012. }
  8013. if (count === undefined) {
  8014. if (elements instanceof Float32Array) {
  8015. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8016. }
  8017. else {
  8018. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8019. }
  8020. }
  8021. else {
  8022. if (elements instanceof Float32Array) {
  8023. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8024. }
  8025. else {
  8026. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8027. }
  8028. }
  8029. this.bindUniformBuffer(null);
  8030. };
  8031. // VBOs
  8032. Engine.prototype._resetVertexBufferBinding = function () {
  8033. this.bindArrayBuffer(null);
  8034. this._cachedVertexBuffers = null;
  8035. };
  8036. Engine.prototype.createVertexBuffer = function (vertices) {
  8037. var vbo = this._gl.createBuffer();
  8038. this.bindArrayBuffer(vbo);
  8039. if (vertices instanceof Float32Array) {
  8040. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8041. }
  8042. else {
  8043. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8044. }
  8045. this._resetVertexBufferBinding();
  8046. vbo.references = 1;
  8047. return vbo;
  8048. };
  8049. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8050. var vbo = this._gl.createBuffer();
  8051. this.bindArrayBuffer(vbo);
  8052. if (vertices instanceof Float32Array) {
  8053. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8054. }
  8055. else {
  8056. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8057. }
  8058. this._resetVertexBufferBinding();
  8059. vbo.references = 1;
  8060. return vbo;
  8061. };
  8062. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8063. this.bindArrayBuffer(vertexBuffer);
  8064. if (offset === undefined) {
  8065. offset = 0;
  8066. }
  8067. if (count === undefined) {
  8068. if (vertices instanceof Float32Array) {
  8069. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8070. }
  8071. else {
  8072. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8073. }
  8074. }
  8075. else {
  8076. if (vertices instanceof Float32Array) {
  8077. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8078. }
  8079. else {
  8080. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8081. }
  8082. }
  8083. this._resetVertexBufferBinding();
  8084. };
  8085. Engine.prototype._resetIndexBufferBinding = function () {
  8086. this.bindIndexBuffer(null);
  8087. this._cachedIndexBuffer = null;
  8088. };
  8089. Engine.prototype.createIndexBuffer = function (indices) {
  8090. var vbo = this._gl.createBuffer();
  8091. this.bindIndexBuffer(vbo);
  8092. // Check for 32 bits indices
  8093. var arrayBuffer;
  8094. var need32Bits = false;
  8095. if (indices instanceof Uint16Array) {
  8096. arrayBuffer = indices;
  8097. }
  8098. else {
  8099. //check 32 bit support
  8100. if (this._caps.uintIndices) {
  8101. if (indices instanceof Uint32Array) {
  8102. arrayBuffer = indices;
  8103. need32Bits = true;
  8104. }
  8105. else {
  8106. //number[] or Int32Array, check if 32 bit is necessary
  8107. for (var index = 0; index < indices.length; index++) {
  8108. if (indices[index] > 65535) {
  8109. need32Bits = true;
  8110. break;
  8111. }
  8112. }
  8113. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8114. }
  8115. }
  8116. else {
  8117. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8118. arrayBuffer = new Uint16Array(indices);
  8119. }
  8120. }
  8121. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8122. this._resetIndexBufferBinding();
  8123. vbo.references = 1;
  8124. vbo.is32Bits = need32Bits;
  8125. return vbo;
  8126. };
  8127. Engine.prototype.bindArrayBuffer = function (buffer) {
  8128. if (!this._vaoRecordInProgress) {
  8129. this._unBindVertexArrayObject();
  8130. }
  8131. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8132. };
  8133. Engine.prototype.bindUniformBuffer = function (buffer) {
  8134. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8135. };
  8136. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8137. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8138. };
  8139. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8140. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8141. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8142. };
  8143. ;
  8144. Engine.prototype.bindIndexBuffer = function (buffer) {
  8145. if (!this._vaoRecordInProgress) {
  8146. this._unBindVertexArrayObject();
  8147. }
  8148. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8149. };
  8150. Engine.prototype.bindBuffer = function (buffer, target) {
  8151. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8152. this._gl.bindBuffer(target, buffer);
  8153. this._currentBoundBuffer[target] = buffer;
  8154. }
  8155. };
  8156. Engine.prototype.updateArrayBuffer = function (data) {
  8157. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8158. };
  8159. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8160. var pointer = this._currentBufferPointers[indx];
  8161. var changed = false;
  8162. if (!pointer) {
  8163. changed = true;
  8164. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  8165. }
  8166. else {
  8167. if (pointer.buffer !== buffer) {
  8168. pointer.buffer = buffer;
  8169. changed = true;
  8170. }
  8171. if (pointer.size !== size) {
  8172. pointer.size = size;
  8173. changed = true;
  8174. }
  8175. if (pointer.type !== type) {
  8176. pointer.type = type;
  8177. changed = true;
  8178. }
  8179. if (pointer.normalized !== normalized) {
  8180. pointer.normalized = normalized;
  8181. changed = true;
  8182. }
  8183. if (pointer.stride !== stride) {
  8184. pointer.stride = stride;
  8185. changed = true;
  8186. }
  8187. if (pointer.offset !== offset) {
  8188. pointer.offset = offset;
  8189. changed = true;
  8190. }
  8191. }
  8192. if (changed || this._vaoRecordInProgress) {
  8193. this.bindArrayBuffer(buffer);
  8194. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8195. }
  8196. };
  8197. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8198. if (indexBuffer == null) {
  8199. return;
  8200. }
  8201. if (this._cachedIndexBuffer !== indexBuffer) {
  8202. this._cachedIndexBuffer = indexBuffer;
  8203. this.bindIndexBuffer(indexBuffer);
  8204. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8205. }
  8206. };
  8207. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8208. var attributes = effect.getAttributesNames();
  8209. if (!this._vaoRecordInProgress) {
  8210. this._unBindVertexArrayObject();
  8211. }
  8212. this.unbindAllAttributes();
  8213. for (var index = 0; index < attributes.length; index++) {
  8214. var order = effect.getAttributeLocation(index);
  8215. if (order >= 0) {
  8216. var vertexBuffer = vertexBuffers[attributes[index]];
  8217. if (!vertexBuffer) {
  8218. continue;
  8219. }
  8220. this._gl.enableVertexAttribArray(order);
  8221. if (!this._vaoRecordInProgress) {
  8222. this._vertexAttribArraysEnabled[order] = true;
  8223. }
  8224. var buffer = vertexBuffer.getBuffer();
  8225. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8226. if (vertexBuffer.getIsInstanced()) {
  8227. this._gl.vertexAttribDivisor(order, 1);
  8228. if (!this._vaoRecordInProgress) {
  8229. this._currentInstanceLocations.push(order);
  8230. this._currentInstanceBuffers.push(buffer);
  8231. }
  8232. }
  8233. }
  8234. }
  8235. };
  8236. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8237. var vao = this._gl.createVertexArray();
  8238. this._vaoRecordInProgress = true;
  8239. this._gl.bindVertexArray(vao);
  8240. this._mustWipeVertexAttributes = true;
  8241. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8242. this.bindIndexBuffer(indexBuffer);
  8243. this._vaoRecordInProgress = false;
  8244. this._gl.bindVertexArray(null);
  8245. return vao;
  8246. };
  8247. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8248. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8249. this._cachedVertexArrayObject = vertexArrayObject;
  8250. this._gl.bindVertexArray(vertexArrayObject);
  8251. this._cachedVertexBuffers = null;
  8252. this._cachedIndexBuffer = null;
  8253. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8254. this._mustWipeVertexAttributes = true;
  8255. }
  8256. };
  8257. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8258. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8259. this._cachedVertexBuffers = vertexBuffer;
  8260. this._cachedEffectForVertexBuffers = effect;
  8261. var attributesCount = effect.getAttributesCount();
  8262. this._unBindVertexArrayObject();
  8263. this.unbindAllAttributes();
  8264. var offset = 0;
  8265. for (var index = 0; index < attributesCount; index++) {
  8266. if (index < vertexDeclaration.length) {
  8267. var order = effect.getAttributeLocation(index);
  8268. if (order >= 0) {
  8269. this._gl.enableVertexAttribArray(order);
  8270. this._vertexAttribArraysEnabled[order] = true;
  8271. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  8272. }
  8273. offset += vertexDeclaration[index] * 4;
  8274. }
  8275. }
  8276. }
  8277. this._bindIndexBufferWithCache(indexBuffer);
  8278. };
  8279. Engine.prototype._unBindVertexArrayObject = function () {
  8280. if (!this._cachedVertexArrayObject) {
  8281. return;
  8282. }
  8283. this._cachedVertexArrayObject = null;
  8284. this._gl.bindVertexArray(null);
  8285. };
  8286. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  8287. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  8288. this._cachedVertexBuffers = vertexBuffers;
  8289. this._cachedEffectForVertexBuffers = effect;
  8290. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8291. }
  8292. this._bindIndexBufferWithCache(indexBuffer);
  8293. };
  8294. Engine.prototype.unbindInstanceAttributes = function () {
  8295. var boundBuffer;
  8296. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  8297. var instancesBuffer = this._currentInstanceBuffers[i];
  8298. if (boundBuffer != instancesBuffer) {
  8299. boundBuffer = instancesBuffer;
  8300. this.bindArrayBuffer(instancesBuffer);
  8301. }
  8302. var offsetLocation = this._currentInstanceLocations[i];
  8303. this._gl.vertexAttribDivisor(offsetLocation, 0);
  8304. }
  8305. this._currentInstanceBuffers.length = 0;
  8306. this._currentInstanceLocations.length = 0;
  8307. };
  8308. Engine.prototype.releaseVertexArrayObject = function (vao) {
  8309. this._gl.deleteVertexArray(vao);
  8310. };
  8311. Engine.prototype._releaseBuffer = function (buffer) {
  8312. buffer.references--;
  8313. if (buffer.references === 0) {
  8314. this._gl.deleteBuffer(buffer);
  8315. return true;
  8316. }
  8317. return false;
  8318. };
  8319. Engine.prototype.createInstancesBuffer = function (capacity) {
  8320. var buffer = this._gl.createBuffer();
  8321. buffer.capacity = capacity;
  8322. this.bindArrayBuffer(buffer);
  8323. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  8324. return buffer;
  8325. };
  8326. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  8327. this._gl.deleteBuffer(buffer);
  8328. };
  8329. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  8330. this.bindArrayBuffer(instancesBuffer);
  8331. if (data) {
  8332. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8333. }
  8334. if (offsetLocations[0].index !== undefined) {
  8335. var stride = 0;
  8336. for (var i = 0; i < offsetLocations.length; i++) {
  8337. var ai = offsetLocations[i];
  8338. stride += ai.attributeSize * 4;
  8339. }
  8340. for (var i = 0; i < offsetLocations.length; i++) {
  8341. var ai = offsetLocations[i];
  8342. if (!this._vertexAttribArraysEnabled[ai.index]) {
  8343. this._gl.enableVertexAttribArray(ai.index);
  8344. this._vertexAttribArraysEnabled[ai.index] = true;
  8345. }
  8346. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  8347. this._gl.vertexAttribDivisor(ai.index, 1);
  8348. this._currentInstanceLocations.push(ai.index);
  8349. this._currentInstanceBuffers.push(instancesBuffer);
  8350. }
  8351. }
  8352. else {
  8353. for (var index = 0; index < 4; index++) {
  8354. var offsetLocation = offsetLocations[index];
  8355. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  8356. this._gl.enableVertexAttribArray(offsetLocation);
  8357. this._vertexAttribArraysEnabled[offsetLocation] = true;
  8358. }
  8359. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  8360. this._gl.vertexAttribDivisor(offsetLocation, 1);
  8361. this._currentInstanceLocations.push(offsetLocation);
  8362. this._currentInstanceBuffers.push(instancesBuffer);
  8363. }
  8364. }
  8365. };
  8366. Engine.prototype.applyStates = function () {
  8367. this._depthCullingState.apply(this._gl);
  8368. this._stencilState.apply(this._gl);
  8369. this._alphaState.apply(this._gl);
  8370. };
  8371. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  8372. // Apply states
  8373. this.applyStates();
  8374. this._drawCalls.addCount(1, false);
  8375. // Render
  8376. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  8377. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  8378. if (instancesCount) {
  8379. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  8380. return;
  8381. }
  8382. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  8383. };
  8384. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  8385. // Apply states
  8386. this.applyStates();
  8387. this._drawCalls.addCount(1, false);
  8388. if (instancesCount) {
  8389. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  8390. return;
  8391. }
  8392. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  8393. };
  8394. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  8395. // Apply states
  8396. this.applyStates();
  8397. this._drawCalls.addCount(1, false);
  8398. if (instancesCount) {
  8399. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  8400. return;
  8401. }
  8402. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  8403. };
  8404. // Shaders
  8405. Engine.prototype._releaseEffect = function (effect) {
  8406. if (this._compiledEffects[effect._key]) {
  8407. delete this._compiledEffects[effect._key];
  8408. if (effect.getProgram()) {
  8409. this._gl.deleteProgram(effect.getProgram());
  8410. }
  8411. }
  8412. };
  8413. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  8414. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  8415. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  8416. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  8417. if (this._compiledEffects[name]) {
  8418. return this._compiledEffects[name];
  8419. }
  8420. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  8421. effect._key = name;
  8422. this._compiledEffects[name] = effect;
  8423. return effect;
  8424. };
  8425. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  8426. if (uniformsNames === void 0) { uniformsNames = []; }
  8427. if (samplers === void 0) { samplers = []; }
  8428. if (defines === void 0) { defines = ""; }
  8429. return this.createEffect({
  8430. vertex: "particles",
  8431. fragmentElement: fragmentName
  8432. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  8433. };
  8434. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  8435. context = context || this._gl;
  8436. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  8437. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  8438. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  8439. var shaderProgram = context.createProgram();
  8440. context.attachShader(shaderProgram, vertexShader);
  8441. context.attachShader(shaderProgram, fragmentShader);
  8442. context.linkProgram(shaderProgram);
  8443. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  8444. if (!linked) {
  8445. var error = context.getProgramInfoLog(shaderProgram);
  8446. if (error) {
  8447. throw new Error(error);
  8448. }
  8449. }
  8450. context.deleteShader(vertexShader);
  8451. context.deleteShader(fragmentShader);
  8452. return shaderProgram;
  8453. };
  8454. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  8455. var results = [];
  8456. for (var index = 0; index < uniformsNames.length; index++) {
  8457. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  8458. }
  8459. return results;
  8460. };
  8461. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  8462. var results = [];
  8463. for (var index = 0; index < attributesNames.length; index++) {
  8464. try {
  8465. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  8466. }
  8467. catch (e) {
  8468. results.push(-1);
  8469. }
  8470. }
  8471. return results;
  8472. };
  8473. Engine.prototype.enableEffect = function (effect) {
  8474. // Use program
  8475. this.setProgram(effect.getProgram());
  8476. this._currentEffect = effect;
  8477. if (effect.onBind) {
  8478. effect.onBind(effect);
  8479. }
  8480. };
  8481. Engine.prototype.setIntArray = function (uniform, array) {
  8482. if (!uniform)
  8483. return;
  8484. this._gl.uniform1iv(uniform, array);
  8485. };
  8486. Engine.prototype.setIntArray2 = function (uniform, array) {
  8487. if (!uniform || array.length % 2 !== 0)
  8488. return;
  8489. this._gl.uniform2iv(uniform, array);
  8490. };
  8491. Engine.prototype.setIntArray3 = function (uniform, array) {
  8492. if (!uniform || array.length % 3 !== 0)
  8493. return;
  8494. this._gl.uniform3iv(uniform, array);
  8495. };
  8496. Engine.prototype.setIntArray4 = function (uniform, array) {
  8497. if (!uniform || array.length % 4 !== 0)
  8498. return;
  8499. this._gl.uniform4iv(uniform, array);
  8500. };
  8501. Engine.prototype.setFloatArray = function (uniform, array) {
  8502. if (!uniform)
  8503. return;
  8504. this._gl.uniform1fv(uniform, array);
  8505. };
  8506. Engine.prototype.setFloatArray2 = function (uniform, array) {
  8507. if (!uniform || array.length % 2 !== 0)
  8508. return;
  8509. this._gl.uniform2fv(uniform, array);
  8510. };
  8511. Engine.prototype.setFloatArray3 = function (uniform, array) {
  8512. if (!uniform || array.length % 3 !== 0)
  8513. return;
  8514. this._gl.uniform3fv(uniform, array);
  8515. };
  8516. Engine.prototype.setFloatArray4 = function (uniform, array) {
  8517. if (!uniform || array.length % 4 !== 0)
  8518. return;
  8519. this._gl.uniform4fv(uniform, array);
  8520. };
  8521. Engine.prototype.setArray = function (uniform, array) {
  8522. if (!uniform)
  8523. return;
  8524. this._gl.uniform1fv(uniform, array);
  8525. };
  8526. Engine.prototype.setArray2 = function (uniform, array) {
  8527. if (!uniform || array.length % 2 !== 0)
  8528. return;
  8529. this._gl.uniform2fv(uniform, array);
  8530. };
  8531. Engine.prototype.setArray3 = function (uniform, array) {
  8532. if (!uniform || array.length % 3 !== 0)
  8533. return;
  8534. this._gl.uniform3fv(uniform, array);
  8535. };
  8536. Engine.prototype.setArray4 = function (uniform, array) {
  8537. if (!uniform || array.length % 4 !== 0)
  8538. return;
  8539. this._gl.uniform4fv(uniform, array);
  8540. };
  8541. Engine.prototype.setMatrices = function (uniform, matrices) {
  8542. if (!uniform)
  8543. return;
  8544. this._gl.uniformMatrix4fv(uniform, false, matrices);
  8545. };
  8546. Engine.prototype.setMatrix = function (uniform, matrix) {
  8547. if (!uniform)
  8548. return;
  8549. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  8550. };
  8551. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  8552. if (!uniform)
  8553. return;
  8554. this._gl.uniformMatrix3fv(uniform, false, matrix);
  8555. };
  8556. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  8557. if (!uniform)
  8558. return;
  8559. this._gl.uniformMatrix2fv(uniform, false, matrix);
  8560. };
  8561. Engine.prototype.setFloat = function (uniform, value) {
  8562. if (!uniform)
  8563. return;
  8564. this._gl.uniform1f(uniform, value);
  8565. };
  8566. Engine.prototype.setFloat2 = function (uniform, x, y) {
  8567. if (!uniform)
  8568. return;
  8569. this._gl.uniform2f(uniform, x, y);
  8570. };
  8571. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  8572. if (!uniform)
  8573. return;
  8574. this._gl.uniform3f(uniform, x, y, z);
  8575. };
  8576. Engine.prototype.setBool = function (uniform, bool) {
  8577. if (!uniform)
  8578. return;
  8579. this._gl.uniform1i(uniform, bool);
  8580. };
  8581. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  8582. if (!uniform)
  8583. return;
  8584. this._gl.uniform4f(uniform, x, y, z, w);
  8585. };
  8586. Engine.prototype.setColor3 = function (uniform, color3) {
  8587. if (!uniform)
  8588. return;
  8589. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  8590. };
  8591. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  8592. if (!uniform)
  8593. return;
  8594. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  8595. };
  8596. // States
  8597. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  8598. if (zOffset === void 0) { zOffset = 0; }
  8599. if (reverseSide === void 0) { reverseSide = false; }
  8600. // Culling
  8601. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  8602. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  8603. var cullFace = this.cullBackFaces ? showSide : hideSide;
  8604. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  8605. if (culling) {
  8606. this._depthCullingState.cullFace = cullFace;
  8607. this._depthCullingState.cull = true;
  8608. }
  8609. else {
  8610. this._depthCullingState.cull = false;
  8611. }
  8612. }
  8613. // Z offset
  8614. this._depthCullingState.zOffset = zOffset;
  8615. };
  8616. Engine.prototype.setDepthBuffer = function (enable) {
  8617. this._depthCullingState.depthTest = enable;
  8618. };
  8619. Engine.prototype.getDepthWrite = function () {
  8620. return this._depthCullingState.depthMask;
  8621. };
  8622. Engine.prototype.setDepthWrite = function (enable) {
  8623. this._depthCullingState.depthMask = enable;
  8624. };
  8625. Engine.prototype.setColorWrite = function (enable) {
  8626. this._gl.colorMask(enable, enable, enable, enable);
  8627. };
  8628. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8629. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8630. if (this._alphaMode === mode) {
  8631. return;
  8632. }
  8633. switch (mode) {
  8634. case Engine.ALPHA_DISABLE:
  8635. this._alphaState.alphaBlend = false;
  8636. break;
  8637. case Engine.ALPHA_PREMULTIPLIED:
  8638. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8639. this._alphaState.alphaBlend = true;
  8640. break;
  8641. case Engine.ALPHA_COMBINE:
  8642. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8643. this._alphaState.alphaBlend = true;
  8644. break;
  8645. case Engine.ALPHA_ONEONE:
  8646. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8647. this._alphaState.alphaBlend = true;
  8648. break;
  8649. case Engine.ALPHA_ADD:
  8650. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8651. this._alphaState.alphaBlend = true;
  8652. break;
  8653. case Engine.ALPHA_SUBTRACT:
  8654. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8655. this._alphaState.alphaBlend = true;
  8656. break;
  8657. case Engine.ALPHA_MULTIPLY:
  8658. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8659. this._alphaState.alphaBlend = true;
  8660. break;
  8661. case Engine.ALPHA_MAXIMIZED:
  8662. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8663. this._alphaState.alphaBlend = true;
  8664. break;
  8665. }
  8666. if (!noDepthWriteChange) {
  8667. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8668. }
  8669. this._alphaMode = mode;
  8670. };
  8671. Engine.prototype.getAlphaMode = function () {
  8672. return this._alphaMode;
  8673. };
  8674. Engine.prototype.setAlphaTesting = function (enable) {
  8675. this._alphaTest = enable;
  8676. };
  8677. Engine.prototype.getAlphaTesting = function () {
  8678. return !!this._alphaTest;
  8679. };
  8680. // Textures
  8681. Engine.prototype.wipeCaches = function () {
  8682. if (this.preventCacheWipeBetweenFrames) {
  8683. return;
  8684. }
  8685. this.resetTextureCache();
  8686. this._currentEffect = null;
  8687. this._stencilState.reset();
  8688. this._depthCullingState.reset();
  8689. this.setDepthFunctionToLessOrEqual();
  8690. this._alphaState.reset();
  8691. this._cachedVertexBuffers = null;
  8692. this._cachedIndexBuffer = null;
  8693. this._cachedEffectForVertexBuffers = null;
  8694. this._unBindVertexArrayObject();
  8695. this.bindIndexBuffer(null);
  8696. this.bindArrayBuffer(null);
  8697. };
  8698. /**
  8699. * Set the compressed texture format to use, based on the formats you have, and the formats
  8700. * supported by the hardware / browser.
  8701. *
  8702. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  8703. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  8704. * to API arguments needed to compressed textures. This puts the burden on the container
  8705. * generator to house the arcane code for determining these for current & future formats.
  8706. *
  8707. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  8708. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  8709. *
  8710. * Note: The result of this call is not taken into account when a texture is base64.
  8711. *
  8712. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  8713. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  8714. *
  8715. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  8716. * @returns The extension selected.
  8717. */
  8718. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8719. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8720. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8721. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8722. return this._textureFormatInUse = this._texturesSupported[i];
  8723. }
  8724. }
  8725. }
  8726. // actively set format to nothing, to allow this to be called more than once
  8727. // and possibly fail the 2nd time
  8728. return this._textureFormatInUse = null;
  8729. };
  8730. /**
  8731. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  8732. * @param {string} urlArg- This contains one of the following:
  8733. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  8734. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  8735. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  8736. *
  8737. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  8738. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  8739. * @param {Scene} scene- Needed for loading to the correct scene.
  8740. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  8741. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  8742. * @param {callback} onError- Optional callback to be called upon failure.
  8743. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  8744. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  8745. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  8746. *
  8747. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  8748. */
  8749. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  8750. var _this = this;
  8751. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8752. if (onLoad === void 0) { onLoad = null; }
  8753. if (onError === void 0) { onError = null; }
  8754. if (buffer === void 0) { buffer = null; }
  8755. var texture = fallBack ? fallBack : this._gl.createTexture();
  8756. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  8757. var fromData = url.substr(0, 5) === "data:";
  8758. var isBase64 = fromData && url.indexOf("base64") !== -1;
  8759. // establish the file extension, if possible
  8760. var lastDot = url.lastIndexOf('.');
  8761. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  8762. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8763. if (isDDS) {
  8764. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  8765. }
  8766. var isTGA = (extension === ".tga");
  8767. // determine if a ktx file should be substituted
  8768. var isKTX = false;
  8769. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  8770. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8771. isKTX = true;
  8772. }
  8773. scene._addPendingData(texture);
  8774. texture.url = url;
  8775. texture.noMipmap = noMipmap;
  8776. texture.references = 1;
  8777. texture.samplingMode = samplingMode;
  8778. texture.onLoadedCallbacks = [];
  8779. if (onLoad) {
  8780. texture.onLoadedCallbacks.push(onLoad);
  8781. }
  8782. if (!fallBack)
  8783. this._loadedTexturesCache.push(texture);
  8784. var onerror = function () {
  8785. scene._removePendingData(texture);
  8786. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  8787. if (isKTX) {
  8788. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  8789. }
  8790. else if (onError) {
  8791. onError();
  8792. }
  8793. };
  8794. var callback;
  8795. // processing for non-image formats
  8796. if (isKTX || isTGA || isDDS) {
  8797. if (isKTX) {
  8798. callback = function (data) {
  8799. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  8800. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  8801. ktx.uploadLevels(_this._gl, !noMipmap);
  8802. }, samplingMode);
  8803. };
  8804. }
  8805. else if (isTGA) {
  8806. callback = function (arrayBuffer) {
  8807. var data = new Uint8Array(arrayBuffer);
  8808. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8809. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8810. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8811. }, samplingMode);
  8812. };
  8813. }
  8814. else if (isDDS) {
  8815. callback = function (data) {
  8816. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8817. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8818. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8819. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8820. }, samplingMode);
  8821. };
  8822. }
  8823. if (!buffer) {
  8824. BABYLON.Tools.LoadFile(url, function (data) {
  8825. callback(data);
  8826. }, null, scene.database, true, onerror);
  8827. }
  8828. else {
  8829. callback(buffer);
  8830. }
  8831. // image format processing
  8832. }
  8833. else {
  8834. var onload = function (img) {
  8835. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8836. var isPot = (img.width === potWidth && img.height === potHeight);
  8837. if (!isPot) {
  8838. _this._prepareWorkingCanvas();
  8839. _this._workingCanvas.width = potWidth;
  8840. _this._workingCanvas.height = potHeight;
  8841. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8842. _this._workingContext.imageSmoothingEnabled = false;
  8843. _this._workingContext.mozImageSmoothingEnabled = false;
  8844. _this._workingContext.oImageSmoothingEnabled = false;
  8845. _this._workingContext.webkitImageSmoothingEnabled = false;
  8846. _this._workingContext.msImageSmoothingEnabled = false;
  8847. }
  8848. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8849. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8850. _this._workingContext.imageSmoothingEnabled = true;
  8851. _this._workingContext.mozImageSmoothingEnabled = true;
  8852. _this._workingContext.oImageSmoothingEnabled = true;
  8853. _this._workingContext.webkitImageSmoothingEnabled = true;
  8854. _this._workingContext.msImageSmoothingEnabled = true;
  8855. }
  8856. }
  8857. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? _this._gl.RGB : _this._gl.RGBA);
  8858. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8859. }, samplingMode);
  8860. };
  8861. if (!fromData || isBase64)
  8862. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8863. else if (buffer instanceof Array || typeof buffer === "string")
  8864. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8865. else
  8866. onload(buffer);
  8867. }
  8868. return texture;
  8869. };
  8870. Engine.prototype._getInternalFormat = function (format) {
  8871. var internalFormat = this._gl.RGBA;
  8872. switch (format) {
  8873. case Engine.TEXTUREFORMAT_ALPHA:
  8874. internalFormat = this._gl.ALPHA;
  8875. break;
  8876. case Engine.TEXTUREFORMAT_LUMINANCE:
  8877. internalFormat = this._gl.LUMINANCE;
  8878. break;
  8879. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8880. internalFormat = this._gl.LUMINANCE_ALPHA;
  8881. break;
  8882. case Engine.TEXTUREFORMAT_RGB:
  8883. internalFormat = this._gl.RGB;
  8884. break;
  8885. case Engine.TEXTUREFORMAT_RGBA:
  8886. internalFormat = this._gl.RGBA;
  8887. break;
  8888. }
  8889. return internalFormat;
  8890. };
  8891. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8892. if (compression === void 0) { compression = null; }
  8893. var internalFormat = this._getInternalFormat(format);
  8894. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8895. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8896. if (texture._width % 4 !== 0) {
  8897. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8898. }
  8899. if (compression) {
  8900. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8901. }
  8902. else {
  8903. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8904. }
  8905. if (texture.generateMipMaps) {
  8906. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8907. }
  8908. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8909. this.resetTextureCache();
  8910. texture.isReady = true;
  8911. };
  8912. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8913. if (compression === void 0) { compression = null; }
  8914. var texture = this._gl.createTexture();
  8915. texture._baseWidth = width;
  8916. texture._baseHeight = height;
  8917. texture._width = width;
  8918. texture._height = height;
  8919. texture.references = 1;
  8920. this.updateRawTexture(texture, data, format, invertY, compression);
  8921. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8922. // Filters
  8923. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8924. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8925. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8926. if (generateMipMaps) {
  8927. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8928. }
  8929. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8930. texture.samplingMode = samplingMode;
  8931. this._loadedTexturesCache.push(texture);
  8932. return texture;
  8933. };
  8934. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8935. var texture = this._gl.createTexture();
  8936. texture._baseWidth = width;
  8937. texture._baseHeight = height;
  8938. if (generateMipMaps) {
  8939. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8940. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8941. }
  8942. this.resetTextureCache();
  8943. texture._width = width;
  8944. texture._height = height;
  8945. texture.isReady = false;
  8946. texture.generateMipMaps = generateMipMaps;
  8947. texture.references = 1;
  8948. texture.samplingMode = samplingMode;
  8949. this.updateTextureSamplingMode(samplingMode, texture);
  8950. this._loadedTexturesCache.push(texture);
  8951. return texture;
  8952. };
  8953. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8954. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8955. if (texture.isCube) {
  8956. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8957. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8958. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8959. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8960. }
  8961. else {
  8962. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8963. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8964. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8965. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8966. }
  8967. texture.samplingMode = samplingMode;
  8968. };
  8969. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  8970. if (premulAlpha === void 0) { premulAlpha = false; }
  8971. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8972. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8973. if (premulAlpha) {
  8974. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8975. }
  8976. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  8977. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  8978. if (texture.generateMipMaps) {
  8979. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8980. }
  8981. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8982. if (premulAlpha) {
  8983. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8984. }
  8985. this.resetTextureCache();
  8986. texture.isReady = true;
  8987. };
  8988. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8989. if (texture._isDisabled) {
  8990. return;
  8991. }
  8992. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8993. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8994. try {
  8995. // Testing video texture support
  8996. if (this._videoTextureSupported === undefined) {
  8997. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8998. if (this._gl.getError() !== 0) {
  8999. this._videoTextureSupported = false;
  9000. }
  9001. else {
  9002. this._videoTextureSupported = true;
  9003. }
  9004. }
  9005. // Copy video through the current working canvas if video texture is not supported
  9006. if (!this._videoTextureSupported) {
  9007. if (!texture._workingCanvas) {
  9008. texture._workingCanvas = document.createElement("canvas");
  9009. texture._workingContext = texture._workingCanvas.getContext("2d");
  9010. texture._workingCanvas.width = texture._width;
  9011. texture._workingCanvas.height = texture._height;
  9012. }
  9013. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  9014. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9015. }
  9016. else {
  9017. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9018. }
  9019. if (texture.generateMipMaps) {
  9020. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9021. }
  9022. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9023. this.resetTextureCache();
  9024. texture.isReady = true;
  9025. }
  9026. catch (ex) {
  9027. // Something unexpected
  9028. // Let's disable the texture
  9029. texture._isDisabled = true;
  9030. }
  9031. };
  9032. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9033. // old version had a "generateMipMaps" arg instead of options.
  9034. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  9035. // in the same way, generateDepthBuffer is defaulted to true
  9036. var generateMipMaps = false;
  9037. var generateDepthBuffer = true;
  9038. var generateStencilBuffer = false;
  9039. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9040. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9041. if (options !== undefined) {
  9042. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9043. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9044. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9045. type = options.type === undefined ? type : options.type;
  9046. if (options.samplingMode !== undefined) {
  9047. samplingMode = options.samplingMode;
  9048. }
  9049. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9050. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9051. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9052. }
  9053. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9054. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9055. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9056. }
  9057. }
  9058. var gl = this._gl;
  9059. var texture = gl.createTexture();
  9060. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9061. var width = size.width || size;
  9062. var height = size.height || size;
  9063. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9064. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9065. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9066. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9067. }
  9068. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9069. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9070. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9071. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9072. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9073. // Create the framebuffer
  9074. var framebuffer = gl.createFramebuffer();
  9075. this.bindUnboundFramebuffer(framebuffer);
  9076. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9077. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9078. if (generateMipMaps) {
  9079. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9080. }
  9081. // Unbind
  9082. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9083. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9084. this.bindUnboundFramebuffer(null);
  9085. texture._framebuffer = framebuffer;
  9086. texture._baseWidth = width;
  9087. texture._baseHeight = height;
  9088. texture._width = width;
  9089. texture._height = height;
  9090. texture.isReady = true;
  9091. texture.samples = 1;
  9092. texture.generateMipMaps = generateMipMaps;
  9093. texture.references = 1;
  9094. texture.samplingMode = samplingMode;
  9095. texture.type = type;
  9096. texture._generateDepthBuffer = generateDepthBuffer;
  9097. texture._generateStencilBuffer = generateStencilBuffer;
  9098. this.resetTextureCache();
  9099. this._loadedTexturesCache.push(texture);
  9100. return texture;
  9101. };
  9102. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  9103. if (samples === void 0) { samples = 1; }
  9104. var depthStencilBuffer = null;
  9105. var gl = this._gl;
  9106. // Create the depth/stencil buffer
  9107. if (generateStencilBuffer) {
  9108. depthStencilBuffer = gl.createRenderbuffer();
  9109. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9110. if (samples > 1) {
  9111. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_STENCIL, width, height);
  9112. }
  9113. else {
  9114. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  9115. }
  9116. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9117. }
  9118. else if (generateDepthBuffer) {
  9119. depthStencilBuffer = gl.createRenderbuffer();
  9120. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  9121. if (samples > 1) {
  9122. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  9123. }
  9124. else {
  9125. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  9126. }
  9127. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  9128. }
  9129. return depthStencilBuffer;
  9130. };
  9131. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  9132. if (this.webGLVersion < 2) {
  9133. return 1;
  9134. }
  9135. if (texture.samples === samples) {
  9136. return samples;
  9137. }
  9138. var gl = this._gl;
  9139. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  9140. // Dispose previous render buffers
  9141. if (texture._depthStencilBuffer) {
  9142. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9143. }
  9144. if (texture._MSAAFramebuffer) {
  9145. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9146. }
  9147. if (texture._MSAARenderBuffer) {
  9148. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9149. }
  9150. if (samples > 1) {
  9151. texture._MSAAFramebuffer = gl.createFramebuffer();
  9152. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  9153. var colorRenderbuffer = gl.createRenderbuffer();
  9154. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  9155. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture._width, texture._height);
  9156. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  9157. texture._MSAARenderBuffer = colorRenderbuffer;
  9158. }
  9159. else {
  9160. this.bindUnboundFramebuffer(texture._framebuffer);
  9161. }
  9162. texture.samples = samples;
  9163. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture._width, texture._height, samples);
  9164. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9165. this.bindUnboundFramebuffer(null);
  9166. return samples;
  9167. };
  9168. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  9169. var gl = this._gl;
  9170. var texture = gl.createTexture();
  9171. var generateMipMaps = true;
  9172. var generateDepthBuffer = true;
  9173. var generateStencilBuffer = false;
  9174. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9175. if (options !== undefined) {
  9176. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  9177. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9178. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  9179. if (options.samplingMode !== undefined) {
  9180. samplingMode = options.samplingMode;
  9181. }
  9182. }
  9183. texture.isCube = true;
  9184. texture.references = 1;
  9185. texture.generateMipMaps = generateMipMaps;
  9186. texture.references = 1;
  9187. texture.samples = 1;
  9188. texture.samplingMode = samplingMode;
  9189. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9190. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9191. for (var face = 0; face < 6; face++) {
  9192. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  9193. }
  9194. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  9195. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  9196. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9197. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9198. // Create the framebuffer
  9199. var framebuffer = gl.createFramebuffer();
  9200. this.bindUnboundFramebuffer(framebuffer);
  9201. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  9202. // Mipmaps
  9203. if (texture.generateMipMaps) {
  9204. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9205. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9206. }
  9207. // Unbind
  9208. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9209. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9210. this.bindUnboundFramebuffer(null);
  9211. texture._framebuffer = framebuffer;
  9212. texture._width = size;
  9213. texture._height = size;
  9214. texture.isReady = true;
  9215. this.resetTextureCache();
  9216. this._loadedTexturesCache.push(texture);
  9217. return texture;
  9218. };
  9219. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format) {
  9220. var _this = this;
  9221. if (onLoad === void 0) { onLoad = null; }
  9222. if (onError === void 0) { onError = null; }
  9223. var gl = this._gl;
  9224. var texture = gl.createTexture();
  9225. texture.isCube = true;
  9226. texture.url = rootUrl;
  9227. texture.references = 1;
  9228. texture.onLoadedCallbacks = [];
  9229. var isKTX = false;
  9230. var lastDot = rootUrl.lastIndexOf('.');
  9231. var extension = rootUrl.substring(lastDot).toLowerCase();
  9232. if (this._textureFormatInUse) {
  9233. extension = this._textureFormatInUse;
  9234. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  9235. isKTX = true;
  9236. }
  9237. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9238. if (isDDS) {
  9239. BABYLON.Tools.Warn("DDS files deprecated since 3.0, use KTX files");
  9240. }
  9241. if (isKTX) {
  9242. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9243. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  9244. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  9245. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9246. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9247. ktx.uploadLevels(_this._gl, !noMipmap);
  9248. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9249. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9250. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9251. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9252. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9253. _this.resetTextureCache();
  9254. texture._width = ktx.pixelWidth;
  9255. texture._height = ktx.pixelHeight;
  9256. texture.isReady = true;
  9257. }, null, null, true, onError);
  9258. }
  9259. else if (isDDS) {
  9260. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  9261. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9262. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  9263. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9264. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  9265. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  9266. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  9267. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9268. }
  9269. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9270. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  9271. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9272. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9273. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9274. _this.resetTextureCache();
  9275. texture._width = info.width;
  9276. texture._height = info.height;
  9277. texture.isReady = true;
  9278. }, null, null, true, onError);
  9279. }
  9280. else {
  9281. cascadeLoad(rootUrl, scene, function (imgs) {
  9282. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  9283. var height = width;
  9284. _this._prepareWorkingCanvas();
  9285. _this._workingCanvas.width = width;
  9286. _this._workingCanvas.height = height;
  9287. var faces = [
  9288. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9289. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9290. ];
  9291. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9292. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9293. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  9294. for (var index = 0; index < faces.length; index++) {
  9295. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  9296. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  9297. }
  9298. if (!noMipmap) {
  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, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_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 = width;
  9308. texture._height = height;
  9309. texture.isReady = true;
  9310. texture.onLoadedCallbacks.forEach(function (callback) {
  9311. callback();
  9312. });
  9313. if (onLoad) {
  9314. onLoad();
  9315. }
  9316. }, files, onError);
  9317. }
  9318. this._loadedTexturesCache.push(texture);
  9319. return texture;
  9320. };
  9321. Engine.prototype.updateTextureSize = function (texture, width, height) {
  9322. texture._width = width;
  9323. texture._height = height;
  9324. texture._size = width * height;
  9325. texture._baseWidth = width;
  9326. texture._baseHeight = height;
  9327. };
  9328. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  9329. var _this = this;
  9330. if (onLoad === void 0) { onLoad = null; }
  9331. if (onError === void 0) { onError = null; }
  9332. var gl = this._gl;
  9333. var texture = gl.createTexture();
  9334. scene._addPendingData(texture);
  9335. texture.isCube = true;
  9336. texture.references = 1;
  9337. texture.url = url;
  9338. var textureType = gl.UNSIGNED_BYTE;
  9339. if (type === Engine.TEXTURETYPE_FLOAT) {
  9340. textureType = gl.FLOAT;
  9341. }
  9342. var internalFormat = this._getInternalFormat(format);
  9343. var needConversion = false;
  9344. if (internalFormat === gl.RGB) {
  9345. internalFormat = gl.RGBA;
  9346. needConversion = true;
  9347. }
  9348. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  9349. var width = size;
  9350. var height = width;
  9351. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9352. texture._width = width;
  9353. texture._height = height;
  9354. var onerror = function () {
  9355. scene._removePendingData(texture);
  9356. if (onError) {
  9357. onError();
  9358. }
  9359. };
  9360. var internalCallback = function (data) {
  9361. var rgbeDataArrays = callback(data);
  9362. var facesIndex = [
  9363. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  9364. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  9365. ];
  9366. width = texture._width;
  9367. height = texture._height;
  9368. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  9369. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  9370. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  9371. if (mipmmapGenerator) {
  9372. var arrayTemp = [];
  9373. // Data are known to be in +X +Y +Z -X -Y -Z
  9374. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  9375. arrayTemp.push(rgbeDataArrays[0]); // +X
  9376. arrayTemp.push(rgbeDataArrays[3]); // -X
  9377. arrayTemp.push(rgbeDataArrays[1]); // +Y
  9378. arrayTemp.push(rgbeDataArrays[4]); // -Y
  9379. arrayTemp.push(rgbeDataArrays[2]); // +Z
  9380. arrayTemp.push(rgbeDataArrays[5]); // -Z
  9381. var mipData = mipmmapGenerator(arrayTemp);
  9382. // mipData is order in +X -X +Y -Y +Z -Z
  9383. var mipFaces = [0, 2, 4, 1, 3, 5];
  9384. for (var level = 0; level < mipData.length; level++) {
  9385. var mipSize = width >> level;
  9386. for (var mipIndex in mipFaces) {
  9387. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  9388. if (needConversion) {
  9389. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  9390. }
  9391. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  9392. }
  9393. }
  9394. }
  9395. else {
  9396. // Data are known to be in +X +Y +Z -X -Y -Z
  9397. for (var index = 0; index < facesIndex.length; index++) {
  9398. var faceData = rgbeDataArrays[index];
  9399. if (needConversion) {
  9400. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  9401. }
  9402. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  9403. }
  9404. if (!noMipmap && isPot) {
  9405. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9406. }
  9407. else {
  9408. noMipmap = true;
  9409. }
  9410. }
  9411. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  9412. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9413. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9414. }
  9415. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  9416. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9417. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9418. }
  9419. else {
  9420. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9421. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  9422. }
  9423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9424. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9425. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9426. texture.isReady = true;
  9427. _this.resetTextureCache();
  9428. scene._removePendingData(texture);
  9429. if (onLoad) {
  9430. onLoad();
  9431. }
  9432. };
  9433. BABYLON.Tools.LoadFile(url, function (data) {
  9434. internalCallback(data);
  9435. }, onerror, scene.database, true);
  9436. return texture;
  9437. };
  9438. ;
  9439. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  9440. // Create new RGBA data container.
  9441. var rgbaData;
  9442. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  9443. rgbaData = new Float32Array(width * height * 4);
  9444. }
  9445. else {
  9446. rgbaData = new Uint32Array(width * height * 4);
  9447. }
  9448. // Convert each pixel.
  9449. for (var x = 0; x < width; x++) {
  9450. for (var y = 0; y < height; y++) {
  9451. var index = (y * width + x) * 3;
  9452. var newIndex = (y * width + x) * 4;
  9453. // Map Old Value to new value.
  9454. rgbaData[newIndex + 0] = rgbData[index + 0];
  9455. rgbaData[newIndex + 1] = rgbData[index + 1];
  9456. rgbaData[newIndex + 2] = rgbData[index + 2];
  9457. // Add fully opaque alpha channel.
  9458. rgbaData[newIndex + 3] = 1;
  9459. }
  9460. }
  9461. return rgbaData;
  9462. };
  9463. Engine.prototype._releaseTexture = function (texture) {
  9464. var gl = this._gl;
  9465. if (texture._framebuffer) {
  9466. gl.deleteFramebuffer(texture._framebuffer);
  9467. }
  9468. if (texture._depthStencilBuffer) {
  9469. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  9470. }
  9471. if (texture._MSAAFramebuffer) {
  9472. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  9473. }
  9474. if (texture._MSAARenderBuffer) {
  9475. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  9476. }
  9477. gl.deleteTexture(texture);
  9478. // Unbind channels
  9479. this.unbindAllTextures();
  9480. var index = this._loadedTexturesCache.indexOf(texture);
  9481. if (index !== -1) {
  9482. this._loadedTexturesCache.splice(index, 1);
  9483. }
  9484. };
  9485. Engine.prototype.setProgram = function (program) {
  9486. if (this._currentProgram !== program) {
  9487. this._gl.useProgram(program);
  9488. this._currentProgram = program;
  9489. }
  9490. };
  9491. Engine.prototype.bindSamplers = function (effect) {
  9492. this.setProgram(effect.getProgram());
  9493. var samplers = effect.getSamplers();
  9494. for (var index = 0; index < samplers.length; index++) {
  9495. var uniform = effect.getUniform(samplers[index]);
  9496. this._gl.uniform1i(uniform, index);
  9497. }
  9498. this._currentEffect = null;
  9499. };
  9500. Engine.prototype.activateTexture = function (texture) {
  9501. if (this._activeTexture !== texture) {
  9502. this._gl.activeTexture(texture);
  9503. this._activeTexture = texture;
  9504. }
  9505. };
  9506. Engine.prototype._bindTextureDirectly = function (target, texture) {
  9507. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  9508. this._gl.bindTexture(target, texture);
  9509. this._activeTexturesCache[this._activeTexture] = texture;
  9510. }
  9511. };
  9512. Engine.prototype._bindTexture = function (channel, texture) {
  9513. if (channel < 0) {
  9514. return;
  9515. }
  9516. this.activateTexture(this._gl.TEXTURE0 + channel);
  9517. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9518. };
  9519. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  9520. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  9521. };
  9522. Engine.prototype.unbindAllTextures = function () {
  9523. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  9524. this.activateTexture(this._gl["TEXTURE" + channel]);
  9525. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9526. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9527. }
  9528. };
  9529. Engine.prototype.setTexture = function (channel, uniform, texture) {
  9530. if (channel < 0) {
  9531. return;
  9532. }
  9533. this._gl.uniform1i(uniform, channel);
  9534. this._setTexture(channel, texture);
  9535. };
  9536. Engine.prototype._setTexture = function (channel, texture) {
  9537. // Not ready?
  9538. if (!texture || !texture.isReady()) {
  9539. if (this._activeTexturesCache[channel] != null) {
  9540. this.activateTexture(this._gl["TEXTURE" + channel]);
  9541. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9542. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9543. }
  9544. return;
  9545. }
  9546. // Video
  9547. var alreadyActivated = false;
  9548. if (texture.video) {
  9549. this.activateTexture(this._gl["TEXTURE" + channel]);
  9550. alreadyActivated = true;
  9551. texture.update();
  9552. }
  9553. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  9554. texture.delayLoad();
  9555. return;
  9556. }
  9557. var internalTexture = texture.getInternalTexture();
  9558. if (this._activeTexturesCache[channel] === internalTexture) {
  9559. return;
  9560. }
  9561. if (!alreadyActivated) {
  9562. this.activateTexture(this._gl["TEXTURE" + channel]);
  9563. }
  9564. if (internalTexture.isCube) {
  9565. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  9566. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  9567. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  9568. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  9569. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  9570. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  9571. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  9572. }
  9573. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  9574. }
  9575. else {
  9576. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  9577. if (internalTexture._cachedWrapU !== texture.wrapU) {
  9578. internalTexture._cachedWrapU = texture.wrapU;
  9579. switch (texture.wrapU) {
  9580. case BABYLON.Texture.WRAP_ADDRESSMODE:
  9581. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  9582. break;
  9583. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  9584. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  9585. break;
  9586. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  9587. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  9588. break;
  9589. }
  9590. }
  9591. if (internalTexture._cachedWrapV !== texture.wrapV) {
  9592. internalTexture._cachedWrapV = texture.wrapV;
  9593. switch (texture.wrapV) {
  9594. case BABYLON.Texture.WRAP_ADDRESSMODE:
  9595. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  9596. break;
  9597. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  9598. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  9599. break;
  9600. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  9601. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  9602. break;
  9603. }
  9604. }
  9605. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  9606. }
  9607. };
  9608. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  9609. if (channel < 0) {
  9610. return;
  9611. }
  9612. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  9613. this._textureUnits = new Int32Array(textures.length);
  9614. }
  9615. for (var i = 0; i < textures.length; i++) {
  9616. this._textureUnits[i] = channel + i;
  9617. }
  9618. this._gl.uniform1iv(uniform, this._textureUnits);
  9619. for (var index = 0; index < textures.length; index++) {
  9620. this._setTexture(channel + index, textures[index]);
  9621. }
  9622. };
  9623. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  9624. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  9625. var value = texture.anisotropicFilteringLevel;
  9626. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  9627. value = 1;
  9628. }
  9629. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  9630. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  9631. texture._cachedAnisotropicFilteringLevel = value;
  9632. }
  9633. };
  9634. Engine.prototype.readPixels = function (x, y, width, height) {
  9635. var data = new Uint8Array(height * width * 4);
  9636. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  9637. return data;
  9638. };
  9639. /**
  9640. * Add an externaly attached data from its key.
  9641. * This method call will fail and return false, if such key already exists.
  9642. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  9643. * @param key the unique key that identifies the data
  9644. * @param data the data object to associate to the key for this Engine instance
  9645. * @return true if no such key were already present and the data was added successfully, false otherwise
  9646. */
  9647. Engine.prototype.addExternalData = function (key, data) {
  9648. if (!this._externalData) {
  9649. this._externalData = new BABYLON.StringDictionary();
  9650. }
  9651. return this._externalData.add(key, data);
  9652. };
  9653. /**
  9654. * Get an externaly attached data from its key
  9655. * @param key the unique key that identifies the data
  9656. * @return the associated data, if present (can be null), or undefined if not present
  9657. */
  9658. Engine.prototype.getExternalData = function (key) {
  9659. if (!this._externalData) {
  9660. this._externalData = new BABYLON.StringDictionary();
  9661. }
  9662. return this._externalData.get(key);
  9663. };
  9664. /**
  9665. * Get an externaly attached data from its key, create it using a factory if it's not already present
  9666. * @param key the unique key that identifies the data
  9667. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  9668. * @return the associated data, can be null if the factory returned null.
  9669. */
  9670. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  9671. if (!this._externalData) {
  9672. this._externalData = new BABYLON.StringDictionary();
  9673. }
  9674. return this._externalData.getOrAddWithFactory(key, factory);
  9675. };
  9676. /**
  9677. * Remove an externaly attached data from the Engine instance
  9678. * @param key the unique key that identifies the data
  9679. * @return true if the data was successfully removed, false if it doesn't exist
  9680. */
  9681. Engine.prototype.removeExternalData = function (key) {
  9682. if (!this._externalData) {
  9683. this._externalData = new BABYLON.StringDictionary();
  9684. }
  9685. return this._externalData.remove(key);
  9686. };
  9687. Engine.prototype.releaseInternalTexture = function (texture) {
  9688. if (!texture) {
  9689. return;
  9690. }
  9691. texture.references--;
  9692. // Final reference ?
  9693. if (texture.references === 0) {
  9694. var texturesCache = this.getLoadedTexturesCache();
  9695. var index = texturesCache.indexOf(texture);
  9696. if (index > -1) {
  9697. texturesCache.splice(index, 1);
  9698. }
  9699. this._releaseTexture(texture);
  9700. }
  9701. };
  9702. Engine.prototype.unbindAllAttributes = function () {
  9703. if (this._mustWipeVertexAttributes) {
  9704. this._mustWipeVertexAttributes = false;
  9705. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9706. this._gl.disableVertexAttribArray(i);
  9707. this._vertexAttribArraysEnabled[i] = false;
  9708. this._currentBufferPointers[i] = null;
  9709. }
  9710. return;
  9711. }
  9712. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  9713. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  9714. continue;
  9715. }
  9716. this._gl.disableVertexAttribArray(i);
  9717. this._vertexAttribArraysEnabled[i] = false;
  9718. this._currentBufferPointers[i] = null;
  9719. }
  9720. };
  9721. Engine.prototype.releaseEffects = function () {
  9722. for (var name in this._compiledEffects) {
  9723. this._gl.deleteProgram(this._compiledEffects[name]._program);
  9724. }
  9725. this._compiledEffects = {};
  9726. };
  9727. // Dispose
  9728. Engine.prototype.dispose = function () {
  9729. this.hideLoadingUI();
  9730. this.stopRenderLoop();
  9731. // Release scenes
  9732. while (this.scenes.length) {
  9733. this.scenes[0].dispose();
  9734. }
  9735. // Release audio engine
  9736. Engine.audioEngine.dispose();
  9737. // Release effects
  9738. this.releaseEffects();
  9739. // Unbind
  9740. this.unbindAllAttributes();
  9741. this._gl = null;
  9742. //WebVR
  9743. this.disableVR();
  9744. // Events
  9745. window.removeEventListener("blur", this._onBlur);
  9746. window.removeEventListener("focus", this._onFocus);
  9747. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  9748. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  9749. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  9750. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  9751. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  9752. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  9753. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  9754. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  9755. // Remove from Instances
  9756. var index = Engine.Instances.indexOf(this);
  9757. if (index >= 0) {
  9758. Engine.Instances.splice(index, 1);
  9759. }
  9760. };
  9761. // Loading screen
  9762. Engine.prototype.displayLoadingUI = function () {
  9763. this.loadingScreen.displayLoadingUI();
  9764. };
  9765. Engine.prototype.hideLoadingUI = function () {
  9766. this.loadingScreen.hideLoadingUI();
  9767. };
  9768. Object.defineProperty(Engine.prototype, "loadingScreen", {
  9769. get: function () {
  9770. if (!this._loadingScreen)
  9771. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  9772. return this._loadingScreen;
  9773. },
  9774. set: function (loadingScreen) {
  9775. this._loadingScreen = loadingScreen;
  9776. },
  9777. enumerable: true,
  9778. configurable: true
  9779. });
  9780. Object.defineProperty(Engine.prototype, "loadingUIText", {
  9781. set: function (text) {
  9782. this.loadingScreen.loadingUIText = text;
  9783. },
  9784. enumerable: true,
  9785. configurable: true
  9786. });
  9787. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  9788. set: function (color) {
  9789. this.loadingScreen.loadingUIBackgroundColor = color;
  9790. },
  9791. enumerable: true,
  9792. configurable: true
  9793. });
  9794. Engine.prototype.attachContextLostEvent = function (callback) {
  9795. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  9796. };
  9797. Engine.prototype.attachContextRestoredEvent = function (callback) {
  9798. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  9799. };
  9800. Engine.prototype.getVertexShaderSource = function (program) {
  9801. var shaders = this._gl.getAttachedShaders(program);
  9802. return this._gl.getShaderSource(shaders[0]);
  9803. };
  9804. Engine.prototype.getFragmentShaderSource = function (program) {
  9805. var shaders = this._gl.getAttachedShaders(program);
  9806. return this._gl.getShaderSource(shaders[1]);
  9807. };
  9808. // FPS
  9809. Engine.prototype.getFps = function () {
  9810. return this.fps;
  9811. };
  9812. Engine.prototype.getDeltaTime = function () {
  9813. return this.deltaTime;
  9814. };
  9815. Engine.prototype._measureFps = function () {
  9816. this.previousFramesDuration.push(BABYLON.Tools.Now);
  9817. var length = this.previousFramesDuration.length;
  9818. if (length >= 2) {
  9819. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  9820. }
  9821. if (length >= this.fpsRange) {
  9822. if (length > this.fpsRange) {
  9823. this.previousFramesDuration.splice(0, 1);
  9824. length = this.previousFramesDuration.length;
  9825. }
  9826. var sum = 0;
  9827. for (var id = 0; id < length - 1; id++) {
  9828. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  9829. }
  9830. this.fps = 1000.0 / (sum / (length - 1));
  9831. }
  9832. };
  9833. Engine.prototype._canRenderToFloatFramebuffer = function () {
  9834. if (this._webGLVersion > 1) {
  9835. return this._caps.colorBufferFloat;
  9836. }
  9837. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  9838. };
  9839. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  9840. if (this._webGLVersion > 1) {
  9841. return this._caps.colorBufferFloat;
  9842. }
  9843. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  9844. };
  9845. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9846. Engine.prototype._canRenderToFramebuffer = function (type) {
  9847. var gl = this._gl;
  9848. //clear existing errors
  9849. while (gl.getError() !== gl.NO_ERROR) { }
  9850. var successful = true;
  9851. var texture = gl.createTexture();
  9852. gl.bindTexture(gl.TEXTURE_2D, texture);
  9853. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9856. var fb = gl.createFramebuffer();
  9857. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9858. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9859. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9860. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  9861. successful = successful && (gl.getError() === gl.NO_ERROR);
  9862. //try render by clearing frame buffer's color buffer
  9863. if (successful) {
  9864. gl.clear(gl.COLOR_BUFFER_BIT);
  9865. successful = successful && (gl.getError() === gl.NO_ERROR);
  9866. }
  9867. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  9868. if (successful) {
  9869. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  9870. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9871. var readFormat = gl.RGBA;
  9872. var readType = gl.UNSIGNED_BYTE;
  9873. var buffer = new Uint8Array(4);
  9874. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  9875. successful = successful && (gl.getError() === gl.NO_ERROR);
  9876. }
  9877. //clean up
  9878. gl.deleteTexture(texture);
  9879. gl.deleteFramebuffer(fb);
  9880. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9881. //clear accumulated errors
  9882. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  9883. return successful;
  9884. };
  9885. Engine.prototype._getWebGLTextureType = function (type) {
  9886. if (type === Engine.TEXTURETYPE_FLOAT) {
  9887. return this._gl.FLOAT;
  9888. }
  9889. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9890. // Add Half Float Constant.
  9891. return Engine.HALF_FLOAT_OES;
  9892. }
  9893. return this._gl.UNSIGNED_BYTE;
  9894. };
  9895. ;
  9896. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  9897. if (this._webGLVersion === 1) {
  9898. return this._gl.RGBA;
  9899. }
  9900. if (type === Engine.TEXTURETYPE_FLOAT) {
  9901. return Engine.RGBA32F;
  9902. }
  9903. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9904. return Engine.RGBA16F;
  9905. }
  9906. return this._gl.RGBA;
  9907. };
  9908. ;
  9909. // Statics
  9910. Engine.isSupported = function () {
  9911. try {
  9912. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  9913. if (navigator.isCocoonJS) {
  9914. return true;
  9915. }
  9916. var tempcanvas = document.createElement("canvas");
  9917. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  9918. return gl != null && !!window.WebGLRenderingContext;
  9919. }
  9920. catch (e) {
  9921. return false;
  9922. }
  9923. };
  9924. return Engine;
  9925. }());
  9926. Engine.Instances = new Array();
  9927. // Const statics
  9928. Engine._ALPHA_DISABLE = 0;
  9929. Engine._ALPHA_ADD = 1;
  9930. Engine._ALPHA_COMBINE = 2;
  9931. Engine._ALPHA_SUBTRACT = 3;
  9932. Engine._ALPHA_MULTIPLY = 4;
  9933. Engine._ALPHA_MAXIMIZED = 5;
  9934. Engine._ALPHA_ONEONE = 6;
  9935. Engine._ALPHA_PREMULTIPLIED = 7;
  9936. Engine._DELAYLOADSTATE_NONE = 0;
  9937. Engine._DELAYLOADSTATE_LOADED = 1;
  9938. Engine._DELAYLOADSTATE_LOADING = 2;
  9939. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9940. Engine._TEXTUREFORMAT_ALPHA = 0;
  9941. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9942. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9943. Engine._TEXTUREFORMAT_RGB = 4;
  9944. Engine._TEXTUREFORMAT_RGBA = 5;
  9945. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9946. Engine._TEXTURETYPE_FLOAT = 1;
  9947. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9948. // Depht or Stencil test Constants.
  9949. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9950. 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.
  9951. 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.
  9952. 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.
  9953. 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.
  9954. 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.
  9955. 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.
  9956. 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.
  9957. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9958. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9959. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9960. // Stencil Actions Constants.
  9961. Engine._KEEP = 0x1E00;
  9962. Engine._REPLACE = 0x1E01;
  9963. Engine._INCR = 0x1E02;
  9964. Engine._DECR = 0x1E03;
  9965. Engine._INVERT = 0x150A;
  9966. Engine._INCR_WRAP = 0x8507;
  9967. Engine._DECR_WRAP = 0x8508;
  9968. // Updatable statics so stick with vars here
  9969. Engine.CollisionsEpsilon = 0.001;
  9970. Engine.CodeRepository = "src/";
  9971. Engine.ShadersRepository = "src/Shaders/";
  9972. BABYLON.Engine = Engine;
  9973. })(BABYLON || (BABYLON = {}));
  9974. //# sourceMappingURL=babylon.engine.js.map
  9975. /// <reference path="Tools\babylon.decorators.ts" />
  9976. var BABYLON;
  9977. (function (BABYLON) {
  9978. /**
  9979. * Node is the basic class for all scene objects (Mesh, Light Camera).
  9980. */
  9981. var Node = (function () {
  9982. /**
  9983. * @constructor
  9984. * @param {string} name - the name and id to be given to this node
  9985. * @param {BABYLON.Scene} the scene this node will be added to
  9986. */
  9987. function Node(name, scene) {
  9988. this.state = "";
  9989. this.metadata = null;
  9990. this.doNotSerialize = false;
  9991. this.animations = new Array();
  9992. this._ranges = {};
  9993. this._childrenFlag = -1;
  9994. this._isEnabled = true;
  9995. this._isReady = true;
  9996. this._currentRenderId = -1;
  9997. this._parentRenderId = -1;
  9998. /**
  9999. * An event triggered when the mesh is disposed.
  10000. * @type {BABYLON.Observable}
  10001. */
  10002. this.onDisposeObservable = new BABYLON.Observable();
  10003. this.name = name;
  10004. this.id = name;
  10005. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  10006. this._initCache();
  10007. }
  10008. Object.defineProperty(Node.prototype, "parent", {
  10009. get: function () {
  10010. return this._parentNode;
  10011. },
  10012. set: function (parent) {
  10013. if (this._parentNode === parent) {
  10014. return;
  10015. }
  10016. if (this._parentNode) {
  10017. var index = this._parentNode._children.indexOf(this);
  10018. if (index !== -1) {
  10019. this._parentNode._children.splice(index, 1);
  10020. }
  10021. }
  10022. this._parentNode = parent;
  10023. if (this._parentNode) {
  10024. if (!this._parentNode._children) {
  10025. this._parentNode._children = new Array();
  10026. }
  10027. this._parentNode._children.push(this);
  10028. }
  10029. },
  10030. enumerable: true,
  10031. configurable: true
  10032. });
  10033. Node.prototype.getClassName = function () {
  10034. return "Node";
  10035. };
  10036. Object.defineProperty(Node.prototype, "onDispose", {
  10037. set: function (callback) {
  10038. if (this._onDisposeObserver) {
  10039. this.onDisposeObservable.remove(this._onDisposeObserver);
  10040. }
  10041. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10042. },
  10043. enumerable: true,
  10044. configurable: true
  10045. });
  10046. Node.prototype.getScene = function () {
  10047. return this._scene;
  10048. };
  10049. Node.prototype.getEngine = function () {
  10050. return this._scene.getEngine();
  10051. };
  10052. // override it in derived class
  10053. Node.prototype.getWorldMatrix = function () {
  10054. return BABYLON.Matrix.Identity();
  10055. };
  10056. // override it in derived class if you add new variables to the cache
  10057. // and call the parent class method
  10058. Node.prototype._initCache = function () {
  10059. this._cache = {};
  10060. this._cache.parent = undefined;
  10061. };
  10062. Node.prototype.updateCache = function (force) {
  10063. if (!force && this.isSynchronized())
  10064. return;
  10065. this._cache.parent = this.parent;
  10066. this._updateCache();
  10067. };
  10068. // override it in derived class if you add new variables to the cache
  10069. // and call the parent class method if !ignoreParentClass
  10070. Node.prototype._updateCache = function (ignoreParentClass) {
  10071. };
  10072. // override it in derived class if you add new variables to the cache
  10073. Node.prototype._isSynchronized = function () {
  10074. return true;
  10075. };
  10076. Node.prototype._markSyncedWithParent = function () {
  10077. this._parentRenderId = this.parent._currentRenderId;
  10078. };
  10079. Node.prototype.isSynchronizedWithParent = function () {
  10080. if (!this.parent) {
  10081. return true;
  10082. }
  10083. if (this._parentRenderId !== this.parent._currentRenderId) {
  10084. return false;
  10085. }
  10086. return this.parent.isSynchronized();
  10087. };
  10088. Node.prototype.isSynchronized = function (updateCache) {
  10089. var check = this.hasNewParent();
  10090. check = check || !this.isSynchronizedWithParent();
  10091. check = check || !this._isSynchronized();
  10092. if (updateCache)
  10093. this.updateCache(true);
  10094. return !check;
  10095. };
  10096. Node.prototype.hasNewParent = function (update) {
  10097. if (this._cache.parent === this.parent)
  10098. return false;
  10099. if (update)
  10100. this._cache.parent = this.parent;
  10101. return true;
  10102. };
  10103. /**
  10104. * Is this node ready to be used/rendered
  10105. * @return {boolean} is it ready
  10106. */
  10107. Node.prototype.isReady = function () {
  10108. return this._isReady;
  10109. };
  10110. /**
  10111. * Is this node enabled.
  10112. * If the node has a parent and is enabled, the parent will be inspected as well.
  10113. * @return {boolean} whether this node (and its parent) is enabled.
  10114. * @see setEnabled
  10115. */
  10116. Node.prototype.isEnabled = function () {
  10117. if (!this._isEnabled) {
  10118. return false;
  10119. }
  10120. if (this.parent) {
  10121. return this.parent.isEnabled();
  10122. }
  10123. return true;
  10124. };
  10125. /**
  10126. * Set the enabled state of this node.
  10127. * @param {boolean} value - the new enabled state
  10128. * @see isEnabled
  10129. */
  10130. Node.prototype.setEnabled = function (value) {
  10131. this._isEnabled = value;
  10132. };
  10133. /**
  10134. * Is this node a descendant of the given node.
  10135. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  10136. * @param {BABYLON.Node} ancestor - The parent node to inspect
  10137. * @see parent
  10138. */
  10139. Node.prototype.isDescendantOf = function (ancestor) {
  10140. if (this.parent) {
  10141. if (this.parent === ancestor) {
  10142. return true;
  10143. }
  10144. return this.parent.isDescendantOf(ancestor);
  10145. }
  10146. return false;
  10147. };
  10148. /**
  10149. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  10150. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  10151. * @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.
  10152. * @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.
  10153. */
  10154. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  10155. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  10156. if (!this._children) {
  10157. return;
  10158. }
  10159. for (var index = 0; index < this._children.length; index++) {
  10160. var item = this._children[index];
  10161. if (!predicate || predicate(item)) {
  10162. results.push(item);
  10163. }
  10164. if (!directDescendantsOnly) {
  10165. item._getDescendants(results, false, predicate);
  10166. }
  10167. }
  10168. };
  10169. /**
  10170. * Will return all nodes that have this node as ascendant.
  10171. * @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.
  10172. * @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.
  10173. * @return {BABYLON.Node[]} all children nodes of all types.
  10174. */
  10175. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  10176. var results = [];
  10177. this._getDescendants(results, directDescendantsOnly, predicate);
  10178. return results;
  10179. };
  10180. /**
  10181. * Get all child-meshes of this node.
  10182. */
  10183. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  10184. var results = [];
  10185. this._getDescendants(results, directDecendantsOnly, function (node) {
  10186. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  10187. });
  10188. return results;
  10189. };
  10190. /**
  10191. * Get all direct children of this node.
  10192. */
  10193. Node.prototype.getChildren = function (predicate) {
  10194. return this.getDescendants(true, predicate);
  10195. };
  10196. Node.prototype._setReady = function (state) {
  10197. if (state === this._isReady) {
  10198. return;
  10199. }
  10200. if (!state) {
  10201. this._isReady = false;
  10202. return;
  10203. }
  10204. this._isReady = true;
  10205. if (this.onReady) {
  10206. this.onReady(this);
  10207. }
  10208. };
  10209. Node.prototype.getAnimationByName = function (name) {
  10210. for (var i = 0; i < this.animations.length; i++) {
  10211. var animation = this.animations[i];
  10212. if (animation.name === name) {
  10213. return animation;
  10214. }
  10215. }
  10216. return null;
  10217. };
  10218. Node.prototype.createAnimationRange = function (name, from, to) {
  10219. // check name not already in use
  10220. if (!this._ranges[name]) {
  10221. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  10222. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10223. if (this.animations[i]) {
  10224. this.animations[i].createRange(name, from, to);
  10225. }
  10226. }
  10227. }
  10228. };
  10229. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  10230. if (deleteFrames === void 0) { deleteFrames = true; }
  10231. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  10232. if (this.animations[i]) {
  10233. this.animations[i].deleteRange(name, deleteFrames);
  10234. }
  10235. }
  10236. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  10237. };
  10238. Node.prototype.getAnimationRange = function (name) {
  10239. return this._ranges[name];
  10240. };
  10241. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  10242. var range = this.getAnimationRange(name);
  10243. if (!range) {
  10244. return null;
  10245. }
  10246. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  10247. };
  10248. Node.prototype.serializeAnimationRanges = function () {
  10249. var serializationRanges = [];
  10250. for (var name in this._ranges) {
  10251. var range = {};
  10252. range.name = name;
  10253. range.from = this._ranges[name].from;
  10254. range.to = this._ranges[name].to;
  10255. serializationRanges.push(range);
  10256. }
  10257. return serializationRanges;
  10258. };
  10259. Node.prototype.dispose = function () {
  10260. this.parent = null;
  10261. // Callback
  10262. this.onDisposeObservable.notifyObservers(this);
  10263. this.onDisposeObservable.clear();
  10264. };
  10265. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  10266. if (parsedNode.ranges) {
  10267. for (var index = 0; index < parsedNode.ranges.length; index++) {
  10268. var data = parsedNode.ranges[index];
  10269. node.createAnimationRange(data.name, data.from, data.to);
  10270. }
  10271. }
  10272. };
  10273. return Node;
  10274. }());
  10275. __decorate([
  10276. BABYLON.serialize()
  10277. ], Node.prototype, "name", void 0);
  10278. __decorate([
  10279. BABYLON.serialize()
  10280. ], Node.prototype, "id", void 0);
  10281. __decorate([
  10282. BABYLON.serialize()
  10283. ], Node.prototype, "uniqueId", void 0);
  10284. __decorate([
  10285. BABYLON.serialize()
  10286. ], Node.prototype, "state", void 0);
  10287. __decorate([
  10288. BABYLON.serialize()
  10289. ], Node.prototype, "metadata", void 0);
  10290. BABYLON.Node = Node;
  10291. })(BABYLON || (BABYLON = {}));
  10292. //# sourceMappingURL=babylon.node.js.map
  10293. var BABYLON;
  10294. (function (BABYLON) {
  10295. var BoundingSphere = (function () {
  10296. function BoundingSphere(minimum, maximum) {
  10297. this.minimum = minimum;
  10298. this.maximum = maximum;
  10299. this._tempRadiusVector = BABYLON.Vector3.Zero();
  10300. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  10301. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  10302. this.radius = distance * 0.5;
  10303. this.centerWorld = BABYLON.Vector3.Zero();
  10304. this._update(BABYLON.Matrix.Identity());
  10305. }
  10306. // Methods
  10307. BoundingSphere.prototype._update = function (world) {
  10308. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  10309. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  10310. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  10311. };
  10312. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  10313. for (var i = 0; i < 6; i++) {
  10314. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  10315. return false;
  10316. }
  10317. return true;
  10318. };
  10319. BoundingSphere.prototype.intersectsPoint = function (point) {
  10320. var x = this.centerWorld.x - point.x;
  10321. var y = this.centerWorld.y - point.y;
  10322. var z = this.centerWorld.z - point.z;
  10323. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10324. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  10325. return false;
  10326. return true;
  10327. };
  10328. // Statics
  10329. BoundingSphere.Intersects = function (sphere0, sphere1) {
  10330. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  10331. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  10332. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  10333. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  10334. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  10335. return false;
  10336. return true;
  10337. };
  10338. return BoundingSphere;
  10339. }());
  10340. BABYLON.BoundingSphere = BoundingSphere;
  10341. })(BABYLON || (BABYLON = {}));
  10342. //# sourceMappingURL=babylon.boundingSphere.js.map
  10343. var BABYLON;
  10344. (function (BABYLON) {
  10345. var BoundingBox = (function () {
  10346. function BoundingBox(minimum, maximum) {
  10347. this.minimum = minimum;
  10348. this.maximum = maximum;
  10349. this.vectors = new Array();
  10350. this.vectorsWorld = new Array();
  10351. // Bounding vectors
  10352. this.vectors.push(this.minimum.clone());
  10353. this.vectors.push(this.maximum.clone());
  10354. this.vectors.push(this.minimum.clone());
  10355. this.vectors[2].x = this.maximum.x;
  10356. this.vectors.push(this.minimum.clone());
  10357. this.vectors[3].y = this.maximum.y;
  10358. this.vectors.push(this.minimum.clone());
  10359. this.vectors[4].z = this.maximum.z;
  10360. this.vectors.push(this.maximum.clone());
  10361. this.vectors[5].z = this.minimum.z;
  10362. this.vectors.push(this.maximum.clone());
  10363. this.vectors[6].x = this.minimum.x;
  10364. this.vectors.push(this.maximum.clone());
  10365. this.vectors[7].y = this.minimum.y;
  10366. // OBB
  10367. this.center = this.maximum.add(this.minimum).scale(0.5);
  10368. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  10369. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  10370. // World
  10371. for (var index = 0; index < this.vectors.length; index++) {
  10372. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  10373. }
  10374. this.minimumWorld = BABYLON.Vector3.Zero();
  10375. this.maximumWorld = BABYLON.Vector3.Zero();
  10376. this.centerWorld = BABYLON.Vector3.Zero();
  10377. this.extendSizeWorld = BABYLON.Vector3.Zero();
  10378. this._update(BABYLON.Matrix.Identity());
  10379. }
  10380. // Methods
  10381. BoundingBox.prototype.getWorldMatrix = function () {
  10382. return this._worldMatrix;
  10383. };
  10384. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  10385. this._worldMatrix.copyFrom(matrix);
  10386. return this;
  10387. };
  10388. BoundingBox.prototype._update = function (world) {
  10389. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  10390. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  10391. for (var index = 0; index < this.vectors.length; index++) {
  10392. var v = this.vectorsWorld[index];
  10393. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  10394. if (v.x < this.minimumWorld.x)
  10395. this.minimumWorld.x = v.x;
  10396. if (v.y < this.minimumWorld.y)
  10397. this.minimumWorld.y = v.y;
  10398. if (v.z < this.minimumWorld.z)
  10399. this.minimumWorld.z = v.z;
  10400. if (v.x > this.maximumWorld.x)
  10401. this.maximumWorld.x = v.x;
  10402. if (v.y > this.maximumWorld.y)
  10403. this.maximumWorld.y = v.y;
  10404. if (v.z > this.maximumWorld.z)
  10405. this.maximumWorld.z = v.z;
  10406. }
  10407. // Extend
  10408. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  10409. this.extendSizeWorld.scaleInPlace(0.5);
  10410. // OBB
  10411. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  10412. this.centerWorld.scaleInPlace(0.5);
  10413. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  10414. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  10415. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  10416. this._worldMatrix = world;
  10417. };
  10418. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  10419. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  10420. };
  10421. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10422. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  10423. };
  10424. BoundingBox.prototype.intersectsPoint = function (point) {
  10425. var delta = -BABYLON.Epsilon;
  10426. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  10427. return false;
  10428. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  10429. return false;
  10430. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  10431. return false;
  10432. return true;
  10433. };
  10434. BoundingBox.prototype.intersectsSphere = function (sphere) {
  10435. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  10436. };
  10437. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  10438. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  10439. return false;
  10440. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  10441. return false;
  10442. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  10443. return false;
  10444. return true;
  10445. };
  10446. // Statics
  10447. BoundingBox.Intersects = function (box0, box1) {
  10448. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  10449. return false;
  10450. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  10451. return false;
  10452. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  10453. return false;
  10454. return true;
  10455. };
  10456. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  10457. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  10458. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  10459. return (num <= (sphereRadius * sphereRadius));
  10460. };
  10461. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  10462. for (var p = 0; p < 6; p++) {
  10463. for (var i = 0; i < 8; i++) {
  10464. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10465. return false;
  10466. }
  10467. }
  10468. }
  10469. return true;
  10470. };
  10471. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  10472. for (var p = 0; p < 6; p++) {
  10473. var inCount = 8;
  10474. for (var i = 0; i < 8; i++) {
  10475. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  10476. --inCount;
  10477. }
  10478. else {
  10479. break;
  10480. }
  10481. }
  10482. if (inCount === 0)
  10483. return false;
  10484. }
  10485. return true;
  10486. };
  10487. return BoundingBox;
  10488. }());
  10489. BABYLON.BoundingBox = BoundingBox;
  10490. })(BABYLON || (BABYLON = {}));
  10491. //# sourceMappingURL=babylon.boundingBox.js.map
  10492. var BABYLON;
  10493. (function (BABYLON) {
  10494. var computeBoxExtents = function (axis, box) {
  10495. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  10496. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  10497. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  10498. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  10499. var r = r0 + r1 + r2;
  10500. return {
  10501. min: p - r,
  10502. max: p + r
  10503. };
  10504. };
  10505. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  10506. var axisOverlap = function (axis, box0, box1) {
  10507. var result0 = computeBoxExtents(axis, box0);
  10508. var result1 = computeBoxExtents(axis, box1);
  10509. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  10510. };
  10511. var BoundingInfo = (function () {
  10512. function BoundingInfo(minimum, maximum) {
  10513. this.minimum = minimum;
  10514. this.maximum = maximum;
  10515. this._isLocked = false;
  10516. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  10517. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  10518. }
  10519. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  10520. get: function () {
  10521. return this._isLocked;
  10522. },
  10523. set: function (value) {
  10524. this._isLocked = value;
  10525. },
  10526. enumerable: true,
  10527. configurable: true
  10528. });
  10529. // Methods
  10530. BoundingInfo.prototype.update = function (world) {
  10531. if (this._isLocked) {
  10532. return;
  10533. }
  10534. this.boundingBox._update(world);
  10535. this.boundingSphere._update(world);
  10536. };
  10537. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  10538. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  10539. return false;
  10540. return this.boundingBox.isInFrustum(frustumPlanes);
  10541. };
  10542. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10543. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  10544. };
  10545. BoundingInfo.prototype._checkCollision = function (collider) {
  10546. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  10547. };
  10548. BoundingInfo.prototype.intersectsPoint = function (point) {
  10549. if (!this.boundingSphere.centerWorld) {
  10550. return false;
  10551. }
  10552. if (!this.boundingSphere.intersectsPoint(point)) {
  10553. return false;
  10554. }
  10555. if (!this.boundingBox.intersectsPoint(point)) {
  10556. return false;
  10557. }
  10558. return true;
  10559. };
  10560. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  10561. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  10562. return false;
  10563. }
  10564. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  10565. return false;
  10566. }
  10567. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  10568. return false;
  10569. }
  10570. if (!precise) {
  10571. return true;
  10572. }
  10573. var box0 = this.boundingBox;
  10574. var box1 = boundingInfo.boundingBox;
  10575. if (!axisOverlap(box0.directions[0], box0, box1))
  10576. return false;
  10577. if (!axisOverlap(box0.directions[1], box0, box1))
  10578. return false;
  10579. if (!axisOverlap(box0.directions[2], box0, box1))
  10580. return false;
  10581. if (!axisOverlap(box1.directions[0], box0, box1))
  10582. return false;
  10583. if (!axisOverlap(box1.directions[1], box0, box1))
  10584. return false;
  10585. if (!axisOverlap(box1.directions[2], box0, box1))
  10586. return false;
  10587. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  10588. return false;
  10589. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  10590. return false;
  10591. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  10592. return false;
  10593. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  10594. return false;
  10595. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  10596. return false;
  10597. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  10598. return false;
  10599. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  10600. return false;
  10601. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  10602. return false;
  10603. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  10604. return false;
  10605. return true;
  10606. };
  10607. return BoundingInfo;
  10608. }());
  10609. BABYLON.BoundingInfo = BoundingInfo;
  10610. })(BABYLON || (BABYLON = {}));
  10611. //# sourceMappingURL=babylon.boundingInfo.js.map
  10612. var BABYLON;
  10613. (function (BABYLON) {
  10614. var AbstractMesh = (function (_super) {
  10615. __extends(AbstractMesh, _super);
  10616. // Constructor
  10617. function AbstractMesh(name, scene) {
  10618. var _this = _super.call(this, name, scene) || this;
  10619. _this._facetNb = 0; // facet number
  10620. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  10621. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  10622. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  10623. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  10624. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  10625. _this._subDiv = {
  10626. max: 1,
  10627. X: 1,
  10628. Y: 1,
  10629. Z: 1
  10630. };
  10631. // Events
  10632. /**
  10633. * An event triggered when this mesh collides with another one
  10634. * @type {BABYLON.Observable}
  10635. */
  10636. _this.onCollideObservable = new BABYLON.Observable();
  10637. /**
  10638. * An event triggered when the collision's position changes
  10639. * @type {BABYLON.Observable}
  10640. */
  10641. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10642. /**
  10643. * An event triggered after the world matrix is updated
  10644. * @type {BABYLON.Observable}
  10645. */
  10646. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10647. // Properties
  10648. _this.definedFacingForward = true; // orientation for POV movement & rotation
  10649. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10650. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10651. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  10652. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10653. _this.visibility = 1.0;
  10654. _this.alphaIndex = Number.MAX_VALUE;
  10655. _this.infiniteDistance = false;
  10656. _this.isVisible = true;
  10657. _this.isPickable = true;
  10658. _this.showBoundingBox = false;
  10659. _this.showSubMeshesBoundingBox = false;
  10660. _this.isBlocker = false;
  10661. _this.renderingGroupId = 0;
  10662. _this._receiveShadows = false;
  10663. _this.renderOutline = false;
  10664. _this.outlineColor = BABYLON.Color3.Red();
  10665. _this.outlineWidth = 0.02;
  10666. _this.renderOverlay = false;
  10667. _this.overlayColor = BABYLON.Color3.Red();
  10668. _this.overlayAlpha = 0.5;
  10669. _this._hasVertexAlpha = false;
  10670. _this._useVertexColors = true;
  10671. _this._computeBonesUsingShaders = true;
  10672. _this._numBoneInfluencers = 4;
  10673. _this._applyFog = true;
  10674. _this.scalingDeterminant = 1;
  10675. _this.useOctreeForRenderingSelection = true;
  10676. _this.useOctreeForPicking = true;
  10677. _this.useOctreeForCollisions = true;
  10678. _this.layerMask = 0x0FFFFFFF;
  10679. /**
  10680. * True if the mesh must be rendered in any case.
  10681. */
  10682. _this.alwaysSelectAsActiveMesh = false;
  10683. // Collisions
  10684. _this._checkCollisions = false;
  10685. _this._collisionMask = -1;
  10686. _this._collisionGroup = -1;
  10687. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10688. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10689. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10690. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10691. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10692. // Edges
  10693. _this.edgesWidth = 1;
  10694. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10695. // Cache
  10696. _this._localWorld = BABYLON.Matrix.Zero();
  10697. _this._worldMatrix = BABYLON.Matrix.Zero();
  10698. _this._absolutePosition = BABYLON.Vector3.Zero();
  10699. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10700. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10701. _this._isDirty = false;
  10702. _this._pivotMatrix = BABYLON.Matrix.Identity();
  10703. _this._isDisposed = false;
  10704. _this._renderId = 0;
  10705. _this._intersectionsInProgress = new Array();
  10706. _this._isWorldMatrixFrozen = false;
  10707. _this._unIndexed = false;
  10708. _this._lightSources = new Array();
  10709. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10710. if (collidedMesh === void 0) { collidedMesh = null; }
  10711. //TODO move this to the collision coordinator!
  10712. if (_this.getScene().workerCollisions)
  10713. newPosition.multiplyInPlace(_this._collider.radius);
  10714. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10715. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10716. _this.position.addInPlace(_this._diffPositionForCollisions);
  10717. }
  10718. if (collidedMesh) {
  10719. _this.onCollideObservable.notifyObservers(collidedMesh);
  10720. }
  10721. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10722. };
  10723. _this.getScene().addMesh(_this);
  10724. _this._resyncLightSources();
  10725. return _this;
  10726. }
  10727. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10728. get: function () {
  10729. return AbstractMesh._BILLBOARDMODE_NONE;
  10730. },
  10731. enumerable: true,
  10732. configurable: true
  10733. });
  10734. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10735. get: function () {
  10736. return AbstractMesh._BILLBOARDMODE_X;
  10737. },
  10738. enumerable: true,
  10739. configurable: true
  10740. });
  10741. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10742. get: function () {
  10743. return AbstractMesh._BILLBOARDMODE_Y;
  10744. },
  10745. enumerable: true,
  10746. configurable: true
  10747. });
  10748. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10749. get: function () {
  10750. return AbstractMesh._BILLBOARDMODE_Z;
  10751. },
  10752. enumerable: true,
  10753. configurable: true
  10754. });
  10755. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10756. get: function () {
  10757. return AbstractMesh._BILLBOARDMODE_ALL;
  10758. },
  10759. enumerable: true,
  10760. configurable: true
  10761. });
  10762. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  10763. /**
  10764. * Read-only : the number of facets in the mesh
  10765. */
  10766. get: function () {
  10767. return this._facetNb;
  10768. },
  10769. enumerable: true,
  10770. configurable: true
  10771. });
  10772. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  10773. /**
  10774. * The number (integer) of subdivisions per axis in the partioning space
  10775. */
  10776. get: function () {
  10777. return this._partitioningSubdivisions;
  10778. },
  10779. set: function (nb) {
  10780. this._partitioningSubdivisions = nb;
  10781. },
  10782. enumerable: true,
  10783. configurable: true
  10784. });
  10785. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  10786. /**
  10787. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  10788. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  10789. */
  10790. get: function () {
  10791. return this._partitioningBBoxRatio;
  10792. },
  10793. set: function (ratio) {
  10794. this._partitioningBBoxRatio = ratio;
  10795. },
  10796. enumerable: true,
  10797. configurable: true
  10798. });
  10799. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  10800. /**
  10801. * Read-only boolean : is the feature facetData enabled ?
  10802. */
  10803. get: function () {
  10804. return this._facetDataEnabled;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10810. set: function (callback) {
  10811. if (this._onCollideObserver) {
  10812. this.onCollideObservable.remove(this._onCollideObserver);
  10813. }
  10814. this._onCollideObserver = this.onCollideObservable.add(callback);
  10815. },
  10816. enumerable: true,
  10817. configurable: true
  10818. });
  10819. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10820. set: function (callback) {
  10821. if (this._onCollisionPositionChangeObserver) {
  10822. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10823. }
  10824. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10825. },
  10826. enumerable: true,
  10827. configurable: true
  10828. });
  10829. Object.defineProperty(AbstractMesh.prototype, "material", {
  10830. get: function () {
  10831. return this._material;
  10832. },
  10833. set: function (value) {
  10834. if (this._material === value) {
  10835. return;
  10836. }
  10837. this._material = value;
  10838. if (!this.subMeshes) {
  10839. return;
  10840. }
  10841. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  10842. var subMesh = _a[_i];
  10843. subMesh.setEffect(null);
  10844. }
  10845. },
  10846. enumerable: true,
  10847. configurable: true
  10848. });
  10849. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  10850. get: function () {
  10851. return this._receiveShadows;
  10852. },
  10853. set: function (value) {
  10854. if (this._receiveShadows === value) {
  10855. return;
  10856. }
  10857. this._receiveShadows = value;
  10858. this._markSubMeshesAsLightDirty();
  10859. },
  10860. enumerable: true,
  10861. configurable: true
  10862. });
  10863. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  10864. get: function () {
  10865. return this._hasVertexAlpha;
  10866. },
  10867. set: function (value) {
  10868. if (this._hasVertexAlpha === value) {
  10869. return;
  10870. }
  10871. this._hasVertexAlpha = value;
  10872. this._markSubMeshesAsAttributesDirty();
  10873. },
  10874. enumerable: true,
  10875. configurable: true
  10876. });
  10877. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  10878. get: function () {
  10879. return this._useVertexColors;
  10880. },
  10881. set: function (value) {
  10882. if (this._useVertexColors === value) {
  10883. return;
  10884. }
  10885. this._useVertexColors = value;
  10886. this._markSubMeshesAsAttributesDirty();
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  10892. get: function () {
  10893. return this._computeBonesUsingShaders;
  10894. },
  10895. set: function (value) {
  10896. if (this._computeBonesUsingShaders === value) {
  10897. return;
  10898. }
  10899. this._computeBonesUsingShaders = value;
  10900. this._markSubMeshesAsAttributesDirty();
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  10906. get: function () {
  10907. return this._numBoneInfluencers;
  10908. },
  10909. set: function (value) {
  10910. if (this._numBoneInfluencers === value) {
  10911. return;
  10912. }
  10913. this._numBoneInfluencers = value;
  10914. this._markSubMeshesAsAttributesDirty();
  10915. },
  10916. enumerable: true,
  10917. configurable: true
  10918. });
  10919. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  10920. get: function () {
  10921. return this._applyFog;
  10922. },
  10923. set: function (value) {
  10924. if (this._applyFog === value) {
  10925. return;
  10926. }
  10927. this._applyFog = value;
  10928. this._markSubMeshesAsMiscDirty();
  10929. },
  10930. enumerable: true,
  10931. configurable: true
  10932. });
  10933. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  10934. get: function () {
  10935. return this._collisionMask;
  10936. },
  10937. set: function (mask) {
  10938. this._collisionMask = !isNaN(mask) ? mask : -1;
  10939. },
  10940. enumerable: true,
  10941. configurable: true
  10942. });
  10943. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  10944. get: function () {
  10945. return this._collisionGroup;
  10946. },
  10947. set: function (mask) {
  10948. this._collisionGroup = !isNaN(mask) ? mask : -1;
  10949. },
  10950. enumerable: true,
  10951. configurable: true
  10952. });
  10953. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10954. get: function () {
  10955. return this._skeleton;
  10956. },
  10957. set: function (value) {
  10958. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10959. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10960. }
  10961. if (value && value.needInitialSkinMatrix) {
  10962. value._registerMeshWithPoseMatrix(this);
  10963. }
  10964. this._skeleton = value;
  10965. if (!this._skeleton) {
  10966. this._bonesTransformMatrices = null;
  10967. }
  10968. this._markSubMeshesAsAttributesDirty();
  10969. },
  10970. enumerable: true,
  10971. configurable: true
  10972. });
  10973. /**
  10974. * Returns the string "AbstractMesh"
  10975. */
  10976. AbstractMesh.prototype.getClassName = function () {
  10977. return "AbstractMesh";
  10978. };
  10979. /**
  10980. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10981. */
  10982. AbstractMesh.prototype.toString = function (fullDetails) {
  10983. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10984. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10985. if (this._skeleton) {
  10986. ret += ", skeleton: " + this._skeleton.name;
  10987. }
  10988. if (fullDetails) {
  10989. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10990. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10991. }
  10992. return ret;
  10993. };
  10994. AbstractMesh.prototype._resyncLightSources = function () {
  10995. this._lightSources.length = 0;
  10996. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  10997. var light = _a[_i];
  10998. if (!light.isEnabled()) {
  10999. continue;
  11000. }
  11001. if (light.canAffectMesh(this)) {
  11002. this._lightSources.push(light);
  11003. }
  11004. }
  11005. this._markSubMeshesAsLightDirty();
  11006. };
  11007. AbstractMesh.prototype._resyncLighSource = function (light) {
  11008. var isIn = light.isEnabled() && light.canAffectMesh(this);
  11009. var index = this._lightSources.indexOf(light);
  11010. if (index === -1) {
  11011. if (!isIn) {
  11012. return;
  11013. }
  11014. this._lightSources.push(light);
  11015. }
  11016. else {
  11017. if (isIn) {
  11018. return;
  11019. }
  11020. this._lightSources.splice(index, 1);
  11021. }
  11022. this._markSubMeshesAsLightDirty();
  11023. };
  11024. AbstractMesh.prototype._removeLightSource = function (light) {
  11025. var index = this._lightSources.indexOf(light);
  11026. if (index === -1) {
  11027. return;
  11028. }
  11029. this._lightSources.splice(index, 1);
  11030. };
  11031. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  11032. if (!this.subMeshes) {
  11033. return;
  11034. }
  11035. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11036. var subMesh = _a[_i];
  11037. if (subMesh._materialDefines) {
  11038. func(subMesh._materialDefines);
  11039. }
  11040. }
  11041. };
  11042. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  11043. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  11044. };
  11045. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  11046. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  11047. };
  11048. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  11049. if (!this.subMeshes) {
  11050. return;
  11051. }
  11052. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  11053. var subMesh = _a[_i];
  11054. var material = subMesh.getMaterial();
  11055. if (material) {
  11056. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  11057. }
  11058. }
  11059. };
  11060. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  11061. /**
  11062. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  11063. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  11064. * Default : (0.0, 0.0, 0.0)
  11065. */
  11066. get: function () {
  11067. return this._rotation;
  11068. },
  11069. set: function (newRotation) {
  11070. this._rotation = newRotation;
  11071. },
  11072. enumerable: true,
  11073. configurable: true
  11074. });
  11075. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  11076. /**
  11077. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  11078. * Default : (1.0, 1.0, 1.0)
  11079. */
  11080. get: function () {
  11081. return this._scaling;
  11082. },
  11083. set: function (newScaling) {
  11084. this._scaling = newScaling;
  11085. if (this.physicsImpostor) {
  11086. this.physicsImpostor.forceUpdate();
  11087. }
  11088. },
  11089. enumerable: true,
  11090. configurable: true
  11091. });
  11092. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  11093. /**
  11094. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  11095. * It's null by default.
  11096. * 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)
  11097. */
  11098. get: function () {
  11099. return this._rotationQuaternion;
  11100. },
  11101. set: function (quaternion) {
  11102. this._rotationQuaternion = quaternion;
  11103. //reset the rotation vector.
  11104. if (quaternion && this.rotation.length()) {
  11105. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  11106. }
  11107. },
  11108. enumerable: true,
  11109. configurable: true
  11110. });
  11111. // Methods
  11112. /**
  11113. * Copies the paramater passed Matrix into the mesh Pose matrix.
  11114. * Returns the AbstractMesh.
  11115. */
  11116. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  11117. this._poseMatrix.copyFrom(matrix);
  11118. return this;
  11119. };
  11120. /**
  11121. * Returns the mesh Pose matrix.
  11122. * Returned object : Matrix
  11123. */
  11124. AbstractMesh.prototype.getPoseMatrix = function () {
  11125. return this._poseMatrix;
  11126. };
  11127. /**
  11128. * Disables the mesh edger rendering mode.
  11129. * Returns the AbstractMesh.
  11130. */
  11131. AbstractMesh.prototype.disableEdgesRendering = function () {
  11132. if (this._edgesRenderer !== undefined) {
  11133. this._edgesRenderer.dispose();
  11134. this._edgesRenderer = undefined;
  11135. }
  11136. return this;
  11137. };
  11138. /**
  11139. * Enables the edge rendering mode on the mesh.
  11140. * This mode makes the mesh edges visible.
  11141. * Returns the AbstractMesh.
  11142. */
  11143. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  11144. if (epsilon === void 0) { epsilon = 0.95; }
  11145. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  11146. this.disableEdgesRendering();
  11147. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  11148. return this;
  11149. };
  11150. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  11151. /**
  11152. * Returns true if the mesh is blocked. Used by the class Mesh.
  11153. * Returns the boolean `false` by default.
  11154. */
  11155. get: function () {
  11156. return false;
  11157. },
  11158. enumerable: true,
  11159. configurable: true
  11160. });
  11161. /**
  11162. * Returns the mesh itself by default, used by the class Mesh.
  11163. * Returned type : AbstractMesh
  11164. */
  11165. AbstractMesh.prototype.getLOD = function (camera) {
  11166. return this;
  11167. };
  11168. /**
  11169. * Returns 0 by default, used by the class Mesh.
  11170. * Returns an integer.
  11171. */
  11172. AbstractMesh.prototype.getTotalVertices = function () {
  11173. return 0;
  11174. };
  11175. /**
  11176. * Returns null by default, used by the class Mesh.
  11177. * Returned type : integer array
  11178. */
  11179. AbstractMesh.prototype.getIndices = function () {
  11180. return null;
  11181. };
  11182. /**
  11183. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  11184. * Returned type : float array or Float32Array
  11185. */
  11186. AbstractMesh.prototype.getVerticesData = function (kind) {
  11187. return null;
  11188. };
  11189. /**
  11190. * Sets the vertex data of the mesh geometry for the requested `kind`.
  11191. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  11192. * The `data` are either a numeric array either a Float32Array.
  11193. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  11194. * 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).
  11195. * Note that a new underlying VertexBuffer object is created each call.
  11196. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  11197. *
  11198. * Possible `kind` values :
  11199. * - BABYLON.VertexBuffer.PositionKind
  11200. * - BABYLON.VertexBuffer.UVKind
  11201. * - BABYLON.VertexBuffer.UV2Kind
  11202. * - BABYLON.VertexBuffer.UV3Kind
  11203. * - BABYLON.VertexBuffer.UV4Kind
  11204. * - BABYLON.VertexBuffer.UV5Kind
  11205. * - BABYLON.VertexBuffer.UV6Kind
  11206. * - BABYLON.VertexBuffer.ColorKind
  11207. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11208. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11209. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11210. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11211. *
  11212. * Returns the Mesh.
  11213. */
  11214. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11215. return null;
  11216. };
  11217. /**
  11218. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  11219. * If the mesh has no geometry, it is simply returned as it is.
  11220. * The `data` are either a numeric array either a Float32Array.
  11221. * No new underlying VertexBuffer object is created.
  11222. * 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.
  11223. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  11224. *
  11225. * Possible `kind` values :
  11226. * - BABYLON.VertexBuffer.PositionKind
  11227. * - BABYLON.VertexBuffer.UVKind
  11228. * - BABYLON.VertexBuffer.UV2Kind
  11229. * - BABYLON.VertexBuffer.UV3Kind
  11230. * - BABYLON.VertexBuffer.UV4Kind
  11231. * - BABYLON.VertexBuffer.UV5Kind
  11232. * - BABYLON.VertexBuffer.UV6Kind
  11233. * - BABYLON.VertexBuffer.ColorKind
  11234. * - BABYLON.VertexBuffer.MatricesIndicesKind
  11235. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  11236. * - BABYLON.VertexBuffer.MatricesWeightsKind
  11237. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  11238. *
  11239. * Returns the Mesh.
  11240. */
  11241. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11242. return null;
  11243. };
  11244. /**
  11245. * Sets the mesh indices.
  11246. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  11247. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  11248. * This method creates a new index buffer each call.
  11249. * Returns the Mesh.
  11250. */
  11251. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  11252. return null;
  11253. };
  11254. /** Returns false by default, used by the class Mesh.
  11255. * Returns a boolean
  11256. */
  11257. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  11258. return false;
  11259. };
  11260. /**
  11261. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  11262. * Returns a BoundingInfo
  11263. */
  11264. AbstractMesh.prototype.getBoundingInfo = function () {
  11265. if (this._masterMesh) {
  11266. return this._masterMesh.getBoundingInfo();
  11267. }
  11268. if (!this._boundingInfo) {
  11269. this._updateBoundingInfo();
  11270. }
  11271. return this._boundingInfo;
  11272. };
  11273. /**
  11274. * Sets a mesh new object BoundingInfo.
  11275. * Returns the AbstractMesh.
  11276. */
  11277. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  11278. this._boundingInfo = boundingInfo;
  11279. return this;
  11280. };
  11281. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  11282. get: function () {
  11283. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  11284. },
  11285. enumerable: true,
  11286. configurable: true
  11287. });
  11288. AbstractMesh.prototype._preActivate = function () {
  11289. };
  11290. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  11291. };
  11292. AbstractMesh.prototype._activate = function (renderId) {
  11293. this._renderId = renderId;
  11294. };
  11295. /**
  11296. * Returns the last update of the World matrix
  11297. * Returns a Matrix.
  11298. */
  11299. AbstractMesh.prototype.getWorldMatrix = function () {
  11300. if (this._masterMesh) {
  11301. return this._masterMesh.getWorldMatrix();
  11302. }
  11303. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  11304. this.computeWorldMatrix();
  11305. }
  11306. return this._worldMatrix;
  11307. };
  11308. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  11309. /**
  11310. * Returns directly the last state of the mesh World matrix.
  11311. * A Matrix is returned.
  11312. */
  11313. get: function () {
  11314. return this._worldMatrix;
  11315. },
  11316. enumerable: true,
  11317. configurable: true
  11318. });
  11319. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  11320. /**
  11321. * Returns the current mesh absolute position.
  11322. * Retuns a Vector3.
  11323. */
  11324. get: function () {
  11325. return this._absolutePosition;
  11326. },
  11327. enumerable: true,
  11328. configurable: true
  11329. });
  11330. /**
  11331. * Prevents the World matrix to be computed any longer.
  11332. * Returns the AbstractMesh.
  11333. */
  11334. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11335. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11336. this.computeWorldMatrix(true);
  11337. this._isWorldMatrixFrozen = true;
  11338. return this;
  11339. };
  11340. /**
  11341. * Allows back the World matrix computation.
  11342. * Returns the AbstractMesh.
  11343. */
  11344. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11345. this._isWorldMatrixFrozen = false;
  11346. this.computeWorldMatrix(true);
  11347. return this;
  11348. };
  11349. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11350. /**
  11351. * True if the World matrix has been frozen.
  11352. * Returns a boolean.
  11353. */
  11354. get: function () {
  11355. return this._isWorldMatrixFrozen;
  11356. },
  11357. enumerable: true,
  11358. configurable: true
  11359. });
  11360. /**
  11361. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11362. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11363. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  11364. * The passed axis is also normalized.
  11365. * Returns the AbstractMesh.
  11366. */
  11367. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11368. axis.normalize();
  11369. if (!this.rotationQuaternion) {
  11370. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11371. this.rotation = BABYLON.Vector3.Zero();
  11372. }
  11373. var rotationQuaternion;
  11374. if (!space || space === BABYLON.Space.LOCAL) {
  11375. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11376. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11377. }
  11378. else {
  11379. if (this.parent) {
  11380. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11381. invertParentWorldMatrix.invert();
  11382. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11383. }
  11384. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11385. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11386. }
  11387. return this;
  11388. };
  11389. /**
  11390. * Translates the mesh along the axis vector for the passed distance in the given space.
  11391. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  11392. * Returns the AbstractMesh.
  11393. */
  11394. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11395. var displacementVector = axis.scale(distance);
  11396. if (!space || space === BABYLON.Space.LOCAL) {
  11397. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11398. this.setPositionWithLocalVector(tempV3);
  11399. }
  11400. else {
  11401. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11402. }
  11403. return this;
  11404. };
  11405. /**
  11406. * Adds a rotation step to the mesh current rotation.
  11407. * x, y, z are Euler angles expressed in radians.
  11408. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11409. * This means this rotation is made in the mesh local space only.
  11410. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11411. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11412. * ```javascript
  11413. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11414. * ```
  11415. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11416. * 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.
  11417. * Returns the AbstractMesh.
  11418. */
  11419. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11420. var rotationQuaternion;
  11421. if (this.rotationQuaternion) {
  11422. rotationQuaternion = this.rotationQuaternion;
  11423. }
  11424. else {
  11425. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11426. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11427. }
  11428. var accumulation = BABYLON.Tmp.Quaternion[0];
  11429. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11430. rotationQuaternion.multiplyInPlace(accumulation);
  11431. if (!this.rotationQuaternion) {
  11432. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11433. }
  11434. return this;
  11435. };
  11436. /**
  11437. * Retuns the mesh absolute position in the World.
  11438. * Returns a Vector3.
  11439. */
  11440. AbstractMesh.prototype.getAbsolutePosition = function () {
  11441. this.computeWorldMatrix();
  11442. return this._absolutePosition;
  11443. };
  11444. /**
  11445. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11446. * Returns the AbstractMesh.
  11447. */
  11448. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11449. if (!absolutePosition) {
  11450. return;
  11451. }
  11452. var absolutePositionX;
  11453. var absolutePositionY;
  11454. var absolutePositionZ;
  11455. if (absolutePosition.x === undefined) {
  11456. if (arguments.length < 3) {
  11457. return;
  11458. }
  11459. absolutePositionX = arguments[0];
  11460. absolutePositionY = arguments[1];
  11461. absolutePositionZ = arguments[2];
  11462. }
  11463. else {
  11464. absolutePositionX = absolutePosition.x;
  11465. absolutePositionY = absolutePosition.y;
  11466. absolutePositionZ = absolutePosition.z;
  11467. }
  11468. if (this.parent) {
  11469. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11470. invertParentWorldMatrix.invert();
  11471. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  11472. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  11473. }
  11474. else {
  11475. this.position.x = absolutePositionX;
  11476. this.position.y = absolutePositionY;
  11477. this.position.z = absolutePositionZ;
  11478. }
  11479. return this;
  11480. };
  11481. // ================================== Point of View Movement =================================
  11482. /**
  11483. * Perform relative position change from the point of view of behind the front of the mesh.
  11484. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11485. * Supports definition of mesh facing forward or backward.
  11486. * @param {number} amountRight
  11487. * @param {number} amountUp
  11488. * @param {number} amountForward
  11489. *
  11490. * Returns the AbstractMesh.
  11491. */
  11492. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  11493. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  11494. return this;
  11495. };
  11496. /**
  11497. * Calculate relative position change from the point of view of behind the front of the mesh.
  11498. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11499. * Supports definition of mesh facing forward or backward.
  11500. * @param {number} amountRight
  11501. * @param {number} amountUp
  11502. * @param {number} amountForward
  11503. *
  11504. * Returns a new Vector3.
  11505. */
  11506. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  11507. var rotMatrix = new BABYLON.Matrix();
  11508. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11509. rotQuaternion.toRotationMatrix(rotMatrix);
  11510. var translationDelta = BABYLON.Vector3.Zero();
  11511. var defForwardMult = this.definedFacingForward ? -1 : 1;
  11512. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  11513. return translationDelta;
  11514. };
  11515. // ================================== Point of View Rotation =================================
  11516. /**
  11517. * Perform relative rotation change from the point of view of behind the front of the mesh.
  11518. * Supports definition of mesh facing forward or backward.
  11519. * @param {number} flipBack
  11520. * @param {number} twirlClockwise
  11521. * @param {number} tiltRight
  11522. *
  11523. * Returns the AbstractMesh.
  11524. */
  11525. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11526. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  11527. return this;
  11528. };
  11529. /**
  11530. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  11531. * Supports definition of mesh facing forward or backward.
  11532. * @param {number} flipBack
  11533. * @param {number} twirlClockwise
  11534. * @param {number} tiltRight
  11535. *
  11536. * Returns a new Vector3.
  11537. */
  11538. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11539. var defForwardMult = this.definedFacingForward ? 1 : -1;
  11540. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  11541. };
  11542. /**
  11543. * Sets a new pivot matrix to the mesh.
  11544. * Returns the AbstractMesh.
  11545. */
  11546. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  11547. this._pivotMatrix = matrix;
  11548. this._cache.pivotMatrixUpdated = true;
  11549. return this;
  11550. };
  11551. /**
  11552. * Returns the mesh pivot matrix.
  11553. * Default : Identity.
  11554. * A Matrix is returned.
  11555. */
  11556. AbstractMesh.prototype.getPivotMatrix = function () {
  11557. return this._pivotMatrix;
  11558. };
  11559. AbstractMesh.prototype._isSynchronized = function () {
  11560. if (this._isDirty) {
  11561. return false;
  11562. }
  11563. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  11564. return false;
  11565. if (this._cache.pivotMatrixUpdated) {
  11566. return false;
  11567. }
  11568. if (this.infiniteDistance) {
  11569. return false;
  11570. }
  11571. if (!this._cache.position.equals(this.position))
  11572. return false;
  11573. if (this.rotationQuaternion) {
  11574. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  11575. return false;
  11576. }
  11577. if (!this._cache.rotation.equals(this.rotation))
  11578. return false;
  11579. if (!this._cache.scaling.equals(this.scaling))
  11580. return false;
  11581. return true;
  11582. };
  11583. AbstractMesh.prototype._initCache = function () {
  11584. _super.prototype._initCache.call(this);
  11585. this._cache.localMatrixUpdated = false;
  11586. this._cache.position = BABYLON.Vector3.Zero();
  11587. this._cache.scaling = BABYLON.Vector3.Zero();
  11588. this._cache.rotation = BABYLON.Vector3.Zero();
  11589. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  11590. this._cache.billboardMode = -1;
  11591. };
  11592. AbstractMesh.prototype.markAsDirty = function (property) {
  11593. if (property === "rotation") {
  11594. this.rotationQuaternion = null;
  11595. }
  11596. this._currentRenderId = Number.MAX_VALUE;
  11597. this._isDirty = true;
  11598. return this;
  11599. };
  11600. /**
  11601. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  11602. * Returns the AbstractMesh.
  11603. */
  11604. AbstractMesh.prototype._updateBoundingInfo = function () {
  11605. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  11606. this._boundingInfo.update(this.worldMatrixFromCache);
  11607. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11608. return this;
  11609. };
  11610. /**
  11611. * Update a mesh's children BoundingInfo objects only.
  11612. * Returns the AbstractMesh.
  11613. */
  11614. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  11615. if (!this.subMeshes) {
  11616. return;
  11617. }
  11618. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  11619. var subMesh = this.subMeshes[subIndex];
  11620. if (!subMesh.IsGlobal) {
  11621. subMesh.updateBoundingInfo(matrix);
  11622. }
  11623. }
  11624. return this;
  11625. };
  11626. /**
  11627. * Computes the mesh World matrix and returns it.
  11628. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  11629. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  11630. * If the parameter `force`is set to `true`, the actual computation is done.
  11631. * Returns the mesh World Matrix.
  11632. */
  11633. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  11634. if (this._isWorldMatrixFrozen) {
  11635. return this._worldMatrix;
  11636. }
  11637. if (!force && this.isSynchronized(true)) {
  11638. this._currentRenderId = this.getScene().getRenderId();
  11639. return this._worldMatrix;
  11640. }
  11641. this._cache.position.copyFrom(this.position);
  11642. this._cache.scaling.copyFrom(this.scaling);
  11643. this._cache.pivotMatrixUpdated = false;
  11644. this._cache.billboardMode = this.billboardMode;
  11645. this._currentRenderId = this.getScene().getRenderId();
  11646. this._isDirty = false;
  11647. // Scaling
  11648. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  11649. // Rotation
  11650. //rotate, if quaternion is set and rotation was used
  11651. if (this.rotationQuaternion) {
  11652. var len = this.rotation.length();
  11653. if (len) {
  11654. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  11655. this.rotation.copyFromFloats(0, 0, 0);
  11656. }
  11657. }
  11658. if (this.rotationQuaternion) {
  11659. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  11660. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  11661. }
  11662. else {
  11663. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  11664. this._cache.rotation.copyFrom(this.rotation);
  11665. }
  11666. // Translation
  11667. if (this.infiniteDistance && !this.parent) {
  11668. var camera = this.getScene().activeCamera;
  11669. if (camera) {
  11670. var cameraWorldMatrix = camera.getWorldMatrix();
  11671. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  11672. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  11673. }
  11674. }
  11675. else {
  11676. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  11677. }
  11678. // Composing transformations
  11679. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  11680. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11681. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  11682. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  11683. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  11684. // Need to decompose each rotation here
  11685. var currentPosition = BABYLON.Tmp.Vector3[3];
  11686. if (this.parent && this.parent.getWorldMatrix) {
  11687. if (this._meshToBoneReferal) {
  11688. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11689. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  11690. }
  11691. else {
  11692. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  11693. }
  11694. }
  11695. else {
  11696. currentPosition.copyFrom(this.position);
  11697. }
  11698. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  11699. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  11700. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  11701. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  11702. }
  11703. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  11704. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  11705. }
  11706. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  11707. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  11708. }
  11709. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  11710. }
  11711. else {
  11712. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  11713. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  11714. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  11715. }
  11716. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  11717. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11718. }
  11719. // Local world
  11720. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  11721. // Parent
  11722. if (this.parent && this.parent.getWorldMatrix) {
  11723. this._markSyncedWithParent();
  11724. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  11725. if (this._meshToBoneReferal) {
  11726. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11727. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  11728. }
  11729. else {
  11730. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  11731. }
  11732. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  11733. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  11734. this._worldMatrix.copyFrom(this._localWorld);
  11735. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  11736. }
  11737. else {
  11738. if (this._meshToBoneReferal) {
  11739. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11740. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  11741. }
  11742. else {
  11743. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  11744. }
  11745. }
  11746. }
  11747. else {
  11748. this._worldMatrix.copyFrom(this._localWorld);
  11749. }
  11750. // Bounding info
  11751. this._updateBoundingInfo();
  11752. // Absolute position
  11753. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  11754. // Callbacks
  11755. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  11756. if (!this._poseMatrix) {
  11757. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  11758. }
  11759. return this._worldMatrix;
  11760. };
  11761. /**
  11762. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  11763. * @param func: callback function to add
  11764. *
  11765. * Returns the AbstractMesh.
  11766. */
  11767. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  11768. this.onAfterWorldMatrixUpdateObservable.add(func);
  11769. return this;
  11770. };
  11771. /**
  11772. * Removes a registered callback function.
  11773. * Returns the AbstractMesh.
  11774. */
  11775. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  11776. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  11777. return this;
  11778. };
  11779. /**
  11780. * Sets the mesh position in its local space.
  11781. * Returns the AbstractMesh.
  11782. */
  11783. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  11784. this.computeWorldMatrix();
  11785. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  11786. return this;
  11787. };
  11788. /**
  11789. * Returns the mesh position in the local space from the current World matrix values.
  11790. * Returns a new Vector3.
  11791. */
  11792. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  11793. this.computeWorldMatrix();
  11794. var invLocalWorldMatrix = this._localWorld.clone();
  11795. invLocalWorldMatrix.invert();
  11796. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  11797. };
  11798. /**
  11799. * Translates the mesh along the passed Vector3 in its local space.
  11800. * Returns the AbstractMesh.
  11801. */
  11802. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  11803. this.computeWorldMatrix(true);
  11804. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  11805. return this;
  11806. };
  11807. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  11808. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  11809. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  11810. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  11811. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  11812. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  11813. /// <returns>Mesh oriented towards targetMesh</returns>
  11814. if (yawCor === void 0) { yawCor = 0; }
  11815. if (pitchCor === void 0) { pitchCor = 0; }
  11816. if (rollCor === void 0) { rollCor = 0; }
  11817. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11818. var dv = AbstractMesh._lookAtVectorCache;
  11819. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  11820. targetPoint.subtractToRef(pos, dv);
  11821. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  11822. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  11823. var pitch = Math.atan2(dv.y, len);
  11824. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  11825. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  11826. return this;
  11827. };
  11828. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  11829. this._meshToBoneReferal = affectedMesh;
  11830. this.parent = bone;
  11831. if (bone.getWorldMatrix().determinant() < 0) {
  11832. this.scalingDeterminant *= -1;
  11833. }
  11834. return this;
  11835. };
  11836. AbstractMesh.prototype.detachFromBone = function () {
  11837. if (this.parent.getWorldMatrix().determinant() < 0) {
  11838. this.scalingDeterminant *= -1;
  11839. }
  11840. this._meshToBoneReferal = null;
  11841. this.parent = null;
  11842. return this;
  11843. };
  11844. /**
  11845. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  11846. * A mesh is in the frustum if its bounding box intersects the frustum.
  11847. * Boolean returned.
  11848. */
  11849. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11850. return this._boundingInfo.isInFrustum(frustumPlanes);
  11851. };
  11852. /**
  11853. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  11854. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  11855. * Boolean returned.
  11856. */
  11857. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11858. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11859. ;
  11860. };
  11861. /**
  11862. * True if the mesh intersects another mesh or a SolidParticle object.
  11863. * 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)
  11864. * Returns a boolean.
  11865. */
  11866. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11867. if (!this._boundingInfo || !mesh._boundingInfo) {
  11868. return false;
  11869. }
  11870. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11871. };
  11872. /**
  11873. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  11874. * Returns a boolean.
  11875. */
  11876. AbstractMesh.prototype.intersectsPoint = function (point) {
  11877. if (!this._boundingInfo) {
  11878. return false;
  11879. }
  11880. return this._boundingInfo.intersectsPoint(point);
  11881. };
  11882. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11883. return this.physicsImpostor;
  11884. };
  11885. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11886. if (!camera) {
  11887. camera = this.getScene().activeCamera;
  11888. }
  11889. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11890. };
  11891. /**
  11892. * Returns the distance from the mesh to the active camera.
  11893. * Returns a float.
  11894. */
  11895. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11896. if (!camera) {
  11897. camera = this.getScene().activeCamera;
  11898. }
  11899. return this.absolutePosition.subtract(camera.position).length();
  11900. };
  11901. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11902. if (!this.physicsImpostor) {
  11903. return;
  11904. }
  11905. this.physicsImpostor.applyImpulse(force, contactPoint);
  11906. return this;
  11907. };
  11908. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  11909. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  11910. return;
  11911. }
  11912. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  11913. mainPivot: pivot1,
  11914. connectedPivot: pivot2,
  11915. nativeParams: options
  11916. });
  11917. return this;
  11918. };
  11919. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  11920. // Collisions
  11921. /**
  11922. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  11923. * Default `false`.
  11924. */
  11925. get: function () {
  11926. return this._checkCollisions;
  11927. },
  11928. set: function (collisionEnabled) {
  11929. this._checkCollisions = collisionEnabled;
  11930. if (this.getScene().workerCollisions) {
  11931. this.getScene().collisionCoordinator.onMeshUpdated(this);
  11932. }
  11933. },
  11934. enumerable: true,
  11935. configurable: true
  11936. });
  11937. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  11938. var globalPosition = this.getAbsolutePosition();
  11939. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  11940. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  11941. if (!this._collider) {
  11942. this._collider = new BABYLON.Collider();
  11943. }
  11944. this._collider.radius = this.ellipsoid;
  11945. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  11946. return this;
  11947. };
  11948. // Submeshes octree
  11949. /**
  11950. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  11951. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  11952. * Returns an Octree of submeshes.
  11953. */
  11954. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11955. if (maxCapacity === void 0) { maxCapacity = 64; }
  11956. if (maxDepth === void 0) { maxDepth = 2; }
  11957. if (!this._submeshesOctree) {
  11958. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11959. }
  11960. this.computeWorldMatrix(true);
  11961. // Update octree
  11962. var bbox = this.getBoundingInfo().boundingBox;
  11963. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11964. return this._submeshesOctree;
  11965. };
  11966. // Collisions
  11967. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  11968. this._generatePointsArray();
  11969. // Transformation
  11970. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  11971. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  11972. subMesh._lastColliderWorldVertices = [];
  11973. subMesh._trianglePlanes = [];
  11974. var start = subMesh.verticesStart;
  11975. var end = (subMesh.verticesStart + subMesh.verticesCount);
  11976. for (var i = start; i < end; i++) {
  11977. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  11978. }
  11979. }
  11980. // Collide
  11981. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  11982. if (collider.collisionFound) {
  11983. collider.collidedMesh = this;
  11984. }
  11985. return this;
  11986. };
  11987. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  11988. var subMeshes;
  11989. var len;
  11990. // Octrees
  11991. if (this._submeshesOctree && this.useOctreeForCollisions) {
  11992. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  11993. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  11994. len = intersections.length;
  11995. subMeshes = intersections.data;
  11996. }
  11997. else {
  11998. subMeshes = this.subMeshes;
  11999. len = subMeshes.length;
  12000. }
  12001. for (var index = 0; index < len; index++) {
  12002. var subMesh = subMeshes[index];
  12003. // Bounding test
  12004. if (len > 1 && !subMesh._checkCollision(collider))
  12005. continue;
  12006. this._collideForSubMesh(subMesh, transformMatrix, collider);
  12007. }
  12008. return this;
  12009. };
  12010. AbstractMesh.prototype._checkCollision = function (collider) {
  12011. // Bounding box test
  12012. if (!this._boundingInfo._checkCollision(collider))
  12013. return this;
  12014. // Transformation matrix
  12015. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  12016. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  12017. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  12018. return this;
  12019. };
  12020. // Picking
  12021. AbstractMesh.prototype._generatePointsArray = function () {
  12022. return false;
  12023. };
  12024. /**
  12025. * Checks if the passed Ray intersects with the mesh.
  12026. * Returns an object PickingInfo.
  12027. */
  12028. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  12029. var pickingInfo = new BABYLON.PickingInfo();
  12030. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  12031. return pickingInfo;
  12032. }
  12033. if (!this._generatePointsArray()) {
  12034. return pickingInfo;
  12035. }
  12036. var intersectInfo = null;
  12037. // Octrees
  12038. var subMeshes;
  12039. var len;
  12040. if (this._submeshesOctree && this.useOctreeForPicking) {
  12041. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  12042. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  12043. len = intersections.length;
  12044. subMeshes = intersections.data;
  12045. }
  12046. else {
  12047. subMeshes = this.subMeshes;
  12048. len = subMeshes.length;
  12049. }
  12050. for (var index = 0; index < len; index++) {
  12051. var subMesh = subMeshes[index];
  12052. // Bounding test
  12053. if (len > 1 && !subMesh.canIntersects(ray))
  12054. continue;
  12055. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  12056. if (currentIntersectInfo) {
  12057. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12058. intersectInfo = currentIntersectInfo;
  12059. intersectInfo.subMeshId = index;
  12060. if (fastCheck) {
  12061. break;
  12062. }
  12063. }
  12064. }
  12065. }
  12066. if (intersectInfo) {
  12067. // Get picked point
  12068. var world = this.getWorldMatrix();
  12069. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  12070. var direction = ray.direction.clone();
  12071. direction = direction.scale(intersectInfo.distance);
  12072. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  12073. var pickedPoint = worldOrigin.add(worldDirection);
  12074. // Return result
  12075. pickingInfo.hit = true;
  12076. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  12077. pickingInfo.pickedPoint = pickedPoint;
  12078. pickingInfo.pickedMesh = this;
  12079. pickingInfo.bu = intersectInfo.bu;
  12080. pickingInfo.bv = intersectInfo.bv;
  12081. pickingInfo.faceId = intersectInfo.faceId;
  12082. pickingInfo.subMeshId = intersectInfo.subMeshId;
  12083. return pickingInfo;
  12084. }
  12085. return pickingInfo;
  12086. };
  12087. /**
  12088. * Clones the mesh, used by the class Mesh.
  12089. * Just returns `null` for an AbstractMesh.
  12090. */
  12091. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12092. return null;
  12093. };
  12094. /**
  12095. * Disposes all the mesh submeshes.
  12096. * Returns the AbstractMesh.
  12097. */
  12098. AbstractMesh.prototype.releaseSubMeshes = function () {
  12099. if (this.subMeshes) {
  12100. while (this.subMeshes.length) {
  12101. this.subMeshes[0].dispose();
  12102. }
  12103. }
  12104. else {
  12105. this.subMeshes = new Array();
  12106. }
  12107. return this;
  12108. };
  12109. /**
  12110. * Disposes the AbstractMesh.
  12111. * Some internal references are kept for further use.
  12112. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  12113. * Returns nothing.
  12114. */
  12115. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  12116. var _this = this;
  12117. var index;
  12118. // Action manager
  12119. if (this.actionManager) {
  12120. this.actionManager.dispose();
  12121. this.actionManager = null;
  12122. }
  12123. // Skeleton
  12124. this.skeleton = null;
  12125. // Animations
  12126. this.getScene().stopAnimation(this);
  12127. // Physics
  12128. if (this.physicsImpostor) {
  12129. this.physicsImpostor.dispose();
  12130. }
  12131. // Intersections in progress
  12132. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  12133. var other = this._intersectionsInProgress[index];
  12134. var pos = other._intersectionsInProgress.indexOf(this);
  12135. other._intersectionsInProgress.splice(pos, 1);
  12136. }
  12137. this._intersectionsInProgress = [];
  12138. // Lights
  12139. var lights = this.getScene().lights;
  12140. lights.forEach(function (light) {
  12141. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  12142. if (meshIndex !== -1) {
  12143. light.includedOnlyMeshes.splice(meshIndex, 1);
  12144. }
  12145. meshIndex = light.excludedMeshes.indexOf(_this);
  12146. if (meshIndex !== -1) {
  12147. light.excludedMeshes.splice(meshIndex, 1);
  12148. }
  12149. // Shadow generators
  12150. var generator = light.getShadowGenerator();
  12151. if (generator) {
  12152. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  12153. if (meshIndex !== -1) {
  12154. generator.getShadowMap().renderList.splice(meshIndex, 1);
  12155. }
  12156. }
  12157. });
  12158. // Edges
  12159. if (this._edgesRenderer) {
  12160. this._edgesRenderer.dispose();
  12161. this._edgesRenderer = null;
  12162. }
  12163. // SubMeshes
  12164. if (this.getClassName() !== "InstancedMesh") {
  12165. this.releaseSubMeshes();
  12166. }
  12167. // Octree
  12168. var sceneOctree = this.getScene().selectionOctree;
  12169. if (sceneOctree) {
  12170. var index = sceneOctree.dynamicContent.indexOf(this);
  12171. if (index !== -1) {
  12172. sceneOctree.dynamicContent.splice(index, 1);
  12173. }
  12174. }
  12175. // Engine
  12176. this.getScene().getEngine().wipeCaches();
  12177. // Remove from scene
  12178. this.getScene().removeMesh(this);
  12179. if (!doNotRecurse) {
  12180. // Particles
  12181. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  12182. if (this.getScene().particleSystems[index].emitter === this) {
  12183. this.getScene().particleSystems[index].dispose();
  12184. index--;
  12185. }
  12186. }
  12187. // Children
  12188. var objects = this.getDescendants(true);
  12189. for (index = 0; index < objects.length; index++) {
  12190. objects[index].dispose();
  12191. }
  12192. }
  12193. else {
  12194. var childMeshes = this.getChildMeshes(true);
  12195. for (index = 0; index < childMeshes.length; index++) {
  12196. var child = childMeshes[index];
  12197. child.parent = null;
  12198. child.computeWorldMatrix(true);
  12199. }
  12200. }
  12201. // facet data
  12202. if (this._facetDataEnabled) {
  12203. this.disableFacetData();
  12204. }
  12205. this.onAfterWorldMatrixUpdateObservable.clear();
  12206. this.onCollideObservable.clear();
  12207. this.onCollisionPositionChangeObservable.clear();
  12208. this._isDisposed = true;
  12209. _super.prototype.dispose.call(this);
  12210. };
  12211. /**
  12212. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  12213. * This Vector3 is expressed in the World space.
  12214. */
  12215. AbstractMesh.prototype.getDirection = function (localAxis) {
  12216. var result = BABYLON.Vector3.Zero();
  12217. this.getDirectionToRef(localAxis, result);
  12218. return result;
  12219. };
  12220. /**
  12221. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  12222. * localAxis is expressed in the mesh local space.
  12223. * result is computed in the Wordl space from the mesh World matrix.
  12224. * Returns the AbstractMesh.
  12225. */
  12226. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  12227. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  12228. return this;
  12229. };
  12230. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  12231. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  12232. if (this.getScene().getRenderId() == 0) {
  12233. this.computeWorldMatrix(true);
  12234. }
  12235. var wm = this.getWorldMatrix();
  12236. if (space == BABYLON.Space.WORLD) {
  12237. var tmat = BABYLON.Tmp.Matrix[0];
  12238. wm.invertToRef(tmat);
  12239. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  12240. }
  12241. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  12242. this._pivotMatrix.m[12] = -point.x;
  12243. this._pivotMatrix.m[13] = -point.y;
  12244. this._pivotMatrix.m[14] = -point.z;
  12245. this._cache.pivotMatrixUpdated = true;
  12246. return this;
  12247. };
  12248. /**
  12249. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  12250. */
  12251. AbstractMesh.prototype.getPivotPoint = function () {
  12252. var point = BABYLON.Vector3.Zero();
  12253. this.getPivotPointToRef(point);
  12254. return point;
  12255. };
  12256. /**
  12257. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  12258. * Returns the AbstractMesh.
  12259. */
  12260. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  12261. result.x = -this._pivotMatrix.m[12];
  12262. result.y = -this._pivotMatrix.m[13];
  12263. result.z = -this._pivotMatrix.m[14];
  12264. return this;
  12265. };
  12266. /**
  12267. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  12268. */
  12269. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  12270. var point = BABYLON.Vector3.Zero();
  12271. this.getAbsolutePivotPointToRef(point);
  12272. return point;
  12273. };
  12274. /**
  12275. * Defines the passed mesh as the parent of the current mesh.
  12276. * Returns the AbstractMesh.
  12277. */
  12278. AbstractMesh.prototype.setParent = function (mesh) {
  12279. var child = this;
  12280. var parent = mesh;
  12281. if (mesh == null) {
  12282. var rotation = BABYLON.Tmp.Quaternion[0];
  12283. var position = BABYLON.Tmp.Vector3[0];
  12284. var scale = BABYLON.Tmp.Vector3[1];
  12285. child.getWorldMatrix().decompose(scale, rotation, position);
  12286. if (child.rotationQuaternion) {
  12287. child.rotationQuaternion.copyFrom(rotation);
  12288. }
  12289. else {
  12290. rotation.toEulerAnglesToRef(child.rotation);
  12291. }
  12292. child.position.x = position.x;
  12293. child.position.y = position.y;
  12294. child.position.z = position.z;
  12295. }
  12296. else {
  12297. var rotation = BABYLON.Tmp.Quaternion[0];
  12298. var position = BABYLON.Tmp.Vector3[0];
  12299. var scale = BABYLON.Tmp.Vector3[1];
  12300. var m1 = BABYLON.Tmp.Matrix[0];
  12301. var m2 = BABYLON.Tmp.Matrix[1];
  12302. parent.getWorldMatrix().decompose(scale, rotation, position);
  12303. rotation.toRotationMatrix(m1);
  12304. m2.setTranslation(position);
  12305. m2.multiplyToRef(m1, m1);
  12306. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  12307. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12308. m.decompose(scale, rotation, position);
  12309. if (child.rotationQuaternion) {
  12310. child.rotationQuaternion.copyFrom(rotation);
  12311. }
  12312. else {
  12313. rotation.toEulerAnglesToRef(child.rotation);
  12314. }
  12315. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  12316. var m = child.getWorldMatrix().multiply(invParentMatrix);
  12317. m.decompose(scale, rotation, position);
  12318. child.position.x = position.x;
  12319. child.position.y = position.y;
  12320. child.position.z = position.z;
  12321. }
  12322. child.parent = parent;
  12323. return this;
  12324. };
  12325. /**
  12326. * Adds the passed mesh as a child to the current mesh.
  12327. * Returns the AbstractMesh.
  12328. */
  12329. AbstractMesh.prototype.addChild = function (mesh) {
  12330. mesh.setParent(this);
  12331. return this;
  12332. };
  12333. /**
  12334. * Removes the passed mesh from the current mesh children list.
  12335. * Returns the AbstractMesh.
  12336. */
  12337. AbstractMesh.prototype.removeChild = function (mesh) {
  12338. mesh.setParent(null);
  12339. return this;
  12340. };
  12341. /**
  12342. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  12343. * Returns the AbstractMesh.
  12344. */
  12345. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  12346. result.x = this._pivotMatrix.m[12];
  12347. result.y = this._pivotMatrix.m[13];
  12348. result.z = this._pivotMatrix.m[14];
  12349. this.getPivotPointToRef(result);
  12350. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  12351. return this;
  12352. };
  12353. // Facet data
  12354. /**
  12355. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  12356. * Returns the AbstractMesh.
  12357. */
  12358. AbstractMesh.prototype._initFacetData = function () {
  12359. if (!this._facetNormals) {
  12360. this._facetNormals = new Array();
  12361. }
  12362. if (!this._facetPositions) {
  12363. this._facetPositions = new Array();
  12364. }
  12365. if (!this._facetPartitioning) {
  12366. this._facetPartitioning = new Array();
  12367. }
  12368. this._facetNb = this.getIndices().length / 3;
  12369. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12370. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12371. for (var f = 0; f < this._facetNb; f++) {
  12372. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12373. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12374. }
  12375. this._facetDataEnabled = true;
  12376. return this;
  12377. };
  12378. /**
  12379. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12380. * This method can be called within the render loop.
  12381. * 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.
  12382. * Returns the AbstractMesh.
  12383. */
  12384. AbstractMesh.prototype.updateFacetData = function () {
  12385. if (!this._facetDataEnabled) {
  12386. this._initFacetData();
  12387. }
  12388. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12389. var indices = this.getIndices();
  12390. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12391. var bInfo = this.getBoundingInfo();
  12392. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12393. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12394. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12395. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12396. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12397. this._subDiv.max = this._partitioningSubdivisions;
  12398. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12399. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12400. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12401. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12402. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12403. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12404. // set the parameters for ComputeNormals()
  12405. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12406. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12407. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12408. this._facetParameters.bInfo = bInfo;
  12409. this._facetParameters.bbSize = this._bbSize;
  12410. this._facetParameters.subDiv = this._subDiv;
  12411. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12412. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12413. return this;
  12414. };
  12415. /**
  12416. * Returns the facetLocalNormals array.
  12417. * The normals are expressed in the mesh local space.
  12418. */
  12419. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12420. if (!this._facetNormals) {
  12421. this.updateFacetData();
  12422. }
  12423. return this._facetNormals;
  12424. };
  12425. /**
  12426. * Returns the facetLocalPositions array.
  12427. * The facet positions are expressed in the mesh local space.
  12428. */
  12429. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12430. if (!this._facetPositions) {
  12431. this.updateFacetData();
  12432. }
  12433. return this._facetPositions;
  12434. };
  12435. /**
  12436. * Returns the facetLocalPartioning array.
  12437. */
  12438. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12439. if (!this._facetPartitioning) {
  12440. this.updateFacetData();
  12441. }
  12442. return this._facetPartitioning;
  12443. };
  12444. /**
  12445. * Returns the i-th facet position in the world system.
  12446. * This method allocates a new Vector3 per call.
  12447. */
  12448. AbstractMesh.prototype.getFacetPosition = function (i) {
  12449. var pos = BABYLON.Vector3.Zero();
  12450. this.getFacetPositionToRef(i, pos);
  12451. return pos;
  12452. };
  12453. /**
  12454. * Sets the reference Vector3 with the i-th facet position in the world system.
  12455. * Returns the AbstractMesh.
  12456. */
  12457. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  12458. var localPos = (this.getFacetLocalPositions())[i];
  12459. var world = this.getWorldMatrix();
  12460. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  12461. return this;
  12462. };
  12463. /**
  12464. * Returns the i-th facet normal in the world system.
  12465. * This method allocates a new Vector3 per call.
  12466. */
  12467. AbstractMesh.prototype.getFacetNormal = function (i) {
  12468. var norm = BABYLON.Vector3.Zero();
  12469. this.getFacetNormalToRef(i, norm);
  12470. return norm;
  12471. };
  12472. /**
  12473. * Sets the reference Vector3 with the i-th facet normal in the world system.
  12474. * Returns the AbstractMesh.
  12475. */
  12476. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  12477. var localNorm = (this.getFacetLocalNormals())[i];
  12478. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  12479. return this;
  12480. };
  12481. /**
  12482. * 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).
  12483. */
  12484. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  12485. var bInfo = this.getBoundingInfo();
  12486. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  12487. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  12488. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  12489. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  12490. return null;
  12491. }
  12492. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  12493. };
  12494. /**
  12495. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  12496. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  12497. * 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.
  12498. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12499. * 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.
  12500. */
  12501. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  12502. if (checkFace === void 0) { checkFace = false; }
  12503. if (facing === void 0) { facing = true; }
  12504. var world = this.getWorldMatrix();
  12505. var invMat = BABYLON.Tmp.Matrix[5];
  12506. world.invertToRef(invMat);
  12507. var invVect = BABYLON.Tmp.Vector3[8];
  12508. var closest = null;
  12509. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  12510. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  12511. if (projected) {
  12512. // tranform the local computed projected vector to world coordinates
  12513. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  12514. }
  12515. return closest;
  12516. };
  12517. /**
  12518. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  12519. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  12520. * 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.
  12521. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12522. * 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.
  12523. */
  12524. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  12525. if (checkFace === void 0) { checkFace = false; }
  12526. if (facing === void 0) { facing = true; }
  12527. var closest = null;
  12528. var tmpx = 0.0;
  12529. var tmpy = 0.0;
  12530. var tmpz = 0.0;
  12531. var d = 0.0; // tmp dot facet normal * facet position
  12532. var t0 = 0.0;
  12533. var projx = 0.0;
  12534. var projy = 0.0;
  12535. var projz = 0.0;
  12536. // Get all the facets in the same partitioning block than (x, y, z)
  12537. var facetPositions = this.getFacetLocalPositions();
  12538. var facetNormals = this.getFacetLocalNormals();
  12539. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  12540. if (!facetsInBlock) {
  12541. return null;
  12542. }
  12543. // Get the closest facet to (x, y, z)
  12544. var shortest = Number.MAX_VALUE; // init distance vars
  12545. var tmpDistance = shortest;
  12546. var fib; // current facet in the block
  12547. var norm; // current facet normal
  12548. var p0; // current facet barycenter position
  12549. // loop on all the facets in the current partitioning block
  12550. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  12551. fib = facetsInBlock[idx];
  12552. norm = facetNormals[fib];
  12553. p0 = facetPositions[fib];
  12554. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  12555. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  12556. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  12557. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  12558. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  12559. projx = x + norm.x * t0;
  12560. projy = y + norm.y * t0;
  12561. projz = z + norm.z * t0;
  12562. tmpx = projx - x;
  12563. tmpy = projy - y;
  12564. tmpz = projz - z;
  12565. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  12566. if (tmpDistance < shortest) {
  12567. shortest = tmpDistance;
  12568. closest = fib;
  12569. if (projected) {
  12570. projected.x = projx;
  12571. projected.y = projy;
  12572. projected.z = projz;
  12573. }
  12574. }
  12575. }
  12576. }
  12577. return closest;
  12578. };
  12579. /**
  12580. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  12581. */
  12582. AbstractMesh.prototype.getFacetDataParameters = function () {
  12583. return this._facetParameters;
  12584. };
  12585. /**
  12586. * Disables the feature FacetData and frees the related memory.
  12587. * Returns the AbstractMesh.
  12588. */
  12589. AbstractMesh.prototype.disableFacetData = function () {
  12590. if (this._facetDataEnabled) {
  12591. this._facetDataEnabled = false;
  12592. this._facetPositions = null;
  12593. this._facetNormals = null;
  12594. this._facetPartitioning = null;
  12595. this._facetParameters = null;
  12596. }
  12597. return this;
  12598. };
  12599. /**
  12600. * Creates new normals data for the mesh.
  12601. * @param updatable.
  12602. */
  12603. AbstractMesh.prototype.createNormals = function (updatable) {
  12604. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12605. var indices = this.getIndices();
  12606. var normals;
  12607. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  12608. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12609. }
  12610. else {
  12611. normals = [];
  12612. }
  12613. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  12614. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  12615. };
  12616. return AbstractMesh;
  12617. }(BABYLON.Node));
  12618. // Statics
  12619. AbstractMesh._BILLBOARDMODE_NONE = 0;
  12620. AbstractMesh._BILLBOARDMODE_X = 1;
  12621. AbstractMesh._BILLBOARDMODE_Y = 2;
  12622. AbstractMesh._BILLBOARDMODE_Z = 4;
  12623. AbstractMesh._BILLBOARDMODE_ALL = 7;
  12624. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  12625. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  12626. BABYLON.AbstractMesh = AbstractMesh;
  12627. })(BABYLON || (BABYLON = {}));
  12628. //# sourceMappingURL=babylon.abstractMesh.js.map
  12629. var BABYLON;
  12630. (function (BABYLON) {
  12631. var Light = (function (_super) {
  12632. __extends(Light, _super);
  12633. /**
  12634. * Creates a Light object in the scene.
  12635. * Documentation : http://doc.babylonjs.com/tutorials/lights
  12636. */
  12637. function Light(name, scene) {
  12638. var _this = _super.call(this, name, scene) || this;
  12639. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  12640. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  12641. _this.intensity = 1.0;
  12642. _this.range = Number.MAX_VALUE;
  12643. _this._excludeWithLayerMask = 0;
  12644. _this._includeOnlyWithLayerMask = 0;
  12645. _this._lightmapMode = 0;
  12646. // PBR Properties.
  12647. _this.radius = 0.00001;
  12648. _this._excludedMeshesIds = new Array();
  12649. _this._includedOnlyMeshesIds = new Array();
  12650. _this.getScene().addLight(_this);
  12651. _this._uniformBuffer = new BABYLON.UniformBuffer(scene.getEngine());
  12652. _this._buildUniformLayout();
  12653. _this.includedOnlyMeshes = new Array();
  12654. _this.excludedMeshes = new Array();
  12655. _this._resyncMeshes();
  12656. return _this;
  12657. }
  12658. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  12659. /**
  12660. * If every light affecting the material is in this lightmapMode,
  12661. * material.lightmapTexture adds or multiplies
  12662. * (depends on material.useLightmapAsShadowmap)
  12663. * after every other light calculations.
  12664. */
  12665. get: function () {
  12666. return Light._LIGHTMAP_DEFAULT;
  12667. },
  12668. enumerable: true,
  12669. configurable: true
  12670. });
  12671. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  12672. /**
  12673. * material.lightmapTexture as only diffuse lighting from this light
  12674. * adds pnly specular lighting from this light
  12675. * adds dynamic shadows
  12676. */
  12677. get: function () {
  12678. return Light._LIGHTMAP_SPECULAR;
  12679. },
  12680. enumerable: true,
  12681. configurable: true
  12682. });
  12683. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  12684. /**
  12685. * material.lightmapTexture as only lighting
  12686. * no light calculation from this light
  12687. * only adds dynamic shadows from this light
  12688. */
  12689. get: function () {
  12690. return Light._LIGHTMAP_SHADOWSONLY;
  12691. },
  12692. enumerable: true,
  12693. configurable: true
  12694. });
  12695. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  12696. get: function () {
  12697. return this._includedOnlyMeshes;
  12698. },
  12699. set: function (value) {
  12700. this._includedOnlyMeshes = value;
  12701. this._hookArrayForIncludedOnly(value);
  12702. },
  12703. enumerable: true,
  12704. configurable: true
  12705. });
  12706. Object.defineProperty(Light.prototype, "excludedMeshes", {
  12707. get: function () {
  12708. return this._excludedMeshes;
  12709. },
  12710. set: function (value) {
  12711. this._excludedMeshes = value;
  12712. this._hookArrayForExcluded(value);
  12713. },
  12714. enumerable: true,
  12715. configurable: true
  12716. });
  12717. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  12718. get: function () {
  12719. return this._excludeWithLayerMask;
  12720. },
  12721. set: function (value) {
  12722. this._excludeWithLayerMask = value;
  12723. this._resyncMeshes();
  12724. },
  12725. enumerable: true,
  12726. configurable: true
  12727. });
  12728. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  12729. get: function () {
  12730. return this._includeOnlyWithLayerMask;
  12731. },
  12732. set: function (value) {
  12733. this._includeOnlyWithLayerMask = value;
  12734. this._resyncMeshes();
  12735. },
  12736. enumerable: true,
  12737. configurable: true
  12738. });
  12739. Object.defineProperty(Light.prototype, "lightmapMode", {
  12740. get: function () {
  12741. return this._lightmapMode;
  12742. },
  12743. set: function (value) {
  12744. if (this._lightmapMode === value) {
  12745. return;
  12746. }
  12747. this._lightmapMode = value;
  12748. this._markMeshesAsLightDirty();
  12749. },
  12750. enumerable: true,
  12751. configurable: true
  12752. });
  12753. Light.prototype._buildUniformLayout = function () {
  12754. // Overridden
  12755. };
  12756. /**
  12757. * Returns the string "Light".
  12758. */
  12759. Light.prototype.getClassName = function () {
  12760. return "Light";
  12761. };
  12762. /**
  12763. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12764. */
  12765. Light.prototype.toString = function (fullDetails) {
  12766. var ret = "Name: " + this.name;
  12767. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  12768. if (this.animations) {
  12769. for (var i = 0; i < this.animations.length; i++) {
  12770. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12771. }
  12772. }
  12773. if (fullDetails) {
  12774. }
  12775. return ret;
  12776. };
  12777. /**
  12778. * Set the enabled state of this node.
  12779. * @param {boolean} value - the new enabled state
  12780. * @see isEnabled
  12781. */
  12782. Light.prototype.setEnabled = function (value) {
  12783. _super.prototype.setEnabled.call(this, value);
  12784. this._resyncMeshes();
  12785. };
  12786. /**
  12787. * Returns the Light associated shadow generator.
  12788. */
  12789. Light.prototype.getShadowGenerator = function () {
  12790. return this._shadowGenerator;
  12791. };
  12792. /**
  12793. * Returns a Vector3, the absolute light position in the World.
  12794. */
  12795. Light.prototype.getAbsolutePosition = function () {
  12796. return BABYLON.Vector3.Zero();
  12797. };
  12798. Light.prototype.transferToEffect = function (effect, lightIndex) {
  12799. };
  12800. Light.prototype._getWorldMatrix = function () {
  12801. return BABYLON.Matrix.Identity();
  12802. };
  12803. /**
  12804. * Boolean : True if the light will affect the passed mesh.
  12805. */
  12806. Light.prototype.canAffectMesh = function (mesh) {
  12807. if (!mesh) {
  12808. return true;
  12809. }
  12810. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  12811. return false;
  12812. }
  12813. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  12814. return false;
  12815. }
  12816. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  12817. return false;
  12818. }
  12819. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  12820. return false;
  12821. }
  12822. return true;
  12823. };
  12824. /**
  12825. * Returns the light World matrix.
  12826. */
  12827. Light.prototype.getWorldMatrix = function () {
  12828. this._currentRenderId = this.getScene().getRenderId();
  12829. var worldMatrix = this._getWorldMatrix();
  12830. if (this.parent && this.parent.getWorldMatrix) {
  12831. if (!this._parentedWorldMatrix) {
  12832. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  12833. }
  12834. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  12835. this._markSyncedWithParent();
  12836. return this._parentedWorldMatrix;
  12837. }
  12838. return worldMatrix;
  12839. };
  12840. /**
  12841. * Disposes the light.
  12842. */
  12843. Light.prototype.dispose = function () {
  12844. if (this._shadowGenerator) {
  12845. this._shadowGenerator.dispose();
  12846. this._shadowGenerator = null;
  12847. }
  12848. // Animations
  12849. this.getScene().stopAnimation(this);
  12850. // Remove from meshes
  12851. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  12852. var mesh = _a[_i];
  12853. mesh._removeLightSource(this);
  12854. }
  12855. this._uniformBuffer.dispose();
  12856. // Remove from scene
  12857. this.getScene().removeLight(this);
  12858. _super.prototype.dispose.call(this);
  12859. };
  12860. /**
  12861. * Returns the light type ID (integer).
  12862. */
  12863. Light.prototype.getTypeID = function () {
  12864. return 0;
  12865. };
  12866. /**
  12867. * Returns a new Light object, named "name", from the current one.
  12868. */
  12869. Light.prototype.clone = function (name) {
  12870. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  12871. };
  12872. /**
  12873. * Serializes the current light into a Serialization object.
  12874. * Returns the serialized object.
  12875. */
  12876. Light.prototype.serialize = function () {
  12877. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12878. // Type
  12879. serializationObject.type = this.getTypeID();
  12880. // Parent
  12881. if (this.parent) {
  12882. serializationObject.parentId = this.parent.id;
  12883. }
  12884. // Inclusion / exclusions
  12885. if (this.excludedMeshes.length > 0) {
  12886. serializationObject.excludedMeshesIds = [];
  12887. this.excludedMeshes.forEach(function (mesh) {
  12888. serializationObject.excludedMeshesIds.push(mesh.id);
  12889. });
  12890. }
  12891. if (this.includedOnlyMeshes.length > 0) {
  12892. serializationObject.includedOnlyMeshesIds = [];
  12893. this.includedOnlyMeshes.forEach(function (mesh) {
  12894. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  12895. });
  12896. }
  12897. // Animations
  12898. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12899. serializationObject.ranges = this.serializeAnimationRanges();
  12900. return serializationObject;
  12901. };
  12902. /**
  12903. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  12904. * This new light is named "name" and added to the passed scene.
  12905. */
  12906. Light.GetConstructorFromName = function (type, name, scene) {
  12907. switch (type) {
  12908. case 0:
  12909. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  12910. case 1:
  12911. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  12912. case 2:
  12913. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  12914. case 3:
  12915. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  12916. }
  12917. };
  12918. /**
  12919. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  12920. */
  12921. Light.Parse = function (parsedLight, scene) {
  12922. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  12923. // Inclusion / exclusions
  12924. if (parsedLight.excludedMeshesIds) {
  12925. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  12926. }
  12927. if (parsedLight.includedOnlyMeshesIds) {
  12928. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  12929. }
  12930. // Parent
  12931. if (parsedLight.parentId) {
  12932. light._waitingParentId = parsedLight.parentId;
  12933. }
  12934. // Animations
  12935. if (parsedLight.animations) {
  12936. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  12937. var parsedAnimation = parsedLight.animations[animationIndex];
  12938. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12939. }
  12940. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  12941. }
  12942. if (parsedLight.autoAnimate) {
  12943. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  12944. }
  12945. return light;
  12946. };
  12947. Light.prototype._hookArrayForExcluded = function (array) {
  12948. var _this = this;
  12949. var oldPush = array.push;
  12950. array.push = function () {
  12951. var items = [];
  12952. for (var _i = 0; _i < arguments.length; _i++) {
  12953. items[_i] = arguments[_i];
  12954. }
  12955. var result = oldPush.apply(array, items);
  12956. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  12957. var item = items_1[_a];
  12958. item._resyncLighSource(_this);
  12959. }
  12960. return result;
  12961. };
  12962. var oldSplice = array.splice;
  12963. array.splice = function (index, deleteCount) {
  12964. var deleted = oldSplice.apply(array, [index, deleteCount]);
  12965. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  12966. var item = deleted_1[_i];
  12967. item._resyncLighSource(_this);
  12968. }
  12969. return deleted;
  12970. };
  12971. };
  12972. Light.prototype._hookArrayForIncludedOnly = function (array) {
  12973. var _this = this;
  12974. var oldPush = array.push;
  12975. array.push = function () {
  12976. var items = [];
  12977. for (var _i = 0; _i < arguments.length; _i++) {
  12978. items[_i] = arguments[_i];
  12979. }
  12980. var result = oldPush.apply(array, items);
  12981. _this._resyncMeshes();
  12982. return result;
  12983. };
  12984. var oldSplice = array.splice;
  12985. array.splice = function (index, deleteCount) {
  12986. var deleted = oldSplice.apply(array, [index, deleteCount]);
  12987. _this._resyncMeshes();
  12988. return deleted;
  12989. };
  12990. };
  12991. Light.prototype._resyncMeshes = function () {
  12992. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  12993. var mesh = _a[_i];
  12994. mesh._resyncLighSource(this);
  12995. }
  12996. };
  12997. Light.prototype._markMeshesAsLightDirty = function () {
  12998. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  12999. var mesh = _a[_i];
  13000. if (mesh._lightSources.indexOf(this) !== -1) {
  13001. mesh._markSubMeshesAsLightDirty();
  13002. }
  13003. }
  13004. };
  13005. return Light;
  13006. }(BABYLON.Node));
  13007. //lightmapMode Consts
  13008. Light._LIGHTMAP_DEFAULT = 0;
  13009. Light._LIGHTMAP_SPECULAR = 1;
  13010. Light._LIGHTMAP_SHADOWSONLY = 2;
  13011. __decorate([
  13012. BABYLON.serializeAsColor3()
  13013. ], Light.prototype, "diffuse", void 0);
  13014. __decorate([
  13015. BABYLON.serializeAsColor3()
  13016. ], Light.prototype, "specular", void 0);
  13017. __decorate([
  13018. BABYLON.serialize()
  13019. ], Light.prototype, "intensity", void 0);
  13020. __decorate([
  13021. BABYLON.serialize()
  13022. ], Light.prototype, "range", void 0);
  13023. __decorate([
  13024. BABYLON.serialize("excludeWithLayerMask")
  13025. ], Light.prototype, "_excludeWithLayerMask", void 0);
  13026. __decorate([
  13027. BABYLON.serialize("includeOnlyWithLayerMask")
  13028. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  13029. __decorate([
  13030. BABYLON.serialize("lightmapMode")
  13031. ], Light.prototype, "_lightmapMode", void 0);
  13032. __decorate([
  13033. BABYLON.serialize()
  13034. ], Light.prototype, "radius", void 0);
  13035. BABYLON.Light = Light;
  13036. })(BABYLON || (BABYLON = {}));
  13037. //# sourceMappingURL=babylon.light.js.map
  13038. var BABYLON;
  13039. (function (BABYLON) {
  13040. var Camera = (function (_super) {
  13041. __extends(Camera, _super);
  13042. function Camera(name, position, scene) {
  13043. var _this = _super.call(this, name, scene) || this;
  13044. _this.upVector = BABYLON.Vector3.Up();
  13045. _this.orthoLeft = null;
  13046. _this.orthoRight = null;
  13047. _this.orthoBottom = null;
  13048. _this.orthoTop = null;
  13049. _this.fov = 0.8;
  13050. _this.minZ = 1.0;
  13051. _this.maxZ = 10000.0;
  13052. _this.inertia = 0.9;
  13053. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13054. _this.isIntermediate = false;
  13055. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13056. _this.layerMask = 0x0FFFFFFF;
  13057. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13058. // Camera rig members
  13059. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13060. _this._rigCameras = new Array();
  13061. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13062. // Cache
  13063. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13064. _this._projectionMatrix = new BABYLON.Matrix();
  13065. _this._doNotComputeProjectionMatrix = false;
  13066. _this._postProcesses = new Array();
  13067. _this._transformMatrix = BABYLON.Matrix.Zero();
  13068. _this._activeMeshes = new BABYLON.SmartArray(256);
  13069. _this._globalPosition = BABYLON.Vector3.Zero();
  13070. _this._refreshFrustumPlanes = true;
  13071. _this.getScene().addCamera(_this);
  13072. if (!_this.getScene().activeCamera) {
  13073. _this.getScene().activeCamera = _this;
  13074. }
  13075. _this.position = position;
  13076. return _this;
  13077. }
  13078. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13079. get: function () {
  13080. return Camera._PERSPECTIVE_CAMERA;
  13081. },
  13082. enumerable: true,
  13083. configurable: true
  13084. });
  13085. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13086. get: function () {
  13087. return Camera._ORTHOGRAPHIC_CAMERA;
  13088. },
  13089. enumerable: true,
  13090. configurable: true
  13091. });
  13092. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13093. get: function () {
  13094. return Camera._FOVMODE_VERTICAL_FIXED;
  13095. },
  13096. enumerable: true,
  13097. configurable: true
  13098. });
  13099. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13100. get: function () {
  13101. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13102. },
  13103. enumerable: true,
  13104. configurable: true
  13105. });
  13106. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13107. get: function () {
  13108. return Camera._RIG_MODE_NONE;
  13109. },
  13110. enumerable: true,
  13111. configurable: true
  13112. });
  13113. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13114. get: function () {
  13115. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13116. },
  13117. enumerable: true,
  13118. configurable: true
  13119. });
  13120. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13121. get: function () {
  13122. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13123. },
  13124. enumerable: true,
  13125. configurable: true
  13126. });
  13127. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13128. get: function () {
  13129. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13130. },
  13131. enumerable: true,
  13132. configurable: true
  13133. });
  13134. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13135. get: function () {
  13136. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13137. },
  13138. enumerable: true,
  13139. configurable: true
  13140. });
  13141. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13142. get: function () {
  13143. return Camera._RIG_MODE_VR;
  13144. },
  13145. enumerable: true,
  13146. configurable: true
  13147. });
  13148. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13149. get: function () {
  13150. return Camera._RIG_MODE_WEBVR;
  13151. },
  13152. enumerable: true,
  13153. configurable: true
  13154. });
  13155. Camera.prototype.getClassName = function () {
  13156. return "Camera";
  13157. };
  13158. /**
  13159. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13160. */
  13161. Camera.prototype.toString = function (fullDetails) {
  13162. var ret = "Name: " + this.name;
  13163. ret += ", type: " + this.getClassName();
  13164. if (this.animations) {
  13165. for (var i = 0; i < this.animations.length; i++) {
  13166. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13167. }
  13168. }
  13169. if (fullDetails) {
  13170. }
  13171. return ret;
  13172. };
  13173. Object.defineProperty(Camera.prototype, "globalPosition", {
  13174. get: function () {
  13175. return this._globalPosition;
  13176. },
  13177. enumerable: true,
  13178. configurable: true
  13179. });
  13180. Camera.prototype.getActiveMeshes = function () {
  13181. return this._activeMeshes;
  13182. };
  13183. Camera.prototype.isActiveMesh = function (mesh) {
  13184. return (this._activeMeshes.indexOf(mesh) !== -1);
  13185. };
  13186. //Cache
  13187. Camera.prototype._initCache = function () {
  13188. _super.prototype._initCache.call(this);
  13189. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13190. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13191. this._cache.mode = undefined;
  13192. this._cache.minZ = undefined;
  13193. this._cache.maxZ = undefined;
  13194. this._cache.fov = undefined;
  13195. this._cache.fovMode = undefined;
  13196. this._cache.aspectRatio = undefined;
  13197. this._cache.orthoLeft = undefined;
  13198. this._cache.orthoRight = undefined;
  13199. this._cache.orthoBottom = undefined;
  13200. this._cache.orthoTop = undefined;
  13201. this._cache.renderWidth = undefined;
  13202. this._cache.renderHeight = undefined;
  13203. };
  13204. Camera.prototype._updateCache = function (ignoreParentClass) {
  13205. if (!ignoreParentClass) {
  13206. _super.prototype._updateCache.call(this);
  13207. }
  13208. var engine = this.getEngine();
  13209. this._cache.position.copyFrom(this.position);
  13210. this._cache.upVector.copyFrom(this.upVector);
  13211. this._cache.mode = this.mode;
  13212. this._cache.minZ = this.minZ;
  13213. this._cache.maxZ = this.maxZ;
  13214. this._cache.fov = this.fov;
  13215. this._cache.fovMode = this.fovMode;
  13216. this._cache.aspectRatio = engine.getAspectRatio(this);
  13217. this._cache.orthoLeft = this.orthoLeft;
  13218. this._cache.orthoRight = this.orthoRight;
  13219. this._cache.orthoBottom = this.orthoBottom;
  13220. this._cache.orthoTop = this.orthoTop;
  13221. this._cache.renderWidth = engine.getRenderWidth();
  13222. this._cache.renderHeight = engine.getRenderHeight();
  13223. };
  13224. Camera.prototype._updateFromScene = function () {
  13225. this.updateCache();
  13226. this.update();
  13227. };
  13228. // Synchronized
  13229. Camera.prototype._isSynchronized = function () {
  13230. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13231. };
  13232. Camera.prototype._isSynchronizedViewMatrix = function () {
  13233. if (!_super.prototype._isSynchronized.call(this))
  13234. return false;
  13235. return this._cache.position.equals(this.position)
  13236. && this._cache.upVector.equals(this.upVector)
  13237. && this.isSynchronizedWithParent();
  13238. };
  13239. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13240. var check = this._cache.mode === this.mode
  13241. && this._cache.minZ === this.minZ
  13242. && this._cache.maxZ === this.maxZ;
  13243. if (!check) {
  13244. return false;
  13245. }
  13246. var engine = this.getEngine();
  13247. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13248. check = this._cache.fov === this.fov
  13249. && this._cache.fovMode === this.fovMode
  13250. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13251. }
  13252. else {
  13253. check = this._cache.orthoLeft === this.orthoLeft
  13254. && this._cache.orthoRight === this.orthoRight
  13255. && this._cache.orthoBottom === this.orthoBottom
  13256. && this._cache.orthoTop === this.orthoTop
  13257. && this._cache.renderWidth === engine.getRenderWidth()
  13258. && this._cache.renderHeight === engine.getRenderHeight();
  13259. }
  13260. return check;
  13261. };
  13262. // Controls
  13263. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13264. };
  13265. Camera.prototype.detachControl = function (element) {
  13266. };
  13267. Camera.prototype.update = function () {
  13268. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13269. this._updateRigCameras();
  13270. }
  13271. this._checkInputs();
  13272. };
  13273. Camera.prototype._checkInputs = function () {
  13274. };
  13275. Object.defineProperty(Camera.prototype, "rigCameras", {
  13276. get: function () {
  13277. return this._rigCameras;
  13278. },
  13279. enumerable: true,
  13280. configurable: true
  13281. });
  13282. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  13283. get: function () {
  13284. return this._rigPostProcess;
  13285. },
  13286. enumerable: true,
  13287. configurable: true
  13288. });
  13289. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13290. // invalidate framebuffer
  13291. if (this._postProcesses.length > 0) {
  13292. this._postProcesses[0].markTextureDirty();
  13293. }
  13294. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13295. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13296. var cam = this._rigCameras[i];
  13297. var rigPostProcess = cam._rigPostProcess;
  13298. // for VR rig, there does not have to be a post process
  13299. if (rigPostProcess) {
  13300. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13301. if (isPass) {
  13302. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13303. cam.isIntermediate = this._postProcesses.length === 0;
  13304. }
  13305. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13306. rigPostProcess.markTextureDirty();
  13307. }
  13308. else {
  13309. cam._postProcesses = this._postProcesses.slice(0);
  13310. }
  13311. }
  13312. };
  13313. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13314. if (insertAt === void 0) { insertAt = null; }
  13315. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13316. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13317. return 0;
  13318. }
  13319. if (insertAt == null || insertAt < 0) {
  13320. this._postProcesses.push(postProcess);
  13321. }
  13322. else {
  13323. this._postProcesses.splice(insertAt, 0, postProcess);
  13324. }
  13325. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13326. return this._postProcesses.indexOf(postProcess);
  13327. };
  13328. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13329. if (atIndices === void 0) { atIndices = null; }
  13330. var result = [];
  13331. var i;
  13332. var index;
  13333. if (!atIndices) {
  13334. var idx = this._postProcesses.indexOf(postProcess);
  13335. if (idx !== -1) {
  13336. this._postProcesses.splice(idx, 1);
  13337. }
  13338. }
  13339. else {
  13340. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13341. // iterate descending, so can just splice as we go
  13342. for (i = atIndices.length - 1; i >= 0; i--) {
  13343. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13344. result.push(i);
  13345. continue;
  13346. }
  13347. index = atIndices[i];
  13348. this._postProcesses.splice(index, 1);
  13349. }
  13350. }
  13351. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13352. return result;
  13353. };
  13354. Camera.prototype.getWorldMatrix = function () {
  13355. if (!this._worldMatrix) {
  13356. this._worldMatrix = BABYLON.Matrix.Identity();
  13357. }
  13358. var viewMatrix = this.getViewMatrix();
  13359. viewMatrix.invertToRef(this._worldMatrix);
  13360. return this._worldMatrix;
  13361. };
  13362. Camera.prototype._getViewMatrix = function () {
  13363. return BABYLON.Matrix.Identity();
  13364. };
  13365. Camera.prototype.getViewMatrix = function (force) {
  13366. this._computedViewMatrix = this._computeViewMatrix(force);
  13367. if (!force && this._isSynchronizedViewMatrix()) {
  13368. return this._computedViewMatrix;
  13369. }
  13370. this._refreshFrustumPlanes = true;
  13371. if (!this.parent || !this.parent.getWorldMatrix) {
  13372. this._globalPosition.copyFrom(this.position);
  13373. }
  13374. else {
  13375. if (!this._worldMatrix) {
  13376. this._worldMatrix = BABYLON.Matrix.Identity();
  13377. }
  13378. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13379. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13380. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13381. this._computedViewMatrix.invert();
  13382. this._markSyncedWithParent();
  13383. }
  13384. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  13385. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  13386. }
  13387. this._currentRenderId = this.getScene().getRenderId();
  13388. return this._computedViewMatrix;
  13389. };
  13390. Camera.prototype._computeViewMatrix = function (force) {
  13391. if (!force && this._isSynchronizedViewMatrix()) {
  13392. return this._computedViewMatrix;
  13393. }
  13394. this._computedViewMatrix = this._getViewMatrix();
  13395. this._currentRenderId = this.getScene().getRenderId();
  13396. return this._computedViewMatrix;
  13397. };
  13398. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13399. this._doNotComputeProjectionMatrix = true;
  13400. if (projection !== undefined) {
  13401. this._projectionMatrix = projection;
  13402. }
  13403. };
  13404. ;
  13405. Camera.prototype.unfreezeProjectionMatrix = function () {
  13406. this._doNotComputeProjectionMatrix = false;
  13407. };
  13408. ;
  13409. Camera.prototype.getProjectionMatrix = function (force) {
  13410. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13411. return this._projectionMatrix;
  13412. }
  13413. this._refreshFrustumPlanes = true;
  13414. var engine = this.getEngine();
  13415. var scene = this.getScene();
  13416. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13417. if (this.minZ <= 0) {
  13418. this.minZ = 0.1;
  13419. }
  13420. if (scene.useRightHandedSystem) {
  13421. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13422. }
  13423. else {
  13424. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13425. }
  13426. return this._projectionMatrix;
  13427. }
  13428. var halfWidth = engine.getRenderWidth() / 2.0;
  13429. var halfHeight = engine.getRenderHeight() / 2.0;
  13430. if (scene.useRightHandedSystem) {
  13431. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13432. }
  13433. else {
  13434. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13435. }
  13436. return this._projectionMatrix;
  13437. };
  13438. Camera.prototype.getTranformationMatrix = function () {
  13439. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13440. return this._transformMatrix;
  13441. };
  13442. Camera.prototype.updateFrustumPlanes = function () {
  13443. if (!this._refreshFrustumPlanes) {
  13444. return;
  13445. }
  13446. this.getTranformationMatrix();
  13447. if (!this._frustumPlanes) {
  13448. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13449. }
  13450. else {
  13451. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13452. }
  13453. this._refreshFrustumPlanes = false;
  13454. };
  13455. Camera.prototype.isInFrustum = function (target) {
  13456. this.updateFrustumPlanes();
  13457. return target.isInFrustum(this._frustumPlanes);
  13458. };
  13459. Camera.prototype.isCompletelyInFrustum = function (target) {
  13460. this.updateFrustumPlanes();
  13461. return target.isCompletelyInFrustum(this._frustumPlanes);
  13462. };
  13463. Camera.prototype.dispose = function () {
  13464. // Animations
  13465. this.getScene().stopAnimation(this);
  13466. // Remove from scene
  13467. this.getScene().removeCamera(this);
  13468. while (this._rigCameras.length > 0) {
  13469. this._rigCameras.pop().dispose();
  13470. }
  13471. // Postprocesses
  13472. var i = this._postProcesses.length;
  13473. while (--i >= 0) {
  13474. this._postProcesses[i].dispose(this);
  13475. }
  13476. _super.prototype.dispose.call(this);
  13477. };
  13478. // ---- Camera rigs section ----
  13479. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13480. while (this._rigCameras.length > 0) {
  13481. this._rigCameras.pop().dispose();
  13482. }
  13483. this.cameraRigMode = mode;
  13484. this._cameraRigParams = {};
  13485. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13486. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13487. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13488. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13489. // create the rig cameras, unless none
  13490. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13491. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13492. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13493. }
  13494. switch (this.cameraRigMode) {
  13495. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13496. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13497. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13498. break;
  13499. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13500. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13501. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13502. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13503. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13504. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13505. break;
  13506. case Camera.RIG_MODE_VR:
  13507. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13508. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13509. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13510. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13511. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13512. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13513. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13514. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13515. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13516. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13517. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13518. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13519. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13520. if (metrics.compensateDistortion) {
  13521. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13522. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13523. }
  13524. break;
  13525. case Camera.RIG_MODE_WEBVR:
  13526. if (rigParams.vrDisplay) {
  13527. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13528. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13529. //Left eye
  13530. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13531. this._rigCameras[0].setCameraRigParameter("left", true);
  13532. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  13533. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  13534. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13535. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  13536. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13537. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13538. this._rigCameras[0].parent = this;
  13539. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13540. //Right eye
  13541. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13542. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  13543. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  13544. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13545. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  13546. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13547. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13548. this._rigCameras[1].parent = this;
  13549. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  13550. }
  13551. break;
  13552. }
  13553. this._cascadePostProcessesToRigCams();
  13554. this.
  13555. update();
  13556. };
  13557. Camera.prototype._getVRProjectionMatrix = function () {
  13558. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13559. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13560. return this._projectionMatrix;
  13561. };
  13562. Camera.prototype._updateCameraRotationMatrix = function () {
  13563. //Here for WebVR
  13564. };
  13565. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  13566. //Here for WebVR
  13567. };
  13568. /**
  13569. * This function MUST be overwritten by the different WebVR cameras available.
  13570. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  13571. */
  13572. Camera.prototype._getWebVRProjectionMatrix = function () {
  13573. return BABYLON.Matrix.Identity();
  13574. };
  13575. /**
  13576. * This function MUST be overwritten by the different WebVR cameras available.
  13577. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  13578. */
  13579. Camera.prototype._getWebVRViewMatrix = function () {
  13580. return BABYLON.Matrix.Identity();
  13581. };
  13582. Camera.prototype.setCameraRigParameter = function (name, value) {
  13583. if (!this._cameraRigParams) {
  13584. this._cameraRigParams = {};
  13585. }
  13586. this._cameraRigParams[name] = value;
  13587. //provisionnally:
  13588. if (name === "interaxialDistance") {
  13589. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13590. }
  13591. };
  13592. /**
  13593. * needs to be overridden by children so sub has required properties to be copied
  13594. */
  13595. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13596. return null;
  13597. };
  13598. /**
  13599. * May need to be overridden by children
  13600. */
  13601. Camera.prototype._updateRigCameras = function () {
  13602. for (var i = 0; i < this._rigCameras.length; i++) {
  13603. this._rigCameras[i].minZ = this.minZ;
  13604. this._rigCameras[i].maxZ = this.maxZ;
  13605. this._rigCameras[i].fov = this.fov;
  13606. }
  13607. // only update viewport when ANAGLYPH
  13608. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13609. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13610. }
  13611. };
  13612. Camera.prototype._setupInputs = function () {
  13613. };
  13614. Camera.prototype.serialize = function () {
  13615. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13616. // Type
  13617. serializationObject.type = this.getClassName();
  13618. // Parent
  13619. if (this.parent) {
  13620. serializationObject.parentId = this.parent.id;
  13621. }
  13622. if (this.inputs) {
  13623. this.inputs.serialize(serializationObject);
  13624. }
  13625. // Animations
  13626. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13627. serializationObject.ranges = this.serializeAnimationRanges();
  13628. return serializationObject;
  13629. };
  13630. Camera.prototype.clone = function (name) {
  13631. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13632. };
  13633. Camera.prototype.getDirection = function (localAxis) {
  13634. var result = BABYLON.Vector3.Zero();
  13635. this.getDirectionToRef(localAxis, result);
  13636. return result;
  13637. };
  13638. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  13639. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13640. };
  13641. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13642. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13643. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13644. switch (type) {
  13645. case "ArcRotateCamera":
  13646. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13647. case "DeviceOrientationCamera":
  13648. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13649. case "FollowCamera":
  13650. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13651. case "ArcFollowCamera":
  13652. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13653. case "GamepadCamera":
  13654. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13655. case "TouchCamera":
  13656. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13657. case "VirtualJoysticksCamera":
  13658. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13659. case "WebVRFreeCamera":
  13660. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13661. case "WebVRGamepadCamera":
  13662. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13663. case "VRDeviceOrientationFreeCamera":
  13664. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13665. case "VRDeviceOrientationGamepadCamera":
  13666. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13667. case "AnaglyphArcRotateCamera":
  13668. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13669. case "AnaglyphFreeCamera":
  13670. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13671. case "AnaglyphGamepadCamera":
  13672. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13673. case "AnaglyphUniversalCamera":
  13674. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13675. case "StereoscopicArcRotateCamera":
  13676. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13677. case "StereoscopicFreeCamera":
  13678. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13679. case "StereoscopicGamepadCamera":
  13680. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13681. case "StereoscopicUniversalCamera":
  13682. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13683. case "FreeCamera":
  13684. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13685. default:
  13686. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13687. }
  13688. };
  13689. Camera.Parse = function (parsedCamera, scene) {
  13690. var type = parsedCamera.type;
  13691. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13692. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13693. // Parent
  13694. if (parsedCamera.parentId) {
  13695. camera._waitingParentId = parsedCamera.parentId;
  13696. }
  13697. //If camera has an input manager, let it parse inputs settings
  13698. if (camera.inputs) {
  13699. camera.inputs.parse(parsedCamera);
  13700. camera._setupInputs();
  13701. }
  13702. // Target
  13703. if (parsedCamera.target) {
  13704. if (camera.setTarget) {
  13705. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13706. }
  13707. }
  13708. // Apply 3d rig, when found
  13709. if (parsedCamera.cameraRigMode) {
  13710. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13711. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13712. }
  13713. // Animations
  13714. if (parsedCamera.animations) {
  13715. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13716. var parsedAnimation = parsedCamera.animations[animationIndex];
  13717. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13718. }
  13719. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13720. }
  13721. if (parsedCamera.autoAnimate) {
  13722. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13723. }
  13724. return camera;
  13725. };
  13726. return Camera;
  13727. }(BABYLON.Node));
  13728. // Statics
  13729. Camera._PERSPECTIVE_CAMERA = 0;
  13730. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13731. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13732. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13733. Camera._RIG_MODE_NONE = 0;
  13734. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13735. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13736. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13737. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13738. Camera._RIG_MODE_VR = 20;
  13739. Camera._RIG_MODE_WEBVR = 21;
  13740. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13741. __decorate([
  13742. BABYLON.serializeAsVector3()
  13743. ], Camera.prototype, "position", void 0);
  13744. __decorate([
  13745. BABYLON.serializeAsVector3()
  13746. ], Camera.prototype, "upVector", void 0);
  13747. __decorate([
  13748. BABYLON.serialize()
  13749. ], Camera.prototype, "orthoLeft", void 0);
  13750. __decorate([
  13751. BABYLON.serialize()
  13752. ], Camera.prototype, "orthoRight", void 0);
  13753. __decorate([
  13754. BABYLON.serialize()
  13755. ], Camera.prototype, "orthoBottom", void 0);
  13756. __decorate([
  13757. BABYLON.serialize()
  13758. ], Camera.prototype, "orthoTop", void 0);
  13759. __decorate([
  13760. BABYLON.serialize()
  13761. ], Camera.prototype, "fov", void 0);
  13762. __decorate([
  13763. BABYLON.serialize()
  13764. ], Camera.prototype, "minZ", void 0);
  13765. __decorate([
  13766. BABYLON.serialize()
  13767. ], Camera.prototype, "maxZ", void 0);
  13768. __decorate([
  13769. BABYLON.serialize()
  13770. ], Camera.prototype, "inertia", void 0);
  13771. __decorate([
  13772. BABYLON.serialize()
  13773. ], Camera.prototype, "mode", void 0);
  13774. __decorate([
  13775. BABYLON.serialize()
  13776. ], Camera.prototype, "layerMask", void 0);
  13777. __decorate([
  13778. BABYLON.serialize()
  13779. ], Camera.prototype, "fovMode", void 0);
  13780. __decorate([
  13781. BABYLON.serialize()
  13782. ], Camera.prototype, "cameraRigMode", void 0);
  13783. __decorate([
  13784. BABYLON.serialize()
  13785. ], Camera.prototype, "interaxialDistance", void 0);
  13786. __decorate([
  13787. BABYLON.serialize()
  13788. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13789. BABYLON.Camera = Camera;
  13790. })(BABYLON || (BABYLON = {}));
  13791. //# sourceMappingURL=babylon.camera.js.map
  13792. var BABYLON;
  13793. (function (BABYLON) {
  13794. var RenderingManager = (function () {
  13795. function RenderingManager(scene) {
  13796. this._renderingGroups = new Array();
  13797. this._autoClearDepthStencil = {};
  13798. this._customOpaqueSortCompareFn = {};
  13799. this._customAlphaTestSortCompareFn = {};
  13800. this._customTransparentSortCompareFn = {};
  13801. this._renderinGroupInfo = null;
  13802. this._scene = scene;
  13803. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  13804. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  13805. }
  13806. }
  13807. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  13808. if (depth === void 0) { depth = true; }
  13809. if (stencil === void 0) { stencil = true; }
  13810. if (this._depthStencilBufferAlreadyCleaned) {
  13811. return;
  13812. }
  13813. this._scene.getEngine().clear(null, false, depth, stencil);
  13814. this._depthStencilBufferAlreadyCleaned = true;
  13815. };
  13816. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  13817. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  13818. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  13819. var info = null;
  13820. if (observable) {
  13821. if (!this._renderinGroupInfo) {
  13822. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  13823. }
  13824. info = this._renderinGroupInfo;
  13825. info.scene = this._scene;
  13826. info.camera = this._scene.activeCamera;
  13827. }
  13828. // Dispatch sprites
  13829. if (renderSprites) {
  13830. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  13831. var manager = this._scene.spriteManagers[index];
  13832. this.dispatchSprites(manager);
  13833. }
  13834. }
  13835. // Render
  13836. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13837. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  13838. var renderingGroup = this._renderingGroups[index];
  13839. if (!renderingGroup && !observable)
  13840. continue;
  13841. this._currentIndex = index;
  13842. var renderingGroupMask = 0;
  13843. // Fire PRECLEAR stage
  13844. if (observable) {
  13845. renderingGroupMask = Math.pow(2, index);
  13846. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  13847. info.renderingGroupId = index;
  13848. observable.notifyObservers(info, renderingGroupMask);
  13849. }
  13850. // Clear depth/stencil if needed
  13851. var autoClear = this._autoClearDepthStencil[index];
  13852. if (autoClear && autoClear.autoClear) {
  13853. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  13854. }
  13855. if (observable) {
  13856. // Fire PREOPAQUE stage
  13857. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  13858. observable.notifyObservers(info, renderingGroupMask);
  13859. // Fire PRETRANSPARENT stage
  13860. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  13861. observable.notifyObservers(info, renderingGroupMask);
  13862. }
  13863. if (renderingGroup)
  13864. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  13865. // Fire POSTTRANSPARENT stage
  13866. if (observable) {
  13867. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  13868. observable.notifyObservers(info, renderingGroupMask);
  13869. }
  13870. }
  13871. };
  13872. RenderingManager.prototype.reset = function () {
  13873. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13874. var renderingGroup = this._renderingGroups[index];
  13875. if (renderingGroup) {
  13876. renderingGroup.prepare();
  13877. }
  13878. }
  13879. };
  13880. RenderingManager.prototype.dispose = function () {
  13881. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  13882. var renderingGroup = this._renderingGroups[index];
  13883. if (renderingGroup) {
  13884. renderingGroup.dispose();
  13885. }
  13886. }
  13887. this._renderingGroups.length = 0;
  13888. };
  13889. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  13890. if (!this._renderingGroups[renderingGroupId]) {
  13891. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  13892. }
  13893. };
  13894. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  13895. var renderingGroupId = spriteManager.renderingGroupId || 0;
  13896. this._prepareRenderingGroup(renderingGroupId);
  13897. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  13898. };
  13899. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  13900. var renderingGroupId = particleSystem.renderingGroupId || 0;
  13901. this._prepareRenderingGroup(renderingGroupId);
  13902. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  13903. };
  13904. RenderingManager.prototype.dispatch = function (subMesh) {
  13905. var mesh = subMesh.getMesh();
  13906. var renderingGroupId = mesh.renderingGroupId || 0;
  13907. this._prepareRenderingGroup(renderingGroupId);
  13908. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  13909. };
  13910. /**
  13911. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  13912. * This allowed control for front to back rendering or reversly depending of the special needs.
  13913. *
  13914. * @param renderingGroupId The rendering group id corresponding to its index
  13915. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  13916. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  13917. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  13918. */
  13919. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  13920. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  13921. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  13922. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  13923. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  13924. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  13925. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  13926. if (this._renderingGroups[renderingGroupId]) {
  13927. var group = this._renderingGroups[renderingGroupId];
  13928. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  13929. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  13930. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  13931. }
  13932. };
  13933. /**
  13934. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  13935. *
  13936. * @param renderingGroupId The rendering group id corresponding to its index
  13937. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  13938. * @param depth Automatically clears depth between groups if true and autoClear is true.
  13939. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  13940. */
  13941. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  13942. if (depth === void 0) { depth = true; }
  13943. if (stencil === void 0) { stencil = true; }
  13944. this._autoClearDepthStencil[renderingGroupId] = {
  13945. autoClear: autoClearDepthStencil,
  13946. depth: depth,
  13947. stencil: stencil
  13948. };
  13949. };
  13950. return RenderingManager;
  13951. }());
  13952. /**
  13953. * The max id used for rendering groups (not included)
  13954. */
  13955. RenderingManager.MAX_RENDERINGGROUPS = 4;
  13956. /**
  13957. * The min id used for rendering groups (included)
  13958. */
  13959. RenderingManager.MIN_RENDERINGGROUPS = 0;
  13960. BABYLON.RenderingManager = RenderingManager;
  13961. })(BABYLON || (BABYLON = {}));
  13962. //# sourceMappingURL=babylon.renderingManager.js.map
  13963. var BABYLON;
  13964. (function (BABYLON) {
  13965. var RenderingGroup = (function () {
  13966. /**
  13967. * Creates a new rendering group.
  13968. * @param index The rendering group index
  13969. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  13970. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  13971. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  13972. */
  13973. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  13974. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  13975. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  13976. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  13977. this.index = index;
  13978. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  13979. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  13980. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  13981. this._particleSystems = new BABYLON.SmartArray(256);
  13982. this._spriteManagers = new BABYLON.SmartArray(256);
  13983. this._scene = scene;
  13984. this.opaqueSortCompareFn = opaqueSortCompareFn;
  13985. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  13986. this.transparentSortCompareFn = transparentSortCompareFn;
  13987. }
  13988. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  13989. /**
  13990. * Set the opaque sort comparison function.
  13991. * If null the sub meshes will be render in the order they were created
  13992. */
  13993. set: function (value) {
  13994. this._opaqueSortCompareFn = value;
  13995. if (value) {
  13996. this._renderOpaque = this.renderOpaqueSorted;
  13997. }
  13998. else {
  13999. this._renderOpaque = RenderingGroup.renderUnsorted;
  14000. }
  14001. },
  14002. enumerable: true,
  14003. configurable: true
  14004. });
  14005. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  14006. /**
  14007. * Set the alpha test sort comparison function.
  14008. * If null the sub meshes will be render in the order they were created
  14009. */
  14010. set: function (value) {
  14011. this._alphaTestSortCompareFn = value;
  14012. if (value) {
  14013. this._renderAlphaTest = this.renderAlphaTestSorted;
  14014. }
  14015. else {
  14016. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  14017. }
  14018. },
  14019. enumerable: true,
  14020. configurable: true
  14021. });
  14022. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  14023. /**
  14024. * Set the transparent sort comparison function.
  14025. * If null the sub meshes will be render in the order they were created
  14026. */
  14027. set: function (value) {
  14028. if (value) {
  14029. this._transparentSortCompareFn = value;
  14030. }
  14031. else {
  14032. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  14033. }
  14034. this._renderTransparent = this.renderTransparentSorted;
  14035. },
  14036. enumerable: true,
  14037. configurable: true
  14038. });
  14039. /**
  14040. * Render all the sub meshes contained in the group.
  14041. * @param customRenderFunction Used to override the default render behaviour of the group.
  14042. * @returns true if rendered some submeshes.
  14043. */
  14044. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  14045. if (customRenderFunction) {
  14046. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  14047. return;
  14048. }
  14049. var engine = this._scene.getEngine();
  14050. // Opaque
  14051. if (this._opaqueSubMeshes.length !== 0) {
  14052. this._renderOpaque(this._opaqueSubMeshes);
  14053. }
  14054. // Alpha test
  14055. if (this._alphaTestSubMeshes.length !== 0) {
  14056. engine.setAlphaTesting(true);
  14057. this._renderAlphaTest(this._alphaTestSubMeshes);
  14058. engine.setAlphaTesting(false);
  14059. }
  14060. var stencilState = engine.getStencilBuffer();
  14061. engine.setStencilBuffer(false);
  14062. // Sprites
  14063. if (renderSprites) {
  14064. this._renderSprites();
  14065. }
  14066. // Particles
  14067. if (renderParticles) {
  14068. this._renderParticles(activeMeshes);
  14069. }
  14070. if (this.onBeforeTransparentRendering) {
  14071. this.onBeforeTransparentRendering();
  14072. }
  14073. // Transparent
  14074. if (this._transparentSubMeshes.length !== 0) {
  14075. this._renderTransparent(this._transparentSubMeshes);
  14076. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14077. }
  14078. engine.setStencilBuffer(stencilState);
  14079. };
  14080. /**
  14081. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  14082. * @param subMeshes The submeshes to render
  14083. */
  14084. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  14085. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14086. };
  14087. /**
  14088. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  14089. * @param subMeshes The submeshes to render
  14090. */
  14091. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  14092. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  14093. };
  14094. /**
  14095. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  14096. * @param subMeshes The submeshes to render
  14097. */
  14098. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  14099. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  14100. };
  14101. /**
  14102. * Renders the submeshes in a specified order.
  14103. * @param subMeshes The submeshes to sort before render
  14104. * @param sortCompareFn The comparison function use to sort
  14105. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  14106. * @param transparent Specifies to activate blending if true
  14107. */
  14108. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  14109. var subIndex = 0;
  14110. var subMesh;
  14111. for (; subIndex < subMeshes.length; subIndex++) {
  14112. subMesh = subMeshes.data[subIndex];
  14113. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  14114. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  14115. }
  14116. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  14117. sortedArray.sort(sortCompareFn);
  14118. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  14119. subMesh = sortedArray[subIndex];
  14120. subMesh.render(transparent);
  14121. }
  14122. };
  14123. /**
  14124. * Renders the submeshes in the order they were dispatched (no sort applied).
  14125. * @param subMeshes The submeshes to render
  14126. */
  14127. RenderingGroup.renderUnsorted = function (subMeshes) {
  14128. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  14129. var submesh = subMeshes.data[subIndex];
  14130. submesh.render(false);
  14131. }
  14132. };
  14133. /**
  14134. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14135. * are rendered back to front if in the same alpha index.
  14136. *
  14137. * @param a The first submesh
  14138. * @param b The second submesh
  14139. * @returns The result of the comparison
  14140. */
  14141. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  14142. // Alpha index first
  14143. if (a._alphaIndex > b._alphaIndex) {
  14144. return 1;
  14145. }
  14146. if (a._alphaIndex < b._alphaIndex) {
  14147. return -1;
  14148. }
  14149. // Then distance to camera
  14150. return RenderingGroup.backToFrontSortCompare(a, b);
  14151. };
  14152. /**
  14153. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14154. * are rendered back to front.
  14155. *
  14156. * @param a The first submesh
  14157. * @param b The second submesh
  14158. * @returns The result of the comparison
  14159. */
  14160. RenderingGroup.backToFrontSortCompare = function (a, b) {
  14161. // Then distance to camera
  14162. if (a._distanceToCamera < b._distanceToCamera) {
  14163. return 1;
  14164. }
  14165. if (a._distanceToCamera > b._distanceToCamera) {
  14166. return -1;
  14167. }
  14168. return 0;
  14169. };
  14170. /**
  14171. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  14172. * are rendered front to back (prevent overdraw).
  14173. *
  14174. * @param a The first submesh
  14175. * @param b The second submesh
  14176. * @returns The result of the comparison
  14177. */
  14178. RenderingGroup.frontToBackSortCompare = function (a, b) {
  14179. // Then distance to camera
  14180. if (a._distanceToCamera < b._distanceToCamera) {
  14181. return -1;
  14182. }
  14183. if (a._distanceToCamera > b._distanceToCamera) {
  14184. return 1;
  14185. }
  14186. return 0;
  14187. };
  14188. /**
  14189. * Resets the different lists of submeshes to prepare a new frame.
  14190. */
  14191. RenderingGroup.prototype.prepare = function () {
  14192. this._opaqueSubMeshes.reset();
  14193. this._transparentSubMeshes.reset();
  14194. this._alphaTestSubMeshes.reset();
  14195. this._particleSystems.reset();
  14196. this._spriteManagers.reset();
  14197. };
  14198. RenderingGroup.prototype.dispose = function () {
  14199. this._opaqueSubMeshes.dispose();
  14200. this._transparentSubMeshes.dispose();
  14201. this._alphaTestSubMeshes.dispose();
  14202. this._particleSystems.dispose();
  14203. this._spriteManagers.dispose();
  14204. };
  14205. /**
  14206. * Inserts the submesh in its correct queue depending on its material.
  14207. * @param subMesh The submesh to dispatch
  14208. */
  14209. RenderingGroup.prototype.dispatch = function (subMesh) {
  14210. var material = subMesh.getMaterial();
  14211. var mesh = subMesh.getMesh();
  14212. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  14213. this._transparentSubMeshes.push(subMesh);
  14214. }
  14215. else if (material.needAlphaTesting()) {
  14216. this._alphaTestSubMeshes.push(subMesh);
  14217. }
  14218. else {
  14219. this._opaqueSubMeshes.push(subMesh); // Opaque
  14220. }
  14221. };
  14222. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  14223. this._spriteManagers.push(spriteManager);
  14224. };
  14225. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  14226. this._particleSystems.push(particleSystem);
  14227. };
  14228. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  14229. if (this._particleSystems.length === 0) {
  14230. return;
  14231. }
  14232. // Particles
  14233. var activeCamera = this._scene.activeCamera;
  14234. this._scene._particlesDuration.beginMonitoring();
  14235. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  14236. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  14237. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  14238. continue;
  14239. }
  14240. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  14241. this._scene._activeParticles.addCount(particleSystem.render(), false);
  14242. }
  14243. }
  14244. this._scene._particlesDuration.endMonitoring(false);
  14245. };
  14246. RenderingGroup.prototype._renderSprites = function () {
  14247. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  14248. return;
  14249. }
  14250. // Sprites
  14251. var activeCamera = this._scene.activeCamera;
  14252. this._scene._spritesDuration.beginMonitoring();
  14253. for (var id = 0; id < this._spriteManagers.length; id++) {
  14254. var spriteManager = this._spriteManagers.data[id];
  14255. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  14256. spriteManager.render();
  14257. }
  14258. }
  14259. this._scene._spritesDuration.endMonitoring(false);
  14260. };
  14261. return RenderingGroup;
  14262. }());
  14263. BABYLON.RenderingGroup = RenderingGroup;
  14264. })(BABYLON || (BABYLON = {}));
  14265. //# sourceMappingURL=babylon.renderingGroup.js.map
  14266. var BABYLON;
  14267. (function (BABYLON) {
  14268. var ClickInfo = (function () {
  14269. function ClickInfo() {
  14270. this._singleClick = false;
  14271. this._doubleClick = false;
  14272. this._hasSwiped = false;
  14273. this._ignore = false;
  14274. }
  14275. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  14276. get: function () {
  14277. return this._singleClick;
  14278. },
  14279. set: function (b) {
  14280. this._singleClick = b;
  14281. },
  14282. enumerable: true,
  14283. configurable: true
  14284. });
  14285. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  14286. get: function () {
  14287. return this._doubleClick;
  14288. },
  14289. set: function (b) {
  14290. this._doubleClick = b;
  14291. },
  14292. enumerable: true,
  14293. configurable: true
  14294. });
  14295. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  14296. get: function () {
  14297. return this._hasSwiped;
  14298. },
  14299. set: function (b) {
  14300. this._hasSwiped = b;
  14301. },
  14302. enumerable: true,
  14303. configurable: true
  14304. });
  14305. Object.defineProperty(ClickInfo.prototype, "ignore", {
  14306. get: function () {
  14307. return this._ignore;
  14308. },
  14309. set: function (b) {
  14310. this._ignore = b;
  14311. },
  14312. enumerable: true,
  14313. configurable: true
  14314. });
  14315. return ClickInfo;
  14316. }());
  14317. var PointerEventTypes = (function () {
  14318. function PointerEventTypes() {
  14319. }
  14320. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  14321. get: function () {
  14322. return PointerEventTypes._POINTERDOWN;
  14323. },
  14324. enumerable: true,
  14325. configurable: true
  14326. });
  14327. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  14328. get: function () {
  14329. return PointerEventTypes._POINTERUP;
  14330. },
  14331. enumerable: true,
  14332. configurable: true
  14333. });
  14334. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  14335. get: function () {
  14336. return PointerEventTypes._POINTERMOVE;
  14337. },
  14338. enumerable: true,
  14339. configurable: true
  14340. });
  14341. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  14342. get: function () {
  14343. return PointerEventTypes._POINTERWHEEL;
  14344. },
  14345. enumerable: true,
  14346. configurable: true
  14347. });
  14348. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  14349. get: function () {
  14350. return PointerEventTypes._POINTERPICK;
  14351. },
  14352. enumerable: true,
  14353. configurable: true
  14354. });
  14355. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  14356. get: function () {
  14357. return PointerEventTypes._POINTERTAP;
  14358. },
  14359. enumerable: true,
  14360. configurable: true
  14361. });
  14362. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  14363. get: function () {
  14364. return PointerEventTypes._POINTERDOUBLETAP;
  14365. },
  14366. enumerable: true,
  14367. configurable: true
  14368. });
  14369. return PointerEventTypes;
  14370. }());
  14371. PointerEventTypes._POINTERDOWN = 0x01;
  14372. PointerEventTypes._POINTERUP = 0x02;
  14373. PointerEventTypes._POINTERMOVE = 0x04;
  14374. PointerEventTypes._POINTERWHEEL = 0x08;
  14375. PointerEventTypes._POINTERPICK = 0x10;
  14376. PointerEventTypes._POINTERTAP = 0x20;
  14377. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  14378. BABYLON.PointerEventTypes = PointerEventTypes;
  14379. var PointerInfoBase = (function () {
  14380. function PointerInfoBase(type, event) {
  14381. this.type = type;
  14382. this.event = event;
  14383. }
  14384. return PointerInfoBase;
  14385. }());
  14386. BABYLON.PointerInfoBase = PointerInfoBase;
  14387. /**
  14388. * This class is used to store pointer related info for the onPrePointerObservable event.
  14389. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  14390. */
  14391. var PointerInfoPre = (function (_super) {
  14392. __extends(PointerInfoPre, _super);
  14393. function PointerInfoPre(type, event, localX, localY) {
  14394. var _this = _super.call(this, type, event) || this;
  14395. _this.skipOnPointerObservable = false;
  14396. _this.localPosition = new BABYLON.Vector2(localX, localY);
  14397. return _this;
  14398. }
  14399. return PointerInfoPre;
  14400. }(PointerInfoBase));
  14401. BABYLON.PointerInfoPre = PointerInfoPre;
  14402. /**
  14403. * This type contains all the data related to a pointer event in Babylon.js.
  14404. * 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.
  14405. */
  14406. var PointerInfo = (function (_super) {
  14407. __extends(PointerInfo, _super);
  14408. function PointerInfo(type, event, pickInfo) {
  14409. var _this = _super.call(this, type, event) || this;
  14410. _this.pickInfo = pickInfo;
  14411. return _this;
  14412. }
  14413. return PointerInfo;
  14414. }(PointerInfoBase));
  14415. BABYLON.PointerInfo = PointerInfo;
  14416. /**
  14417. * This class is used by the onRenderingGroupObservable
  14418. */
  14419. var RenderingGroupInfo = (function () {
  14420. function RenderingGroupInfo() {
  14421. }
  14422. return RenderingGroupInfo;
  14423. }());
  14424. /**
  14425. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  14426. * This stage will be fired no matter what
  14427. */
  14428. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  14429. /**
  14430. * Called before opaque object are rendered.
  14431. * This stage will be fired only if there's 3D Opaque content to render
  14432. */
  14433. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  14434. /**
  14435. * Called after the opaque objects are rendered and before the transparent ones
  14436. * This stage will be fired only if there's 3D transparent content to render
  14437. */
  14438. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  14439. /**
  14440. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  14441. * This stage will be fired no matter what
  14442. */
  14443. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  14444. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  14445. /**
  14446. * Represents a scene to be rendered by the engine.
  14447. * @see http://doc.babylonjs.com/page.php?p=21911
  14448. */
  14449. var Scene = (function () {
  14450. /**
  14451. * @constructor
  14452. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  14453. */
  14454. function Scene(engine) {
  14455. // Members
  14456. this.autoClear = true;
  14457. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  14458. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14459. this.forceWireframe = false;
  14460. this._forcePointsCloud = false;
  14461. this.forceShowBoundingBoxes = false;
  14462. this.animationsEnabled = true;
  14463. this.constantlyUpdateMeshUnderPointer = false;
  14464. this.useRightHandedSystem = false;
  14465. this.hoverCursor = "pointer";
  14466. // Metadata
  14467. this.metadata = null;
  14468. // Events
  14469. /**
  14470. * An event triggered when the scene is disposed.
  14471. * @type {BABYLON.Observable}
  14472. */
  14473. this.onDisposeObservable = new BABYLON.Observable();
  14474. /**
  14475. * An event triggered before rendering the scene
  14476. * @type {BABYLON.Observable}
  14477. */
  14478. this.onBeforeRenderObservable = new BABYLON.Observable();
  14479. /**
  14480. * An event triggered after rendering the scene
  14481. * @type {BABYLON.Observable}
  14482. */
  14483. this.onAfterRenderObservable = new BABYLON.Observable();
  14484. /**
  14485. * An event triggered when the scene is ready
  14486. * @type {BABYLON.Observable}
  14487. */
  14488. this.onReadyObservable = new BABYLON.Observable();
  14489. /**
  14490. * An event triggered before rendering a camera
  14491. * @type {BABYLON.Observable}
  14492. */
  14493. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  14494. /**
  14495. * An event triggered after rendering a camera
  14496. * @type {BABYLON.Observable}
  14497. */
  14498. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  14499. /**
  14500. * An event triggered when a camera is created
  14501. * @type {BABYLON.Observable}
  14502. */
  14503. this.onNewCameraAddedObservable = new BABYLON.Observable();
  14504. /**
  14505. * An event triggered when a camera is removed
  14506. * @type {BABYLON.Observable}
  14507. */
  14508. this.onCameraRemovedObservable = new BABYLON.Observable();
  14509. /**
  14510. * An event triggered when a light is created
  14511. * @type {BABYLON.Observable}
  14512. */
  14513. this.onNewLightAddedObservable = new BABYLON.Observable();
  14514. /**
  14515. * An event triggered when a light is removed
  14516. * @type {BABYLON.Observable}
  14517. */
  14518. this.onLightRemovedObservable = new BABYLON.Observable();
  14519. /**
  14520. * An event triggered when a geometry is created
  14521. * @type {BABYLON.Observable}
  14522. */
  14523. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  14524. /**
  14525. * An event triggered when a geometry is removed
  14526. * @type {BABYLON.Observable}
  14527. */
  14528. this.onGeometryRemovedObservable = new BABYLON.Observable();
  14529. /**
  14530. * An event triggered when a mesh is created
  14531. * @type {BABYLON.Observable}
  14532. */
  14533. this.onNewMeshAddedObservable = new BABYLON.Observable();
  14534. /**
  14535. * An event triggered when a mesh is removed
  14536. * @type {BABYLON.Observable}
  14537. */
  14538. this.onMeshRemovedObservable = new BABYLON.Observable();
  14539. /**
  14540. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  14541. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  14542. * 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)
  14543. */
  14544. this.onRenderingGroupObservable = new BABYLON.Observable();
  14545. // Animations
  14546. this.animations = [];
  14547. /**
  14548. * 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).
  14549. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  14550. */
  14551. this.onPrePointerObservable = new BABYLON.Observable();
  14552. /**
  14553. * Observable event triggered each time an input event is received from the rendering canvas
  14554. */
  14555. this.onPointerObservable = new BABYLON.Observable();
  14556. this._meshPickProceed = false;
  14557. this._previousHasSwiped = false;
  14558. this._currentPickResult = null;
  14559. this._previousPickResult = null;
  14560. this._isButtonPressed = false;
  14561. this._doubleClickOccured = false;
  14562. 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
  14563. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  14564. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  14565. this._startingPointerTime = 0;
  14566. this._previousStartingPointerTime = 0;
  14567. // Fog
  14568. /**
  14569. * is fog enabled on this scene.
  14570. * @type {boolean}
  14571. */
  14572. this._fogEnabled = true;
  14573. this._fogMode = Scene.FOGMODE_NONE;
  14574. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  14575. this.fogDensity = 0.1;
  14576. this.fogStart = 0;
  14577. this.fogEnd = 1000.0;
  14578. // Lights
  14579. /**
  14580. * is shadow enabled on this scene.
  14581. * @type {boolean}
  14582. */
  14583. this._shadowsEnabled = true;
  14584. /**
  14585. * is light enabled on this scene.
  14586. * @type {boolean}
  14587. */
  14588. this._lightsEnabled = true;
  14589. /**
  14590. * All of the lights added to this scene.
  14591. * @see BABYLON.Light
  14592. * @type {BABYLON.Light[]}
  14593. */
  14594. this.lights = new Array();
  14595. // Cameras
  14596. /**
  14597. * All of the cameras added to this scene.
  14598. * @see BABYLON.Camera
  14599. * @type {BABYLON.Camera[]}
  14600. */
  14601. this.cameras = new Array();
  14602. this.activeCameras = new Array();
  14603. // Meshes
  14604. /**
  14605. * All of the (abstract) meshes added to this scene.
  14606. * @see BABYLON.AbstractMesh
  14607. * @type {BABYLON.AbstractMesh[]}
  14608. */
  14609. this.meshes = new Array();
  14610. // Geometries
  14611. this._geometries = new Array();
  14612. this.materials = new Array();
  14613. this.multiMaterials = new Array();
  14614. // Textures
  14615. this._texturesEnabled = true;
  14616. this.textures = new Array();
  14617. // Particles
  14618. this.particlesEnabled = true;
  14619. this.particleSystems = new Array();
  14620. // Sprites
  14621. this.spritesEnabled = true;
  14622. this.spriteManagers = new Array();
  14623. // Layers
  14624. this.layers = new Array();
  14625. this.highlightLayers = new Array();
  14626. // Skeletons
  14627. this._skeletonsEnabled = true;
  14628. this.skeletons = new Array();
  14629. // Morph targets
  14630. this.morphTargetManagers = new Array();
  14631. // Lens flares
  14632. this.lensFlaresEnabled = true;
  14633. this.lensFlareSystems = new Array();
  14634. // Collisions
  14635. this.collisionsEnabled = true;
  14636. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  14637. // Postprocesses
  14638. this.postProcessesEnabled = true;
  14639. // Customs render targets
  14640. this.renderTargetsEnabled = true;
  14641. this.dumpNextRenderTargets = false;
  14642. this.customRenderTargets = new Array();
  14643. // Imported meshes
  14644. this.importedMeshesFiles = new Array();
  14645. // Probes
  14646. this.probesEnabled = true;
  14647. this.reflectionProbes = new Array();
  14648. this._actionManagers = new Array();
  14649. this._meshesForIntersections = new BABYLON.SmartArray(256);
  14650. // Procedural textures
  14651. this.proceduralTexturesEnabled = true;
  14652. this._proceduralTextures = new Array();
  14653. this.soundTracks = new Array();
  14654. this._audioEnabled = true;
  14655. this._headphone = false;
  14656. // Performance counters
  14657. this._totalMeshesCounter = new BABYLON.PerfCounter();
  14658. this._totalLightsCounter = new BABYLON.PerfCounter();
  14659. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  14660. this._totalTexturesCounter = new BABYLON.PerfCounter();
  14661. this._totalVertices = new BABYLON.PerfCounter();
  14662. this._activeIndices = new BABYLON.PerfCounter();
  14663. this._activeParticles = new BABYLON.PerfCounter();
  14664. this._lastFrameDuration = new BABYLON.PerfCounter();
  14665. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  14666. this._renderTargetsDuration = new BABYLON.PerfCounter();
  14667. this._particlesDuration = new BABYLON.PerfCounter();
  14668. this._renderDuration = new BABYLON.PerfCounter();
  14669. this._spritesDuration = new BABYLON.PerfCounter();
  14670. this._activeBones = new BABYLON.PerfCounter();
  14671. this._animationTime = 0;
  14672. this.animationTimeScale = 1;
  14673. this._renderId = 0;
  14674. this._executeWhenReadyTimeoutId = -1;
  14675. this._intermediateRendering = false;
  14676. this._viewUpdateFlag = -1;
  14677. this._projectionUpdateFlag = -1;
  14678. this._toBeDisposed = new BABYLON.SmartArray(256);
  14679. this._pendingData = []; //ANY
  14680. this._activeMeshes = new BABYLON.SmartArray(256);
  14681. this._processedMaterials = new BABYLON.SmartArray(256);
  14682. this._renderTargets = new BABYLON.SmartArray(256);
  14683. this._activeParticleSystems = new BABYLON.SmartArray(256);
  14684. this._activeSkeletons = new BABYLON.SmartArray(32);
  14685. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  14686. this._activeAnimatables = new Array();
  14687. this._transformMatrix = BABYLON.Matrix.Zero();
  14688. this._edgesRenderers = new BABYLON.SmartArray(16);
  14689. this._uniqueIdCounter = 0;
  14690. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  14691. this._engine.scenes.push(this);
  14692. this._uid = null;
  14693. this._renderingManager = new BABYLON.RenderingManager(this);
  14694. this.postProcessManager = new BABYLON.PostProcessManager(this);
  14695. if (BABYLON.OutlineRenderer) {
  14696. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  14697. }
  14698. this.attachControl();
  14699. if (BABYLON.SoundTrack) {
  14700. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  14701. }
  14702. //simplification queue
  14703. if (BABYLON.SimplificationQueue) {
  14704. this.simplificationQueue = new BABYLON.SimplificationQueue();
  14705. }
  14706. //collision coordinator initialization. For now legacy per default.
  14707. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  14708. // Uniform Buffer
  14709. this._createUbo();
  14710. }
  14711. Object.defineProperty(Scene, "FOGMODE_NONE", {
  14712. get: function () {
  14713. return Scene._FOGMODE_NONE;
  14714. },
  14715. enumerable: true,
  14716. configurable: true
  14717. });
  14718. Object.defineProperty(Scene, "FOGMODE_EXP", {
  14719. get: function () {
  14720. return Scene._FOGMODE_EXP;
  14721. },
  14722. enumerable: true,
  14723. configurable: true
  14724. });
  14725. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  14726. get: function () {
  14727. return Scene._FOGMODE_EXP2;
  14728. },
  14729. enumerable: true,
  14730. configurable: true
  14731. });
  14732. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  14733. get: function () {
  14734. return Scene._FOGMODE_LINEAR;
  14735. },
  14736. enumerable: true,
  14737. configurable: true
  14738. });
  14739. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  14740. get: function () {
  14741. return this._forcePointsCloud;
  14742. },
  14743. set: function (value) {
  14744. if (this._forcePointsCloud === value) {
  14745. return;
  14746. }
  14747. this._forcePointsCloud = value;
  14748. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14749. },
  14750. enumerable: true,
  14751. configurable: true
  14752. });
  14753. Object.defineProperty(Scene.prototype, "onDispose", {
  14754. set: function (callback) {
  14755. if (this._onDisposeObserver) {
  14756. this.onDisposeObservable.remove(this._onDisposeObserver);
  14757. }
  14758. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  14759. },
  14760. enumerable: true,
  14761. configurable: true
  14762. });
  14763. Object.defineProperty(Scene.prototype, "beforeRender", {
  14764. set: function (callback) {
  14765. if (this._onBeforeRenderObserver) {
  14766. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  14767. }
  14768. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  14769. },
  14770. enumerable: true,
  14771. configurable: true
  14772. });
  14773. Object.defineProperty(Scene.prototype, "afterRender", {
  14774. set: function (callback) {
  14775. if (this._onAfterRenderObserver) {
  14776. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  14777. }
  14778. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  14779. },
  14780. enumerable: true,
  14781. configurable: true
  14782. });
  14783. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  14784. set: function (callback) {
  14785. if (this._onBeforeCameraRenderObserver) {
  14786. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  14787. }
  14788. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  14789. },
  14790. enumerable: true,
  14791. configurable: true
  14792. });
  14793. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  14794. set: function (callback) {
  14795. if (this._onAfterCameraRenderObserver) {
  14796. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  14797. }
  14798. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  14799. },
  14800. enumerable: true,
  14801. configurable: true
  14802. });
  14803. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  14804. get: function () {
  14805. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  14806. },
  14807. enumerable: true,
  14808. configurable: true
  14809. });
  14810. Object.defineProperty(Scene.prototype, "fogEnabled", {
  14811. get: function () {
  14812. return this._fogEnabled;
  14813. },
  14814. set: function (value) {
  14815. if (this._fogEnabled === value) {
  14816. return;
  14817. }
  14818. this._fogEnabled = value;
  14819. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14820. },
  14821. enumerable: true,
  14822. configurable: true
  14823. });
  14824. Object.defineProperty(Scene.prototype, "fogMode", {
  14825. get: function () {
  14826. return this._fogMode;
  14827. },
  14828. set: function (value) {
  14829. if (this._fogMode === value) {
  14830. return;
  14831. }
  14832. this._fogMode = value;
  14833. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  14834. },
  14835. enumerable: true,
  14836. configurable: true
  14837. });
  14838. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  14839. get: function () {
  14840. return this._shadowsEnabled;
  14841. },
  14842. set: function (value) {
  14843. if (this._shadowsEnabled === value) {
  14844. return;
  14845. }
  14846. this._shadowsEnabled = value;
  14847. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  14848. },
  14849. enumerable: true,
  14850. configurable: true
  14851. });
  14852. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  14853. get: function () {
  14854. return this._lightsEnabled;
  14855. },
  14856. set: function (value) {
  14857. if (this._lightsEnabled === value) {
  14858. return;
  14859. }
  14860. this._lightsEnabled = value;
  14861. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  14862. },
  14863. enumerable: true,
  14864. configurable: true
  14865. });
  14866. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  14867. get: function () {
  14868. if (!this._defaultMaterial) {
  14869. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  14870. }
  14871. return this._defaultMaterial;
  14872. },
  14873. enumerable: true,
  14874. configurable: true
  14875. });
  14876. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  14877. get: function () {
  14878. return this._texturesEnabled;
  14879. },
  14880. set: function (value) {
  14881. if (this._texturesEnabled === value) {
  14882. return;
  14883. }
  14884. this._texturesEnabled = value;
  14885. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  14886. },
  14887. enumerable: true,
  14888. configurable: true
  14889. });
  14890. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  14891. get: function () {
  14892. return this._skeletonsEnabled;
  14893. },
  14894. set: function (value) {
  14895. if (this._skeletonsEnabled === value) {
  14896. return;
  14897. }
  14898. this._skeletonsEnabled = value;
  14899. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  14900. },
  14901. enumerable: true,
  14902. configurable: true
  14903. });
  14904. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  14905. get: function () {
  14906. if (!this._postProcessRenderPipelineManager) {
  14907. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  14908. }
  14909. return this._postProcessRenderPipelineManager;
  14910. },
  14911. enumerable: true,
  14912. configurable: true
  14913. });
  14914. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  14915. get: function () {
  14916. return this._frustumPlanes;
  14917. },
  14918. enumerable: true,
  14919. configurable: true
  14920. });
  14921. Object.defineProperty(Scene.prototype, "debugLayer", {
  14922. // Properties
  14923. get: function () {
  14924. if (!this._debugLayer) {
  14925. this._debugLayer = new BABYLON.DebugLayer(this);
  14926. }
  14927. return this._debugLayer;
  14928. },
  14929. enumerable: true,
  14930. configurable: true
  14931. });
  14932. Object.defineProperty(Scene.prototype, "workerCollisions", {
  14933. get: function () {
  14934. return this._workerCollisions;
  14935. },
  14936. set: function (enabled) {
  14937. if (!BABYLON.CollisionCoordinatorLegacy) {
  14938. return;
  14939. }
  14940. enabled = (enabled && !!Worker);
  14941. this._workerCollisions = enabled;
  14942. if (this.collisionCoordinator) {
  14943. this.collisionCoordinator.destroy();
  14944. }
  14945. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  14946. this.collisionCoordinator.init(this);
  14947. },
  14948. enumerable: true,
  14949. configurable: true
  14950. });
  14951. Object.defineProperty(Scene.prototype, "selectionOctree", {
  14952. get: function () {
  14953. return this._selectionOctree;
  14954. },
  14955. enumerable: true,
  14956. configurable: true
  14957. });
  14958. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  14959. /**
  14960. * The mesh that is currently under the pointer.
  14961. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  14962. */
  14963. get: function () {
  14964. return this._pointerOverMesh;
  14965. },
  14966. enumerable: true,
  14967. configurable: true
  14968. });
  14969. Object.defineProperty(Scene.prototype, "pointerX", {
  14970. /**
  14971. * Current on-screen X position of the pointer
  14972. * @return {number} X position of the pointer
  14973. */
  14974. get: function () {
  14975. return this._pointerX;
  14976. },
  14977. enumerable: true,
  14978. configurable: true
  14979. });
  14980. Object.defineProperty(Scene.prototype, "pointerY", {
  14981. /**
  14982. * Current on-screen Y position of the pointer
  14983. * @return {number} Y position of the pointer
  14984. */
  14985. get: function () {
  14986. return this._pointerY;
  14987. },
  14988. enumerable: true,
  14989. configurable: true
  14990. });
  14991. Scene.prototype.getCachedMaterial = function () {
  14992. return this._cachedMaterial;
  14993. };
  14994. Scene.prototype.getCachedEffect = function () {
  14995. return this._cachedEffect;
  14996. };
  14997. Scene.prototype.getBoundingBoxRenderer = function () {
  14998. if (!this._boundingBoxRenderer) {
  14999. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15000. }
  15001. return this._boundingBoxRenderer;
  15002. };
  15003. Scene.prototype.getOutlineRenderer = function () {
  15004. return this._outlineRenderer;
  15005. };
  15006. Scene.prototype.getEngine = function () {
  15007. return this._engine;
  15008. };
  15009. Scene.prototype.getTotalVertices = function () {
  15010. return this._totalVertices.current;
  15011. };
  15012. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  15013. get: function () {
  15014. return this._totalVertices;
  15015. },
  15016. enumerable: true,
  15017. configurable: true
  15018. });
  15019. Scene.prototype.getActiveIndices = function () {
  15020. return this._activeIndices.current;
  15021. };
  15022. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  15023. get: function () {
  15024. return this._activeIndices;
  15025. },
  15026. enumerable: true,
  15027. configurable: true
  15028. });
  15029. Scene.prototype.getActiveParticles = function () {
  15030. return this._activeParticles.current;
  15031. };
  15032. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  15033. get: function () {
  15034. return this._activeParticles;
  15035. },
  15036. enumerable: true,
  15037. configurable: true
  15038. });
  15039. Scene.prototype.getActiveBones = function () {
  15040. return this._activeBones.current;
  15041. };
  15042. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  15043. get: function () {
  15044. return this._activeBones;
  15045. },
  15046. enumerable: true,
  15047. configurable: true
  15048. });
  15049. // Stats
  15050. Scene.prototype.getLastFrameDuration = function () {
  15051. return this._lastFrameDuration.current;
  15052. };
  15053. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  15054. get: function () {
  15055. return this._lastFrameDuration;
  15056. },
  15057. enumerable: true,
  15058. configurable: true
  15059. });
  15060. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  15061. return this._evaluateActiveMeshesDuration.current;
  15062. };
  15063. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  15064. get: function () {
  15065. return this._evaluateActiveMeshesDuration;
  15066. },
  15067. enumerable: true,
  15068. configurable: true
  15069. });
  15070. Scene.prototype.getActiveMeshes = function () {
  15071. return this._activeMeshes;
  15072. };
  15073. Scene.prototype.getRenderTargetsDuration = function () {
  15074. return this._renderTargetsDuration.current;
  15075. };
  15076. Scene.prototype.getRenderDuration = function () {
  15077. return this._renderDuration.current;
  15078. };
  15079. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  15080. get: function () {
  15081. return this._renderDuration;
  15082. },
  15083. enumerable: true,
  15084. configurable: true
  15085. });
  15086. Scene.prototype.getParticlesDuration = function () {
  15087. return this._particlesDuration.current;
  15088. };
  15089. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  15090. get: function () {
  15091. return this._particlesDuration;
  15092. },
  15093. enumerable: true,
  15094. configurable: true
  15095. });
  15096. Scene.prototype.getSpritesDuration = function () {
  15097. return this._spritesDuration.current;
  15098. };
  15099. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  15100. get: function () {
  15101. return this._spritesDuration;
  15102. },
  15103. enumerable: true,
  15104. configurable: true
  15105. });
  15106. Scene.prototype.getAnimationRatio = function () {
  15107. return this._animationRatio;
  15108. };
  15109. Scene.prototype.getRenderId = function () {
  15110. return this._renderId;
  15111. };
  15112. Scene.prototype.incrementRenderId = function () {
  15113. this._renderId++;
  15114. };
  15115. Scene.prototype._updatePointerPosition = function (evt) {
  15116. var canvasRect = this._engine.getRenderingCanvasClientRect();
  15117. this._pointerX = evt.clientX - canvasRect.left;
  15118. this._pointerY = evt.clientY - canvasRect.top;
  15119. this._unTranslatedPointerX = this._pointerX;
  15120. this._unTranslatedPointerY = this._pointerY;
  15121. if (this.cameraToUseForPointers) {
  15122. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  15123. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  15124. }
  15125. };
  15126. Scene.prototype._createUbo = function () {
  15127. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  15128. this._sceneUbo.addUniform("viewProjection", 16);
  15129. this._sceneUbo.addUniform("view", 16);
  15130. };
  15131. // Pointers handling
  15132. /**
  15133. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  15134. * @param attachUp defines if you want to attach events to pointerup
  15135. * @param attachDown defines if you want to attach events to pointerdown
  15136. * @param attachMove defines if you want to attach events to pointermove
  15137. */
  15138. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  15139. var _this = this;
  15140. if (attachUp === void 0) { attachUp = true; }
  15141. if (attachDown === void 0) { attachDown = true; }
  15142. if (attachMove === void 0) { attachMove = true; }
  15143. this._initActionManager = function (act, clickInfo) {
  15144. if (!_this._meshPickProceed) {
  15145. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15146. _this._currentPickResult = pickResult;
  15147. if (pickResult) {
  15148. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  15149. }
  15150. _this._meshPickProceed = true;
  15151. }
  15152. return act;
  15153. };
  15154. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  15155. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  15156. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  15157. btn !== _this._previousButtonPressed) {
  15158. _this._doubleClickOccured = false;
  15159. clickInfo.singleClick = true;
  15160. clickInfo.ignore = false;
  15161. cb(clickInfo, _this._currentPickResult);
  15162. }
  15163. };
  15164. this._initClickEvent = function (obs1, obs2, evt, cb) {
  15165. var clickInfo = new ClickInfo();
  15166. _this._currentPickResult = null;
  15167. var act;
  15168. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  15169. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  15170. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15171. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  15172. act = _this._initActionManager(act, clickInfo);
  15173. if (act)
  15174. checkPicking = act.hasPickTriggers;
  15175. }
  15176. if (checkPicking) {
  15177. var btn = evt.button;
  15178. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  15179. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  15180. if (!clickInfo.hasSwiped) {
  15181. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  15182. if (!checkSingleClickImmediately) {
  15183. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  15184. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15185. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15186. act = _this._initActionManager(act, clickInfo);
  15187. if (act)
  15188. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  15189. }
  15190. }
  15191. if (checkSingleClickImmediately) {
  15192. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  15193. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  15194. btn !== _this._previousButtonPressed) {
  15195. clickInfo.singleClick = true;
  15196. cb(clickInfo, _this._currentPickResult);
  15197. }
  15198. }
  15199. else {
  15200. // wait that no double click has been raised during the double click delay
  15201. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15202. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  15203. }
  15204. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  15205. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  15206. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15207. act = _this._initActionManager(act, clickInfo);
  15208. if (act)
  15209. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  15210. }
  15211. if (checkDoubleClick) {
  15212. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  15213. if (btn === _this._previousButtonPressed &&
  15214. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  15215. !_this._doubleClickOccured) {
  15216. // pointer has not moved for 2 clicks, it's a double click
  15217. if (!clickInfo.hasSwiped &&
  15218. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  15219. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  15220. _this._previousStartingPointerTime = 0;
  15221. _this._doubleClickOccured = true;
  15222. clickInfo.doubleClick = true;
  15223. clickInfo.ignore = false;
  15224. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  15225. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  15226. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15227. cb(clickInfo, _this._currentPickResult);
  15228. }
  15229. else {
  15230. _this._doubleClickOccured = false;
  15231. _this._previousStartingPointerTime = _this._startingPointerTime;
  15232. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  15233. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  15234. _this._previousButtonPressed = btn;
  15235. _this._previousHasSwiped = clickInfo.hasSwiped;
  15236. if (Scene.ExclusiveDoubleClickMode) {
  15237. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  15238. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  15239. }
  15240. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  15241. cb(clickInfo, _this._previousPickResult);
  15242. }
  15243. else {
  15244. cb(clickInfo, _this._currentPickResult);
  15245. }
  15246. }
  15247. }
  15248. else {
  15249. _this._doubleClickOccured = false;
  15250. _this._previousStartingPointerTime = _this._startingPointerTime;
  15251. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  15252. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  15253. _this._previousButtonPressed = btn;
  15254. _this._previousHasSwiped = clickInfo.hasSwiped;
  15255. }
  15256. }
  15257. }
  15258. }
  15259. clickInfo.ignore = true;
  15260. cb(clickInfo, _this._currentPickResult);
  15261. };
  15262. var spritePredicate = function (sprite) {
  15263. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  15264. };
  15265. this._onPointerMove = function (evt) {
  15266. _this._updatePointerPosition(evt);
  15267. // PreObservable support
  15268. if (_this.onPrePointerObservable.hasObservers()) {
  15269. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15270. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15271. _this.onPrePointerObservable.notifyObservers(pi, type);
  15272. if (pi.skipOnPointerObservable) {
  15273. return;
  15274. }
  15275. }
  15276. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15277. return;
  15278. }
  15279. var canvas = _this._engine.getRenderingCanvas();
  15280. if (!_this.pointerMovePredicate) {
  15281. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  15282. }
  15283. // Meshes
  15284. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  15285. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15286. _this.setPointerOverSprite(null);
  15287. _this.setPointerOverMesh(pickResult.pickedMesh);
  15288. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  15289. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  15290. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  15291. }
  15292. else {
  15293. canvas.style.cursor = _this.hoverCursor;
  15294. }
  15295. }
  15296. else {
  15297. canvas.style.cursor = "";
  15298. }
  15299. }
  15300. else {
  15301. _this.setPointerOverMesh(null);
  15302. // Sprites
  15303. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15304. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  15305. _this.setPointerOverSprite(pickResult.pickedSprite);
  15306. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  15307. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  15308. }
  15309. else {
  15310. canvas.style.cursor = _this.hoverCursor;
  15311. }
  15312. }
  15313. else {
  15314. _this.setPointerOverSprite(null);
  15315. // Restore pointer
  15316. canvas.style.cursor = "";
  15317. }
  15318. }
  15319. if (_this.onPointerMove) {
  15320. _this.onPointerMove(evt, pickResult);
  15321. }
  15322. if (_this.onPointerObservable.hasObservers()) {
  15323. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  15324. var pi = new PointerInfo(type, evt, pickResult);
  15325. _this.onPointerObservable.notifyObservers(pi, type);
  15326. }
  15327. };
  15328. this._onPointerDown = function (evt) {
  15329. _this._isButtonPressed = true;
  15330. _this._pickedDownMesh = null;
  15331. _this._meshPickProceed = false;
  15332. _this._updatePointerPosition(evt);
  15333. // PreObservable support
  15334. if (_this.onPrePointerObservable.hasObservers()) {
  15335. var type = PointerEventTypes.POINTERDOWN;
  15336. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  15337. _this.onPrePointerObservable.notifyObservers(pi, type);
  15338. if (pi.skipOnPointerObservable) {
  15339. return;
  15340. }
  15341. }
  15342. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  15343. return;
  15344. }
  15345. _this._startingPointerPosition.x = _this._pointerX;
  15346. _this._startingPointerPosition.y = _this._pointerY;
  15347. _this._startingPointerTime = new Date().getTime();
  15348. if (!_this.pointerDownPredicate) {
  15349. _this.pointerDownPredicate = function (mesh) {
  15350. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  15351. };
  15352. }
  15353. // Meshes
  15354. _this._pickedDownMesh = null;
  15355. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  15356. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15357. _this._pickedDownMesh = pickResult.pickedMesh;
  15358. var actionManager = pickResult.pickedMesh.actionManager;
  15359. if (actionManager) {
  15360. if (actionManager.hasPickTriggers) {
  15361. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15362. switch (evt.button) {
  15363. case 0:
  15364. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15365. break;
  15366. case 1:
  15367. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15368. break;
  15369. case 2:
  15370. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15371. break;
  15372. }
  15373. }
  15374. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  15375. window.setTimeout((function () {
  15376. var _this = this;
  15377. 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);
  15378. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  15379. if (this._isButtonPressed &&
  15380. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  15381. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  15382. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  15383. this._startingPointerTime = 0;
  15384. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15385. }
  15386. }
  15387. }).bind(_this), Scene.LongPressDelay);
  15388. }
  15389. }
  15390. }
  15391. if (_this.onPointerDown) {
  15392. _this.onPointerDown(evt, pickResult);
  15393. }
  15394. if (_this.onPointerObservable.hasObservers()) {
  15395. var type = PointerEventTypes.POINTERDOWN;
  15396. var pi = new PointerInfo(type, evt, pickResult);
  15397. _this.onPointerObservable.notifyObservers(pi, type);
  15398. }
  15399. // Sprites
  15400. _this._pickedDownSprite = null;
  15401. if (_this.spriteManagers.length > 0) {
  15402. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  15403. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  15404. if (pickResult.pickedSprite.actionManager) {
  15405. _this._pickedDownSprite = pickResult.pickedSprite;
  15406. switch (evt.button) {
  15407. case 0:
  15408. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15409. break;
  15410. case 1:
  15411. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15412. break;
  15413. case 2:
  15414. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15415. break;
  15416. }
  15417. if (pickResult.pickedSprite.actionManager) {
  15418. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  15419. }
  15420. }
  15421. }
  15422. }
  15423. };
  15424. this._onPointerUp = function (evt) {
  15425. _this._isButtonPressed = false;
  15426. _this._pickedUpMesh = null;
  15427. _this._meshPickProceed = false;
  15428. _this._updatePointerPosition(evt);
  15429. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  15430. // PreObservable support
  15431. if (this.onPrePointerObservable.hasObservers()) {
  15432. if (!clickInfo.ignore) {
  15433. if (!clickInfo.hasSwiped) {
  15434. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  15435. var type = PointerEventTypes.POINTERTAP;
  15436. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15437. this.onPrePointerObservable.notifyObservers(pi, type);
  15438. if (pi.skipOnPointerObservable) {
  15439. return;
  15440. }
  15441. }
  15442. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  15443. var type = PointerEventTypes.POINTERDOUBLETAP;
  15444. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15445. this.onPrePointerObservable.notifyObservers(pi, type);
  15446. if (pi.skipOnPointerObservable) {
  15447. return;
  15448. }
  15449. }
  15450. }
  15451. }
  15452. else {
  15453. var type = PointerEventTypes.POINTERUP;
  15454. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  15455. this.onPrePointerObservable.notifyObservers(pi, type);
  15456. if (pi.skipOnPointerObservable) {
  15457. return;
  15458. }
  15459. }
  15460. }
  15461. if (!this.cameraToUseForPointers && !this.activeCamera) {
  15462. return;
  15463. }
  15464. if (!this.pointerUpPredicate) {
  15465. this.pointerUpPredicate = function (mesh) {
  15466. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  15467. };
  15468. }
  15469. // Meshes
  15470. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  15471. this._initActionManager(null, clickInfo);
  15472. }
  15473. if (!pickResult) {
  15474. pickResult = this._currentPickResult;
  15475. }
  15476. if (pickResult && pickResult && pickResult.pickedMesh) {
  15477. this._pickedUpMesh = pickResult.pickedMesh;
  15478. if (this._pickedDownMesh === this._pickedUpMesh) {
  15479. if (this.onPointerPick) {
  15480. this.onPointerPick(evt, pickResult);
  15481. }
  15482. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  15483. var type = PointerEventTypes.POINTERPICK;
  15484. var pi = new PointerInfo(type, evt, pickResult);
  15485. this.onPointerObservable.notifyObservers(pi, type);
  15486. }
  15487. }
  15488. if (pickResult.pickedMesh.actionManager) {
  15489. if (clickInfo.ignore) {
  15490. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15491. }
  15492. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  15493. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15494. }
  15495. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  15496. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  15497. }
  15498. }
  15499. }
  15500. if (this._pickedDownMesh &&
  15501. this._pickedDownMesh.actionManager &&
  15502. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  15503. this._pickedDownMesh !== this._pickedUpMesh) {
  15504. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  15505. }
  15506. if (this.onPointerUp) {
  15507. this.onPointerUp(evt, pickResult);
  15508. }
  15509. if (this.onPointerObservable.hasObservers()) {
  15510. if (!clickInfo.ignore) {
  15511. if (!clickInfo.hasSwiped) {
  15512. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  15513. var type = PointerEventTypes.POINTERTAP;
  15514. var pi = new PointerInfo(type, evt, pickResult);
  15515. this.onPointerObservable.notifyObservers(pi, type);
  15516. }
  15517. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  15518. var type = PointerEventTypes.POINTERDOUBLETAP;
  15519. var pi = new PointerInfo(type, evt, pickResult);
  15520. this.onPointerObservable.notifyObservers(pi, type);
  15521. }
  15522. }
  15523. }
  15524. else {
  15525. var type = PointerEventTypes.POINTERUP;
  15526. var pi = new PointerInfo(type, evt, pickResult);
  15527. this.onPointerObservable.notifyObservers(pi, type);
  15528. }
  15529. }
  15530. // Sprites
  15531. if (this.spriteManagers.length > 0) {
  15532. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  15533. if (pickResult.hit && pickResult.pickedSprite) {
  15534. if (pickResult.pickedSprite.actionManager) {
  15535. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  15536. if (pickResult.pickedSprite.actionManager) {
  15537. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  15538. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  15539. }
  15540. }
  15541. }
  15542. }
  15543. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  15544. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  15545. }
  15546. }
  15547. this._previousPickResult = this._currentPickResult;
  15548. }).bind(_this));
  15549. };
  15550. this._onKeyDown = function (evt) {
  15551. if (_this.actionManager) {
  15552. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15553. }
  15554. };
  15555. this._onKeyUp = function (evt) {
  15556. if (_this.actionManager) {
  15557. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  15558. }
  15559. };
  15560. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15561. var canvas = this._engine.getRenderingCanvas();
  15562. if (attachMove) {
  15563. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  15564. // Wheel
  15565. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  15566. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  15567. }
  15568. if (attachDown) {
  15569. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  15570. }
  15571. if (attachUp) {
  15572. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  15573. }
  15574. canvas.tabIndex = 1;
  15575. canvas.addEventListener("keydown", this._onKeyDown, false);
  15576. canvas.addEventListener("keyup", this._onKeyUp, false);
  15577. };
  15578. Scene.prototype.detachControl = function () {
  15579. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15580. var canvas = this._engine.getRenderingCanvas();
  15581. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  15582. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  15583. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  15584. // Wheel
  15585. canvas.removeEventListener('mousewheel', this._onPointerMove);
  15586. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  15587. canvas.removeEventListener("keydown", this._onKeyDown);
  15588. canvas.removeEventListener("keyup", this._onKeyUp);
  15589. };
  15590. // Ready
  15591. Scene.prototype.isReady = function () {
  15592. if (this._pendingData.length > 0) {
  15593. return false;
  15594. }
  15595. var index;
  15596. // Geometries
  15597. for (index = 0; index < this._geometries.length; index++) {
  15598. var geometry = this._geometries[index];
  15599. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  15600. return false;
  15601. }
  15602. }
  15603. // Meshes
  15604. for (index = 0; index < this.meshes.length; index++) {
  15605. var mesh = this.meshes[index];
  15606. if (!mesh.isEnabled()) {
  15607. continue;
  15608. }
  15609. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  15610. continue;
  15611. }
  15612. if (!mesh.isReady()) {
  15613. return false;
  15614. }
  15615. var mat = mesh.material;
  15616. if (mat) {
  15617. if (!mat.isReady(mesh)) {
  15618. return false;
  15619. }
  15620. }
  15621. }
  15622. return true;
  15623. };
  15624. Scene.prototype.resetCachedMaterial = function () {
  15625. this._cachedMaterial = null;
  15626. this._cachedEffect = null;
  15627. };
  15628. Scene.prototype.registerBeforeRender = function (func) {
  15629. this.onBeforeRenderObservable.add(func);
  15630. };
  15631. Scene.prototype.unregisterBeforeRender = function (func) {
  15632. this.onBeforeRenderObservable.removeCallback(func);
  15633. };
  15634. Scene.prototype.registerAfterRender = function (func) {
  15635. this.onAfterRenderObservable.add(func);
  15636. };
  15637. Scene.prototype.unregisterAfterRender = function (func) {
  15638. this.onAfterRenderObservable.removeCallback(func);
  15639. };
  15640. Scene.prototype._addPendingData = function (data) {
  15641. this._pendingData.push(data);
  15642. };
  15643. Scene.prototype._removePendingData = function (data) {
  15644. var index = this._pendingData.indexOf(data);
  15645. if (index !== -1) {
  15646. this._pendingData.splice(index, 1);
  15647. }
  15648. };
  15649. Scene.prototype.getWaitingItemsCount = function () {
  15650. return this._pendingData.length;
  15651. };
  15652. /**
  15653. * Registers a function to be executed when the scene is ready.
  15654. * @param {Function} func - the function to be executed.
  15655. */
  15656. Scene.prototype.executeWhenReady = function (func) {
  15657. var _this = this;
  15658. this.onReadyObservable.add(func);
  15659. if (this._executeWhenReadyTimeoutId !== -1) {
  15660. return;
  15661. }
  15662. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15663. _this._checkIsReady();
  15664. }, 150);
  15665. };
  15666. Scene.prototype._checkIsReady = function () {
  15667. var _this = this;
  15668. if (this.isReady()) {
  15669. this.onReadyObservable.notifyObservers(this);
  15670. this.onReadyObservable.clear();
  15671. this._executeWhenReadyTimeoutId = -1;
  15672. return;
  15673. }
  15674. this._executeWhenReadyTimeoutId = setTimeout(function () {
  15675. _this._checkIsReady();
  15676. }, 150);
  15677. };
  15678. // Animations
  15679. /**
  15680. * Will start the animation sequence of a given target
  15681. * @param target - the target
  15682. * @param {number} from - from which frame should animation start
  15683. * @param {number} to - till which frame should animation run.
  15684. * @param {boolean} [loop] - should the animation loop
  15685. * @param {number} [speedRatio] - the speed in which to run the animation
  15686. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  15687. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  15688. * @return {BABYLON.Animatable} the animatable object created for this animation
  15689. * @see BABYLON.Animatable
  15690. * @see http://doc.babylonjs.com/page.php?p=22081
  15691. */
  15692. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  15693. if (speedRatio === void 0) { speedRatio = 1.0; }
  15694. this.stopAnimation(target);
  15695. if (!animatable) {
  15696. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  15697. }
  15698. // Local animations
  15699. if (target.animations) {
  15700. animatable.appendAnimations(target, target.animations);
  15701. }
  15702. // Children animations
  15703. if (target.getAnimatables) {
  15704. var animatables = target.getAnimatables();
  15705. for (var index = 0; index < animatables.length; index++) {
  15706. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  15707. }
  15708. }
  15709. animatable.reset();
  15710. return animatable;
  15711. };
  15712. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  15713. if (speedRatio === undefined) {
  15714. speedRatio = 1.0;
  15715. }
  15716. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  15717. return animatable;
  15718. };
  15719. Scene.prototype.getAnimatableByTarget = function (target) {
  15720. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15721. if (this._activeAnimatables[index].target === target) {
  15722. return this._activeAnimatables[index];
  15723. }
  15724. }
  15725. return null;
  15726. };
  15727. Object.defineProperty(Scene.prototype, "Animatables", {
  15728. get: function () {
  15729. return this._activeAnimatables;
  15730. },
  15731. enumerable: true,
  15732. configurable: true
  15733. });
  15734. /**
  15735. * Will stop the animation of the given target
  15736. * @param target - the target
  15737. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  15738. * @see beginAnimation
  15739. */
  15740. Scene.prototype.stopAnimation = function (target, animationName) {
  15741. var animatable = this.getAnimatableByTarget(target);
  15742. if (animatable) {
  15743. animatable.stop(animationName);
  15744. }
  15745. };
  15746. Scene.prototype._animate = function () {
  15747. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  15748. return;
  15749. }
  15750. // Getting time
  15751. var now = BABYLON.Tools.Now;
  15752. if (!this._animationTimeLast) {
  15753. if (this._pendingData.length > 0) {
  15754. return;
  15755. }
  15756. this._animationTimeLast = now;
  15757. }
  15758. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  15759. this._animationTime += deltaTime;
  15760. this._animationTimeLast = now;
  15761. for (var index = 0; index < this._activeAnimatables.length; index++) {
  15762. this._activeAnimatables[index]._animate(this._animationTime);
  15763. }
  15764. };
  15765. // Matrix
  15766. Scene.prototype.getViewMatrix = function () {
  15767. return this._viewMatrix;
  15768. };
  15769. Scene.prototype.getProjectionMatrix = function () {
  15770. return this._projectionMatrix;
  15771. };
  15772. Scene.prototype.getTransformMatrix = function () {
  15773. return this._transformMatrix;
  15774. };
  15775. Scene.prototype.setTransformMatrix = function (view, projection) {
  15776. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  15777. return;
  15778. }
  15779. this._viewUpdateFlag = view.updateFlag;
  15780. this._projectionUpdateFlag = projection.updateFlag;
  15781. this._viewMatrix = view;
  15782. this._projectionMatrix = projection;
  15783. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15784. // Update frustum
  15785. if (!this._frustumPlanes) {
  15786. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15787. }
  15788. else {
  15789. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15790. }
  15791. if (this._sceneUbo.useUbo) {
  15792. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  15793. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  15794. this._sceneUbo.update();
  15795. }
  15796. };
  15797. Scene.prototype.getSceneUniformBuffer = function () {
  15798. return this._sceneUbo;
  15799. };
  15800. // Methods
  15801. Scene.prototype.getUniqueId = function () {
  15802. var result = this._uniqueIdCounter;
  15803. this._uniqueIdCounter++;
  15804. return result;
  15805. };
  15806. Scene.prototype.addMesh = function (newMesh) {
  15807. newMesh.uniqueId = this.getUniqueId();
  15808. var position = this.meshes.push(newMesh);
  15809. //notify the collision coordinator
  15810. if (this.collisionCoordinator) {
  15811. this.collisionCoordinator.onMeshAdded(newMesh);
  15812. }
  15813. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  15814. };
  15815. Scene.prototype.removeMesh = function (toRemove) {
  15816. var index = this.meshes.indexOf(toRemove);
  15817. if (index !== -1) {
  15818. // Remove from the scene if mesh found
  15819. this.meshes.splice(index, 1);
  15820. }
  15821. //notify the collision coordinator
  15822. if (this.collisionCoordinator) {
  15823. this.collisionCoordinator.onMeshRemoved(toRemove);
  15824. }
  15825. this.onMeshRemovedObservable.notifyObservers(toRemove);
  15826. return index;
  15827. };
  15828. Scene.prototype.removeSkeleton = function (toRemove) {
  15829. var index = this.skeletons.indexOf(toRemove);
  15830. if (index !== -1) {
  15831. // Remove from the scene if found
  15832. this.skeletons.splice(index, 1);
  15833. }
  15834. return index;
  15835. };
  15836. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  15837. var index = this.morphTargetManagers.indexOf(toRemove);
  15838. if (index !== -1) {
  15839. // Remove from the scene if found
  15840. this.morphTargetManagers.splice(index, 1);
  15841. }
  15842. return index;
  15843. };
  15844. Scene.prototype.removeLight = function (toRemove) {
  15845. var index = this.lights.indexOf(toRemove);
  15846. if (index !== -1) {
  15847. // Remove from the scene if mesh found
  15848. this.lights.splice(index, 1);
  15849. }
  15850. this.onLightRemovedObservable.notifyObservers(toRemove);
  15851. return index;
  15852. };
  15853. Scene.prototype.removeCamera = function (toRemove) {
  15854. var index = this.cameras.indexOf(toRemove);
  15855. if (index !== -1) {
  15856. // Remove from the scene if mesh found
  15857. this.cameras.splice(index, 1);
  15858. }
  15859. // Remove from activeCameras
  15860. var index2 = this.activeCameras.indexOf(toRemove);
  15861. if (index2 !== -1) {
  15862. // Remove from the scene if mesh found
  15863. this.activeCameras.splice(index2, 1);
  15864. }
  15865. // Reset the activeCamera
  15866. if (this.activeCamera === toRemove) {
  15867. if (this.cameras.length > 0) {
  15868. this.activeCamera = this.cameras[0];
  15869. }
  15870. else {
  15871. this.activeCamera = null;
  15872. }
  15873. }
  15874. this.onCameraRemovedObservable.notifyObservers(toRemove);
  15875. return index;
  15876. };
  15877. Scene.prototype.addLight = function (newLight) {
  15878. newLight.uniqueId = this.getUniqueId();
  15879. var position = this.lights.push(newLight);
  15880. this.onNewLightAddedObservable.notifyObservers(newLight);
  15881. };
  15882. Scene.prototype.addCamera = function (newCamera) {
  15883. newCamera.uniqueId = this.getUniqueId();
  15884. var position = this.cameras.push(newCamera);
  15885. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  15886. };
  15887. /**
  15888. * Switch active camera
  15889. * @param {Camera} newCamera - new active camera
  15890. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  15891. */
  15892. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  15893. if (attachControl === void 0) { attachControl = true; }
  15894. var canvas = this._engine.getRenderingCanvas();
  15895. this.activeCamera.detachControl(canvas);
  15896. this.activeCamera = newCamera;
  15897. if (attachControl) {
  15898. newCamera.attachControl(canvas);
  15899. }
  15900. };
  15901. /**
  15902. * sets the active camera of the scene using its ID
  15903. * @param {string} id - the camera's ID
  15904. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15905. * @see activeCamera
  15906. */
  15907. Scene.prototype.setActiveCameraByID = function (id) {
  15908. var camera = this.getCameraByID(id);
  15909. if (camera) {
  15910. this.activeCamera = camera;
  15911. return camera;
  15912. }
  15913. return null;
  15914. };
  15915. /**
  15916. * sets the active camera of the scene using its name
  15917. * @param {string} name - the camera's name
  15918. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  15919. * @see activeCamera
  15920. */
  15921. Scene.prototype.setActiveCameraByName = function (name) {
  15922. var camera = this.getCameraByName(name);
  15923. if (camera) {
  15924. this.activeCamera = camera;
  15925. return camera;
  15926. }
  15927. return null;
  15928. };
  15929. /**
  15930. * get a material using its id
  15931. * @param {string} the material's ID
  15932. * @return {BABYLON.Material|null} the material or null if none found.
  15933. */
  15934. Scene.prototype.getMaterialByID = function (id) {
  15935. for (var index = 0; index < this.materials.length; index++) {
  15936. if (this.materials[index].id === id) {
  15937. return this.materials[index];
  15938. }
  15939. }
  15940. return null;
  15941. };
  15942. /**
  15943. * get a material using its name
  15944. * @param {string} the material's name
  15945. * @return {BABYLON.Material|null} the material or null if none found.
  15946. */
  15947. Scene.prototype.getMaterialByName = function (name) {
  15948. for (var index = 0; index < this.materials.length; index++) {
  15949. if (this.materials[index].name === name) {
  15950. return this.materials[index];
  15951. }
  15952. }
  15953. return null;
  15954. };
  15955. Scene.prototype.getLensFlareSystemByName = function (name) {
  15956. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15957. if (this.lensFlareSystems[index].name === name) {
  15958. return this.lensFlareSystems[index];
  15959. }
  15960. }
  15961. return null;
  15962. };
  15963. Scene.prototype.getLensFlareSystemByID = function (id) {
  15964. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  15965. if (this.lensFlareSystems[index].id === id) {
  15966. return this.lensFlareSystems[index];
  15967. }
  15968. }
  15969. return null;
  15970. };
  15971. Scene.prototype.getCameraByID = function (id) {
  15972. for (var index = 0; index < this.cameras.length; index++) {
  15973. if (this.cameras[index].id === id) {
  15974. return this.cameras[index];
  15975. }
  15976. }
  15977. return null;
  15978. };
  15979. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  15980. for (var index = 0; index < this.cameras.length; index++) {
  15981. if (this.cameras[index].uniqueId === uniqueId) {
  15982. return this.cameras[index];
  15983. }
  15984. }
  15985. return null;
  15986. };
  15987. /**
  15988. * get a camera using its name
  15989. * @param {string} the camera's name
  15990. * @return {BABYLON.Camera|null} the camera or null if none found.
  15991. */
  15992. Scene.prototype.getCameraByName = function (name) {
  15993. for (var index = 0; index < this.cameras.length; index++) {
  15994. if (this.cameras[index].name === name) {
  15995. return this.cameras[index];
  15996. }
  15997. }
  15998. return null;
  15999. };
  16000. /**
  16001. * get a bone using its id
  16002. * @param {string} the bone's id
  16003. * @return {BABYLON.Bone|null} the bone or null if not found
  16004. */
  16005. Scene.prototype.getBoneByID = function (id) {
  16006. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16007. var skeleton = this.skeletons[skeletonIndex];
  16008. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16009. if (skeleton.bones[boneIndex].id === id) {
  16010. return skeleton.bones[boneIndex];
  16011. }
  16012. }
  16013. }
  16014. return null;
  16015. };
  16016. /**
  16017. * get a bone using its id
  16018. * @param {string} the bone's name
  16019. * @return {BABYLON.Bone|null} the bone or null if not found
  16020. */
  16021. Scene.prototype.getBoneByName = function (name) {
  16022. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16023. var skeleton = this.skeletons[skeletonIndex];
  16024. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16025. if (skeleton.bones[boneIndex].name === name) {
  16026. return skeleton.bones[boneIndex];
  16027. }
  16028. }
  16029. }
  16030. return null;
  16031. };
  16032. /**
  16033. * get a light node using its name
  16034. * @param {string} the light's name
  16035. * @return {BABYLON.Light|null} the light or null if none found.
  16036. */
  16037. Scene.prototype.getLightByName = function (name) {
  16038. for (var index = 0; index < this.lights.length; index++) {
  16039. if (this.lights[index].name === name) {
  16040. return this.lights[index];
  16041. }
  16042. }
  16043. return null;
  16044. };
  16045. /**
  16046. * get a light node using its ID
  16047. * @param {string} the light's id
  16048. * @return {BABYLON.Light|null} the light or null if none found.
  16049. */
  16050. Scene.prototype.getLightByID = function (id) {
  16051. for (var index = 0; index < this.lights.length; index++) {
  16052. if (this.lights[index].id === id) {
  16053. return this.lights[index];
  16054. }
  16055. }
  16056. return null;
  16057. };
  16058. /**
  16059. * get a light node using its scene-generated unique ID
  16060. * @param {number} the light's unique id
  16061. * @return {BABYLON.Light|null} the light or null if none found.
  16062. */
  16063. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16064. for (var index = 0; index < this.lights.length; index++) {
  16065. if (this.lights[index].uniqueId === uniqueId) {
  16066. return this.lights[index];
  16067. }
  16068. }
  16069. return null;
  16070. };
  16071. /**
  16072. * get a particle system by id
  16073. * @param id {number} the particle system id
  16074. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16075. */
  16076. Scene.prototype.getParticleSystemByID = function (id) {
  16077. for (var index = 0; index < this.particleSystems.length; index++) {
  16078. if (this.particleSystems[index].id === id) {
  16079. return this.particleSystems[index];
  16080. }
  16081. }
  16082. return null;
  16083. };
  16084. /**
  16085. * get a geometry using its ID
  16086. * @param {string} the geometry's id
  16087. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16088. */
  16089. Scene.prototype.getGeometryByID = function (id) {
  16090. for (var index = 0; index < this._geometries.length; index++) {
  16091. if (this._geometries[index].id === id) {
  16092. return this._geometries[index];
  16093. }
  16094. }
  16095. return null;
  16096. };
  16097. /**
  16098. * add a new geometry to this scene.
  16099. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16100. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16101. * @return {boolean} was the geometry added or not
  16102. */
  16103. Scene.prototype.pushGeometry = function (geometry, force) {
  16104. if (!force && this.getGeometryByID(geometry.id)) {
  16105. return false;
  16106. }
  16107. this._geometries.push(geometry);
  16108. //notify the collision coordinator
  16109. if (this.collisionCoordinator) {
  16110. this.collisionCoordinator.onGeometryAdded(geometry);
  16111. }
  16112. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16113. return true;
  16114. };
  16115. /**
  16116. * Removes an existing geometry
  16117. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16118. * @return {boolean} was the geometry removed or not
  16119. */
  16120. Scene.prototype.removeGeometry = function (geometry) {
  16121. var index = this._geometries.indexOf(geometry);
  16122. if (index > -1) {
  16123. this._geometries.splice(index, 1);
  16124. //notify the collision coordinator
  16125. if (this.collisionCoordinator) {
  16126. this.collisionCoordinator.onGeometryDeleted(geometry);
  16127. }
  16128. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16129. return true;
  16130. }
  16131. return false;
  16132. };
  16133. Scene.prototype.getGeometries = function () {
  16134. return this._geometries;
  16135. };
  16136. /**
  16137. * Get the first added mesh found of a given ID
  16138. * @param {string} id - the id to search for
  16139. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16140. */
  16141. Scene.prototype.getMeshByID = function (id) {
  16142. for (var index = 0; index < this.meshes.length; index++) {
  16143. if (this.meshes[index].id === id) {
  16144. return this.meshes[index];
  16145. }
  16146. }
  16147. return null;
  16148. };
  16149. Scene.prototype.getMeshesByID = function (id) {
  16150. return this.meshes.filter(function (m) {
  16151. return m.id === id;
  16152. });
  16153. };
  16154. /**
  16155. * Get a mesh with its auto-generated unique id
  16156. * @param {number} uniqueId - the unique id to search for
  16157. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16158. */
  16159. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16160. for (var index = 0; index < this.meshes.length; index++) {
  16161. if (this.meshes[index].uniqueId === uniqueId) {
  16162. return this.meshes[index];
  16163. }
  16164. }
  16165. return null;
  16166. };
  16167. /**
  16168. * Get a the last added mesh found of a given ID
  16169. * @param {string} id - the id to search for
  16170. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16171. */
  16172. Scene.prototype.getLastMeshByID = function (id) {
  16173. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16174. if (this.meshes[index].id === id) {
  16175. return this.meshes[index];
  16176. }
  16177. }
  16178. return null;
  16179. };
  16180. /**
  16181. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16182. * @param {string} id - the id to search for
  16183. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16184. */
  16185. Scene.prototype.getLastEntryByID = function (id) {
  16186. var index;
  16187. for (index = this.meshes.length - 1; index >= 0; index--) {
  16188. if (this.meshes[index].id === id) {
  16189. return this.meshes[index];
  16190. }
  16191. }
  16192. for (index = this.cameras.length - 1; index >= 0; index--) {
  16193. if (this.cameras[index].id === id) {
  16194. return this.cameras[index];
  16195. }
  16196. }
  16197. for (index = this.lights.length - 1; index >= 0; index--) {
  16198. if (this.lights[index].id === id) {
  16199. return this.lights[index];
  16200. }
  16201. }
  16202. return null;
  16203. };
  16204. Scene.prototype.getNodeByID = function (id) {
  16205. var mesh = this.getMeshByID(id);
  16206. if (mesh) {
  16207. return mesh;
  16208. }
  16209. var light = this.getLightByID(id);
  16210. if (light) {
  16211. return light;
  16212. }
  16213. var camera = this.getCameraByID(id);
  16214. if (camera) {
  16215. return camera;
  16216. }
  16217. var bone = this.getBoneByID(id);
  16218. return bone;
  16219. };
  16220. Scene.prototype.getNodeByName = function (name) {
  16221. var mesh = this.getMeshByName(name);
  16222. if (mesh) {
  16223. return mesh;
  16224. }
  16225. var light = this.getLightByName(name);
  16226. if (light) {
  16227. return light;
  16228. }
  16229. var camera = this.getCameraByName(name);
  16230. if (camera) {
  16231. return camera;
  16232. }
  16233. var bone = this.getBoneByName(name);
  16234. return bone;
  16235. };
  16236. Scene.prototype.getMeshByName = function (name) {
  16237. for (var index = 0; index < this.meshes.length; index++) {
  16238. if (this.meshes[index].name === name) {
  16239. return this.meshes[index];
  16240. }
  16241. }
  16242. return null;
  16243. };
  16244. Scene.prototype.getSoundByName = function (name) {
  16245. var index;
  16246. if (BABYLON.AudioEngine) {
  16247. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  16248. if (this.mainSoundTrack.soundCollection[index].name === name) {
  16249. return this.mainSoundTrack.soundCollection[index];
  16250. }
  16251. }
  16252. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  16253. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  16254. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  16255. return this.soundTracks[sdIndex].soundCollection[index];
  16256. }
  16257. }
  16258. }
  16259. }
  16260. return null;
  16261. };
  16262. Scene.prototype.getLastSkeletonByID = function (id) {
  16263. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  16264. if (this.skeletons[index].id === id) {
  16265. return this.skeletons[index];
  16266. }
  16267. }
  16268. return null;
  16269. };
  16270. Scene.prototype.getSkeletonById = function (id) {
  16271. for (var index = 0; index < this.skeletons.length; index++) {
  16272. if (this.skeletons[index].id === id) {
  16273. return this.skeletons[index];
  16274. }
  16275. }
  16276. return null;
  16277. };
  16278. Scene.prototype.getSkeletonByName = function (name) {
  16279. for (var index = 0; index < this.skeletons.length; index++) {
  16280. if (this.skeletons[index].name === name) {
  16281. return this.skeletons[index];
  16282. }
  16283. }
  16284. return null;
  16285. };
  16286. Scene.prototype.getMorphTargetManagerById = function (id) {
  16287. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  16288. if (this.morphTargetManagers[index].uniqueId === id) {
  16289. return this.morphTargetManagers[index];
  16290. }
  16291. }
  16292. return null;
  16293. };
  16294. Scene.prototype.isActiveMesh = function (mesh) {
  16295. return (this._activeMeshes.indexOf(mesh) !== -1);
  16296. };
  16297. /**
  16298. * Return a the first highlight layer of the scene with a given name.
  16299. * @param name The name of the highlight layer to look for.
  16300. * @return The highlight layer if found otherwise null.
  16301. */
  16302. Scene.prototype.getHighlightLayerByName = function (name) {
  16303. for (var index = 0; index < this.highlightLayers.length; index++) {
  16304. if (this.highlightLayers[index].name === name) {
  16305. return this.highlightLayers[index];
  16306. }
  16307. }
  16308. return null;
  16309. };
  16310. Object.defineProperty(Scene.prototype, "uid", {
  16311. /**
  16312. * Return a unique id as a string which can serve as an identifier for the scene
  16313. */
  16314. get: function () {
  16315. if (!this._uid) {
  16316. this._uid = BABYLON.Tools.RandomId();
  16317. }
  16318. return this._uid;
  16319. },
  16320. enumerable: true,
  16321. configurable: true
  16322. });
  16323. /**
  16324. * Add an externaly attached data from its key.
  16325. * This method call will fail and return false, if such key already exists.
  16326. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16327. * @param key the unique key that identifies the data
  16328. * @param data the data object to associate to the key for this Engine instance
  16329. * @return true if no such key were already present and the data was added successfully, false otherwise
  16330. */
  16331. Scene.prototype.addExternalData = function (key, data) {
  16332. if (!this._externalData) {
  16333. this._externalData = new BABYLON.StringDictionary();
  16334. }
  16335. return this._externalData.add(key, data);
  16336. };
  16337. /**
  16338. * Get an externaly attached data from its key
  16339. * @param key the unique key that identifies the data
  16340. * @return the associated data, if present (can be null), or undefined if not present
  16341. */
  16342. Scene.prototype.getExternalData = function (key) {
  16343. if (!this._externalData) {
  16344. return null;
  16345. }
  16346. return this._externalData.get(key);
  16347. };
  16348. /**
  16349. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16350. * @param key the unique key that identifies the data
  16351. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16352. * @return the associated data, can be null if the factory returned null.
  16353. */
  16354. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16355. if (!this._externalData) {
  16356. this._externalData = new BABYLON.StringDictionary();
  16357. }
  16358. return this._externalData.getOrAddWithFactory(key, factory);
  16359. };
  16360. /**
  16361. * Remove an externaly attached data from the Engine instance
  16362. * @param key the unique key that identifies the data
  16363. * @return true if the data was successfully removed, false if it doesn't exist
  16364. */
  16365. Scene.prototype.removeExternalData = function (key) {
  16366. return this._externalData.remove(key);
  16367. };
  16368. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  16369. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  16370. var material = subMesh.getMaterial();
  16371. if (mesh.showSubMeshesBoundingBox) {
  16372. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  16373. }
  16374. if (material) {
  16375. // Render targets
  16376. if (material.getRenderTargetTextures) {
  16377. if (this._processedMaterials.indexOf(material) === -1) {
  16378. this._processedMaterials.push(material);
  16379. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  16380. }
  16381. }
  16382. // Dispatch
  16383. this._activeIndices.addCount(subMesh.indexCount, false);
  16384. this._renderingManager.dispatch(subMesh);
  16385. }
  16386. }
  16387. };
  16388. Scene.prototype._isInIntermediateRendering = function () {
  16389. return this._intermediateRendering;
  16390. };
  16391. Scene.prototype._evaluateActiveMeshes = function () {
  16392. this.activeCamera._activeMeshes.reset();
  16393. this._activeMeshes.reset();
  16394. this._renderingManager.reset();
  16395. this._processedMaterials.reset();
  16396. this._activeParticleSystems.reset();
  16397. this._activeSkeletons.reset();
  16398. this._softwareSkinnedMeshes.reset();
  16399. if (this._boundingBoxRenderer) {
  16400. this._boundingBoxRenderer.reset();
  16401. }
  16402. this._edgesRenderers.reset();
  16403. // Meshes
  16404. var meshes;
  16405. var len;
  16406. if (this._selectionOctree) {
  16407. var selection = this._selectionOctree.select(this._frustumPlanes);
  16408. meshes = selection.data;
  16409. len = selection.length;
  16410. }
  16411. else {
  16412. len = this.meshes.length;
  16413. meshes = this.meshes;
  16414. }
  16415. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  16416. var mesh = meshes[meshIndex];
  16417. if (mesh.isBlocked) {
  16418. continue;
  16419. }
  16420. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  16421. if (!mesh.isReady() || !mesh.isEnabled()) {
  16422. continue;
  16423. }
  16424. mesh.computeWorldMatrix();
  16425. // Intersections
  16426. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  16427. this._meshesForIntersections.pushNoDuplicate(mesh);
  16428. }
  16429. // Switch to current LOD
  16430. var meshLOD = mesh.getLOD(this.activeCamera);
  16431. if (!meshLOD) {
  16432. continue;
  16433. }
  16434. mesh._preActivate();
  16435. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  16436. this._activeMeshes.push(mesh);
  16437. this.activeCamera._activeMeshes.push(mesh);
  16438. mesh._activate(this._renderId);
  16439. this._activeMesh(mesh, meshLOD);
  16440. }
  16441. }
  16442. // Particle systems
  16443. this._particlesDuration.beginMonitoring();
  16444. var beforeParticlesDate = BABYLON.Tools.Now;
  16445. if (this.particlesEnabled) {
  16446. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  16447. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  16448. var particleSystem = this.particleSystems[particleIndex];
  16449. if (!particleSystem.isStarted()) {
  16450. continue;
  16451. }
  16452. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  16453. this._activeParticleSystems.push(particleSystem);
  16454. particleSystem.animate();
  16455. this._renderingManager.dispatchParticles(particleSystem);
  16456. }
  16457. }
  16458. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  16459. }
  16460. this._particlesDuration.endMonitoring(false);
  16461. };
  16462. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  16463. if (mesh.skeleton && this.skeletonsEnabled) {
  16464. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  16465. mesh.skeleton.prepare();
  16466. }
  16467. if (!mesh.computeBonesUsingShaders) {
  16468. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  16469. }
  16470. }
  16471. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  16472. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  16473. }
  16474. if (sourceMesh._edgesRenderer) {
  16475. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  16476. }
  16477. if (mesh && mesh.subMeshes) {
  16478. // Submeshes Octrees
  16479. var len;
  16480. var subMeshes;
  16481. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  16482. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  16483. len = intersections.length;
  16484. subMeshes = intersections.data;
  16485. }
  16486. else {
  16487. subMeshes = mesh.subMeshes;
  16488. len = subMeshes.length;
  16489. }
  16490. for (var subIndex = 0; subIndex < len; subIndex++) {
  16491. var subMesh = subMeshes[subIndex];
  16492. this._evaluateSubMesh(subMesh, mesh);
  16493. }
  16494. }
  16495. };
  16496. Scene.prototype.updateTransformMatrix = function (force) {
  16497. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  16498. };
  16499. Scene.prototype._renderForCamera = function (camera) {
  16500. var engine = this._engine;
  16501. var startTime = BABYLON.Tools.Now;
  16502. this.activeCamera = camera;
  16503. if (!this.activeCamera)
  16504. throw new Error("Active camera not set");
  16505. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16506. // Viewport
  16507. engine.setViewport(this.activeCamera.viewport);
  16508. // Camera
  16509. this.resetCachedMaterial();
  16510. this._renderId++;
  16511. this.updateTransformMatrix();
  16512. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  16513. // Meshes
  16514. this._evaluateActiveMeshesDuration.beginMonitoring();
  16515. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  16516. this._evaluateActiveMeshes();
  16517. this._evaluateActiveMeshesDuration.endMonitoring(false);
  16518. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  16519. // Software skinning
  16520. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  16521. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  16522. mesh.applySkeleton(mesh.skeleton);
  16523. }
  16524. // Render targets
  16525. this._renderTargetsDuration.beginMonitoring();
  16526. var needsRestoreFrameBuffer = false;
  16527. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16528. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  16529. this._intermediateRendering = true;
  16530. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16531. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  16532. var renderTarget = this._renderTargets.data[renderIndex];
  16533. if (renderTarget._shouldRender()) {
  16534. this._renderId++;
  16535. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  16536. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  16537. }
  16538. }
  16539. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  16540. this._intermediateRendering = false;
  16541. this._renderId++;
  16542. needsRestoreFrameBuffer = true; // Restore back buffer
  16543. }
  16544. // Render HighlightLayer Texture
  16545. var stencilState = this._engine.getStencilBuffer();
  16546. var renderhighlights = false;
  16547. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  16548. this._intermediateRendering = true;
  16549. for (var i = 0; i < this.highlightLayers.length; i++) {
  16550. var highlightLayer = this.highlightLayers[i];
  16551. if (highlightLayer.shouldRender() &&
  16552. (!highlightLayer.camera ||
  16553. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  16554. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  16555. renderhighlights = true;
  16556. var renderTarget = highlightLayer._mainTexture;
  16557. if (renderTarget._shouldRender()) {
  16558. this._renderId++;
  16559. renderTarget.render(false, false);
  16560. needsRestoreFrameBuffer = true;
  16561. }
  16562. }
  16563. }
  16564. this._intermediateRendering = false;
  16565. this._renderId++;
  16566. }
  16567. if (needsRestoreFrameBuffer) {
  16568. engine.restoreDefaultFramebuffer();
  16569. }
  16570. this._renderTargetsDuration.endMonitoring(false);
  16571. // Prepare Frame
  16572. this.postProcessManager._prepareFrame();
  16573. this._renderDuration.beginMonitoring();
  16574. // Backgrounds
  16575. var layerIndex;
  16576. var layer;
  16577. if (this.layers.length) {
  16578. engine.setDepthBuffer(false);
  16579. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16580. layer = this.layers[layerIndex];
  16581. if (layer.isBackground) {
  16582. layer.render();
  16583. }
  16584. }
  16585. engine.setDepthBuffer(true);
  16586. }
  16587. // Render
  16588. BABYLON.Tools.StartPerformanceCounter("Main render");
  16589. // Activate HighlightLayer stencil
  16590. if (renderhighlights) {
  16591. this._engine.setStencilBuffer(true);
  16592. }
  16593. this._renderingManager.render(null, null, true, true);
  16594. // Restore HighlightLayer stencil
  16595. if (renderhighlights) {
  16596. this._engine.setStencilBuffer(stencilState);
  16597. }
  16598. BABYLON.Tools.EndPerformanceCounter("Main render");
  16599. // Bounding boxes
  16600. if (this._boundingBoxRenderer) {
  16601. this._boundingBoxRenderer.render();
  16602. }
  16603. // Edges
  16604. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  16605. this._edgesRenderers.data[edgesRendererIndex].render();
  16606. }
  16607. // Lens flares
  16608. if (this.lensFlaresEnabled) {
  16609. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16610. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  16611. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  16612. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  16613. lensFlareSystem.render();
  16614. }
  16615. }
  16616. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  16617. }
  16618. // Foregrounds
  16619. if (this.layers.length) {
  16620. engine.setDepthBuffer(false);
  16621. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  16622. layer = this.layers[layerIndex];
  16623. if (!layer.isBackground) {
  16624. layer.render();
  16625. }
  16626. }
  16627. engine.setDepthBuffer(true);
  16628. }
  16629. // Highlight Layer
  16630. if (renderhighlights) {
  16631. engine.setDepthBuffer(false);
  16632. for (var i = 0; i < this.highlightLayers.length; i++) {
  16633. if (this.highlightLayers[i].shouldRender()) {
  16634. this.highlightLayers[i].render();
  16635. }
  16636. }
  16637. engine.setDepthBuffer(true);
  16638. }
  16639. this._renderDuration.endMonitoring(false);
  16640. // Finalize frame
  16641. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  16642. // Update camera
  16643. this.activeCamera._updateFromScene();
  16644. // Reset some special arrays
  16645. this._renderTargets.reset();
  16646. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  16647. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  16648. };
  16649. Scene.prototype._processSubCameras = function (camera) {
  16650. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  16651. this._renderForCamera(camera);
  16652. return;
  16653. }
  16654. // rig cameras
  16655. for (var index = 0; index < camera._rigCameras.length; index++) {
  16656. this._renderForCamera(camera._rigCameras[index]);
  16657. }
  16658. this.activeCamera = camera;
  16659. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  16660. // Update camera
  16661. this.activeCamera._updateFromScene();
  16662. };
  16663. Scene.prototype._checkIntersections = function () {
  16664. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  16665. var sourceMesh = this._meshesForIntersections.data[index];
  16666. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  16667. var action = sourceMesh.actionManager.actions[actionIndex];
  16668. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16669. var parameters = action.getTriggerParameter();
  16670. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  16671. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  16672. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  16673. if (areIntersecting && currentIntersectionInProgress === -1) {
  16674. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  16675. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16676. sourceMesh._intersectionsInProgress.push(otherMesh);
  16677. }
  16678. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16679. sourceMesh._intersectionsInProgress.push(otherMesh);
  16680. }
  16681. }
  16682. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  16683. //They intersected, and now they don't.
  16684. //is this trigger an exit trigger? execute an event.
  16685. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16686. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  16687. }
  16688. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  16689. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  16690. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  16691. }
  16692. }
  16693. }
  16694. }
  16695. }
  16696. };
  16697. Scene.prototype.render = function () {
  16698. if (this.isDisposed) {
  16699. return;
  16700. }
  16701. this._lastFrameDuration.beginMonitoring();
  16702. this._particlesDuration.fetchNewFrame();
  16703. this._spritesDuration.fetchNewFrame();
  16704. this._activeParticles.fetchNewFrame();
  16705. this._renderDuration.fetchNewFrame();
  16706. this._renderTargetsDuration.fetchNewFrame();
  16707. this._evaluateActiveMeshesDuration.fetchNewFrame();
  16708. this._totalVertices.fetchNewFrame();
  16709. this._activeIndices.fetchNewFrame();
  16710. this._activeBones.fetchNewFrame();
  16711. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  16712. this._meshesForIntersections.reset();
  16713. this.resetCachedMaterial();
  16714. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  16715. // Actions
  16716. if (this.actionManager) {
  16717. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  16718. }
  16719. //Simplification Queue
  16720. if (this.simplificationQueue && !this.simplificationQueue.running) {
  16721. this.simplificationQueue.executeNext();
  16722. }
  16723. // Animations
  16724. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  16725. this._animationRatio = deltaTime * (60.0 / 1000.0);
  16726. this._animate();
  16727. // Physics
  16728. if (this._physicsEngine) {
  16729. BABYLON.Tools.StartPerformanceCounter("Physics");
  16730. this._physicsEngine._step(deltaTime / 1000.0);
  16731. BABYLON.Tools.EndPerformanceCounter("Physics");
  16732. }
  16733. // Before render
  16734. this.onBeforeRenderObservable.notifyObservers(this);
  16735. // Customs render targets
  16736. this._renderTargetsDuration.beginMonitoring();
  16737. var beforeRenderTargetDate = BABYLON.Tools.Now;
  16738. var engine = this.getEngine();
  16739. var currentActiveCamera = this.activeCamera;
  16740. if (this.renderTargetsEnabled) {
  16741. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16742. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  16743. var renderTarget = this.customRenderTargets[customIndex];
  16744. if (renderTarget._shouldRender()) {
  16745. this._renderId++;
  16746. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  16747. if (!this.activeCamera)
  16748. throw new Error("Active camera not set");
  16749. // Viewport
  16750. engine.setViewport(this.activeCamera.viewport);
  16751. // Camera
  16752. this.updateTransformMatrix();
  16753. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  16754. }
  16755. }
  16756. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  16757. this._renderId++;
  16758. }
  16759. if (this.customRenderTargets.length > 0) {
  16760. engine.restoreDefaultFramebuffer();
  16761. }
  16762. this._renderTargetsDuration.endMonitoring();
  16763. this.activeCamera = currentActiveCamera;
  16764. // Procedural textures
  16765. if (this.proceduralTexturesEnabled) {
  16766. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16767. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  16768. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  16769. if (proceduralTexture._shouldRender()) {
  16770. proceduralTexture.render();
  16771. }
  16772. }
  16773. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  16774. }
  16775. // Clear
  16776. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  16777. // Shadows
  16778. if (this.shadowsEnabled) {
  16779. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  16780. var light = this.lights[lightIndex];
  16781. var shadowGenerator = light.getShadowGenerator();
  16782. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  16783. this._renderTargets.push(shadowGenerator.getShadowMap());
  16784. }
  16785. }
  16786. }
  16787. // Depth renderer
  16788. if (this._depthRenderer) {
  16789. this._renderTargets.push(this._depthRenderer.getDepthMap());
  16790. }
  16791. // RenderPipeline
  16792. if (this._postProcessRenderPipelineManager) {
  16793. this._postProcessRenderPipelineManager.update();
  16794. }
  16795. // Multi-cameras?
  16796. if (this.activeCameras.length > 0) {
  16797. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  16798. if (cameraIndex > 0) {
  16799. this._engine.clear(null, false, true, true);
  16800. }
  16801. this._processSubCameras(this.activeCameras[cameraIndex]);
  16802. }
  16803. }
  16804. else {
  16805. if (!this.activeCamera) {
  16806. throw new Error("No camera defined");
  16807. }
  16808. this._processSubCameras(this.activeCamera);
  16809. }
  16810. // Intersection checks
  16811. this._checkIntersections();
  16812. // Update the audio listener attached to the camera
  16813. if (BABYLON.AudioEngine) {
  16814. this._updateAudioParameters();
  16815. }
  16816. // After render
  16817. if (this.afterRender) {
  16818. this.afterRender();
  16819. }
  16820. this.onAfterRenderObservable.notifyObservers(this);
  16821. // Cleaning
  16822. for (var index = 0; index < this._toBeDisposed.length; index++) {
  16823. this._toBeDisposed.data[index].dispose();
  16824. this._toBeDisposed[index] = null;
  16825. }
  16826. this._toBeDisposed.reset();
  16827. if (this.dumpNextRenderTargets) {
  16828. this.dumpNextRenderTargets = false;
  16829. }
  16830. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  16831. this._lastFrameDuration.endMonitoring();
  16832. this._totalMeshesCounter.addCount(this.meshes.length, true);
  16833. this._totalLightsCounter.addCount(this.lights.length, true);
  16834. this._totalMaterialsCounter.addCount(this.materials.length, true);
  16835. this._totalTexturesCounter.addCount(this.textures.length, true);
  16836. this._activeBones.addCount(0, true);
  16837. this._activeIndices.addCount(0, true);
  16838. this._activeParticles.addCount(0, true);
  16839. };
  16840. Scene.prototype._updateAudioParameters = function () {
  16841. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  16842. return;
  16843. }
  16844. var listeningCamera;
  16845. var audioEngine = BABYLON.Engine.audioEngine;
  16846. if (this.activeCameras.length > 0) {
  16847. listeningCamera = this.activeCameras[0];
  16848. }
  16849. else {
  16850. listeningCamera = this.activeCamera;
  16851. }
  16852. if (listeningCamera && audioEngine.canUseWebAudio) {
  16853. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  16854. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  16855. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  16856. cameraDirection.normalize();
  16857. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  16858. var i;
  16859. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16860. var sound = this.mainSoundTrack.soundCollection[i];
  16861. if (sound.useCustomAttenuation) {
  16862. sound.updateDistanceFromListener();
  16863. }
  16864. }
  16865. for (i = 0; i < this.soundTracks.length; i++) {
  16866. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16867. sound = this.soundTracks[i].soundCollection[j];
  16868. if (sound.useCustomAttenuation) {
  16869. sound.updateDistanceFromListener();
  16870. }
  16871. }
  16872. }
  16873. }
  16874. };
  16875. Object.defineProperty(Scene.prototype, "audioEnabled", {
  16876. // Audio
  16877. get: function () {
  16878. return this._audioEnabled;
  16879. },
  16880. set: function (value) {
  16881. this._audioEnabled = value;
  16882. if (BABYLON.AudioEngine) {
  16883. if (this._audioEnabled) {
  16884. this._enableAudio();
  16885. }
  16886. else {
  16887. this._disableAudio();
  16888. }
  16889. }
  16890. },
  16891. enumerable: true,
  16892. configurable: true
  16893. });
  16894. Scene.prototype._disableAudio = function () {
  16895. var i;
  16896. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16897. this.mainSoundTrack.soundCollection[i].pause();
  16898. }
  16899. for (i = 0; i < this.soundTracks.length; i++) {
  16900. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16901. this.soundTracks[i].soundCollection[j].pause();
  16902. }
  16903. }
  16904. };
  16905. Scene.prototype._enableAudio = function () {
  16906. var i;
  16907. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  16908. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  16909. this.mainSoundTrack.soundCollection[i].play();
  16910. }
  16911. }
  16912. for (i = 0; i < this.soundTracks.length; i++) {
  16913. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  16914. if (this.soundTracks[i].soundCollection[j].isPaused) {
  16915. this.soundTracks[i].soundCollection[j].play();
  16916. }
  16917. }
  16918. }
  16919. };
  16920. Object.defineProperty(Scene.prototype, "headphone", {
  16921. get: function () {
  16922. return this._headphone;
  16923. },
  16924. set: function (value) {
  16925. this._headphone = value;
  16926. if (BABYLON.AudioEngine) {
  16927. if (this._headphone) {
  16928. this._switchAudioModeForHeadphones();
  16929. }
  16930. else {
  16931. this._switchAudioModeForNormalSpeakers();
  16932. }
  16933. }
  16934. },
  16935. enumerable: true,
  16936. configurable: true
  16937. });
  16938. Scene.prototype._switchAudioModeForHeadphones = function () {
  16939. this.mainSoundTrack.switchPanningModelToHRTF();
  16940. for (var i = 0; i < this.soundTracks.length; i++) {
  16941. this.soundTracks[i].switchPanningModelToHRTF();
  16942. }
  16943. };
  16944. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  16945. this.mainSoundTrack.switchPanningModelToEqualPower();
  16946. for (var i = 0; i < this.soundTracks.length; i++) {
  16947. this.soundTracks[i].switchPanningModelToEqualPower();
  16948. }
  16949. };
  16950. Scene.prototype.enableDepthRenderer = function () {
  16951. if (this._depthRenderer) {
  16952. return this._depthRenderer;
  16953. }
  16954. this._depthRenderer = new BABYLON.DepthRenderer(this);
  16955. return this._depthRenderer;
  16956. };
  16957. Scene.prototype.disableDepthRenderer = function () {
  16958. if (!this._depthRenderer) {
  16959. return;
  16960. }
  16961. this._depthRenderer.dispose();
  16962. this._depthRenderer = null;
  16963. };
  16964. Scene.prototype.freezeMaterials = function () {
  16965. for (var i = 0; i < this.materials.length; i++) {
  16966. this.materials[i].freeze();
  16967. }
  16968. };
  16969. Scene.prototype.unfreezeMaterials = function () {
  16970. for (var i = 0; i < this.materials.length; i++) {
  16971. this.materials[i].unfreeze();
  16972. }
  16973. };
  16974. Scene.prototype.dispose = function () {
  16975. this.beforeRender = null;
  16976. this.afterRender = null;
  16977. this.skeletons = [];
  16978. this.morphTargetManagers = [];
  16979. if (this._depthRenderer) {
  16980. this._depthRenderer.dispose();
  16981. }
  16982. // Smart arrays
  16983. if (this.activeCamera) {
  16984. this.activeCamera._activeMeshes.dispose();
  16985. this.activeCamera = null;
  16986. }
  16987. this._activeMeshes.dispose();
  16988. this._renderingManager.dispose();
  16989. this._processedMaterials.dispose();
  16990. this._activeParticleSystems.dispose();
  16991. this._activeSkeletons.dispose();
  16992. this._softwareSkinnedMeshes.dispose();
  16993. if (this._boundingBoxRenderer) {
  16994. this._boundingBoxRenderer.dispose();
  16995. }
  16996. this._edgesRenderers.dispose();
  16997. this._meshesForIntersections.dispose();
  16998. this._toBeDisposed.dispose();
  16999. // Debug layer
  17000. if (this._debugLayer) {
  17001. this._debugLayer.hide();
  17002. }
  17003. // Events
  17004. this.onDisposeObservable.notifyObservers(this);
  17005. this.onDisposeObservable.clear();
  17006. this.onBeforeRenderObservable.clear();
  17007. this.onAfterRenderObservable.clear();
  17008. this.detachControl();
  17009. // Release sounds & sounds tracks
  17010. if (BABYLON.AudioEngine) {
  17011. this.disposeSounds();
  17012. }
  17013. // Detach cameras
  17014. var canvas = this._engine.getRenderingCanvas();
  17015. var index;
  17016. for (index = 0; index < this.cameras.length; index++) {
  17017. this.cameras[index].detachControl(canvas);
  17018. }
  17019. // Release lights
  17020. while (this.lights.length) {
  17021. this.lights[0].dispose();
  17022. }
  17023. // Release meshes
  17024. while (this.meshes.length) {
  17025. this.meshes[0].dispose(true);
  17026. }
  17027. // Release cameras
  17028. while (this.cameras.length) {
  17029. this.cameras[0].dispose();
  17030. }
  17031. // Release materials
  17032. while (this.materials.length) {
  17033. this.materials[0].dispose();
  17034. }
  17035. // Release particles
  17036. while (this.particleSystems.length) {
  17037. this.particleSystems[0].dispose();
  17038. }
  17039. // Release sprites
  17040. while (this.spriteManagers.length) {
  17041. this.spriteManagers[0].dispose();
  17042. }
  17043. // Release layers
  17044. while (this.layers.length) {
  17045. this.layers[0].dispose();
  17046. }
  17047. while (this.highlightLayers.length) {
  17048. this.highlightLayers[0].dispose();
  17049. }
  17050. // Release textures
  17051. while (this.textures.length) {
  17052. this.textures[0].dispose();
  17053. }
  17054. // Release UBO
  17055. this._sceneUbo.dispose();
  17056. // Post-processes
  17057. this.postProcessManager.dispose();
  17058. // Physics
  17059. if (this._physicsEngine) {
  17060. this.disablePhysicsEngine();
  17061. }
  17062. // Remove from engine
  17063. index = this._engine.scenes.indexOf(this);
  17064. if (index > -1) {
  17065. this._engine.scenes.splice(index, 1);
  17066. }
  17067. this._engine.wipeCaches();
  17068. this._engine = null;
  17069. };
  17070. Object.defineProperty(Scene.prototype, "isDisposed", {
  17071. get: function () {
  17072. return !this._engine;
  17073. },
  17074. enumerable: true,
  17075. configurable: true
  17076. });
  17077. // Release sounds & sounds tracks
  17078. Scene.prototype.disposeSounds = function () {
  17079. this.mainSoundTrack.dispose();
  17080. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17081. this.soundTracks[scIndex].dispose();
  17082. }
  17083. };
  17084. // Octrees
  17085. Scene.prototype.getWorldExtends = function () {
  17086. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17087. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17088. for (var index = 0; index < this.meshes.length; index++) {
  17089. var mesh = this.meshes[index];
  17090. mesh.computeWorldMatrix(true);
  17091. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17092. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17093. BABYLON.Tools.CheckExtends(minBox, min, max);
  17094. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17095. }
  17096. return {
  17097. min: min,
  17098. max: max
  17099. };
  17100. };
  17101. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17102. if (maxCapacity === void 0) { maxCapacity = 64; }
  17103. if (maxDepth === void 0) { maxDepth = 2; }
  17104. if (!this._selectionOctree) {
  17105. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17106. }
  17107. var worldExtends = this.getWorldExtends();
  17108. // Update octree
  17109. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17110. return this._selectionOctree;
  17111. };
  17112. // Picking
  17113. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17114. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17115. var engine = this._engine;
  17116. if (!camera) {
  17117. if (!this.activeCamera)
  17118. throw new Error("Active camera not set");
  17119. camera = this.activeCamera;
  17120. }
  17121. var cameraViewport = camera.viewport;
  17122. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17123. // Moving coordinates to local viewport world
  17124. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17125. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17126. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17127. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17128. };
  17129. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17130. if (!BABYLON.PickingInfo) {
  17131. return null;
  17132. }
  17133. var engine = this._engine;
  17134. if (!camera) {
  17135. if (!this.activeCamera)
  17136. throw new Error("Active camera not set");
  17137. camera = this.activeCamera;
  17138. }
  17139. var cameraViewport = camera.viewport;
  17140. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17141. var identity = BABYLON.Matrix.Identity();
  17142. // Moving coordinates to local viewport world
  17143. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17144. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17145. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17146. };
  17147. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17148. if (!BABYLON.PickingInfo) {
  17149. return null;
  17150. }
  17151. var pickingInfo = null;
  17152. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17153. var mesh = this.meshes[meshIndex];
  17154. if (predicate) {
  17155. if (!predicate(mesh)) {
  17156. continue;
  17157. }
  17158. }
  17159. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17160. continue;
  17161. }
  17162. var world = mesh.getWorldMatrix();
  17163. var ray = rayFunction(world);
  17164. var result = mesh.intersects(ray, fastCheck);
  17165. if (!result || !result.hit)
  17166. continue;
  17167. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17168. continue;
  17169. pickingInfo = result;
  17170. if (fastCheck) {
  17171. break;
  17172. }
  17173. }
  17174. return pickingInfo || new BABYLON.PickingInfo();
  17175. };
  17176. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  17177. if (!BABYLON.PickingInfo) {
  17178. return null;
  17179. }
  17180. var pickingInfos = new Array();
  17181. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17182. var mesh = this.meshes[meshIndex];
  17183. if (predicate) {
  17184. if (!predicate(mesh)) {
  17185. continue;
  17186. }
  17187. }
  17188. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17189. continue;
  17190. }
  17191. var world = mesh.getWorldMatrix();
  17192. var ray = rayFunction(world);
  17193. var result = mesh.intersects(ray, false);
  17194. if (!result || !result.hit)
  17195. continue;
  17196. pickingInfos.push(result);
  17197. }
  17198. return pickingInfos;
  17199. };
  17200. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17201. if (!BABYLON.PickingInfo) {
  17202. return null;
  17203. }
  17204. var pickingInfo = null;
  17205. camera = camera || this.activeCamera;
  17206. if (this.spriteManagers.length > 0) {
  17207. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17208. var spriteManager = this.spriteManagers[spriteIndex];
  17209. if (!spriteManager.isPickable) {
  17210. continue;
  17211. }
  17212. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17213. if (!result || !result.hit)
  17214. continue;
  17215. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17216. continue;
  17217. pickingInfo = result;
  17218. if (fastCheck) {
  17219. break;
  17220. }
  17221. }
  17222. }
  17223. return pickingInfo || new BABYLON.PickingInfo();
  17224. };
  17225. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17226. /// <param name="x">X position on screen</param>
  17227. /// <param name="y">Y position on screen</param>
  17228. /// <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>
  17229. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17230. /// <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>
  17231. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17232. var _this = this;
  17233. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17234. };
  17235. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17236. /// <param name="x">X position on screen</param>
  17237. /// <param name="y">Y position on screen</param>
  17238. /// <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>
  17239. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17240. /// <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>
  17241. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17242. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17243. };
  17244. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17245. var _this = this;
  17246. return this._internalPick(function (world) {
  17247. if (!_this._pickWithRayInverseMatrix) {
  17248. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17249. }
  17250. world.invertToRef(_this._pickWithRayInverseMatrix);
  17251. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17252. }, predicate, fastCheck);
  17253. };
  17254. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17255. /// <param name="x">X position on screen</param>
  17256. /// <param name="y">Y position on screen</param>
  17257. /// <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>
  17258. /// <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>
  17259. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  17260. var _this = this;
  17261. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  17262. };
  17263. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17264. /// <param name="ray">Ray to use</param>
  17265. /// <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>
  17266. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  17267. var _this = this;
  17268. return this._internalMultiPick(function (world) {
  17269. if (!_this._pickWithRayInverseMatrix) {
  17270. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17271. }
  17272. world.invertToRef(_this._pickWithRayInverseMatrix);
  17273. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17274. }, predicate);
  17275. };
  17276. Scene.prototype.setPointerOverMesh = function (mesh) {
  17277. if (this._pointerOverMesh === mesh) {
  17278. return;
  17279. }
  17280. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17281. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17282. }
  17283. this._pointerOverMesh = mesh;
  17284. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17285. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17286. }
  17287. };
  17288. Scene.prototype.getPointerOverMesh = function () {
  17289. return this._pointerOverMesh;
  17290. };
  17291. Scene.prototype.setPointerOverSprite = function (sprite) {
  17292. if (this._pointerOverSprite === sprite) {
  17293. return;
  17294. }
  17295. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17296. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17297. }
  17298. this._pointerOverSprite = sprite;
  17299. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17300. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17301. }
  17302. };
  17303. Scene.prototype.getPointerOverSprite = function () {
  17304. return this._pointerOverSprite;
  17305. };
  17306. // Physics
  17307. Scene.prototype.getPhysicsEngine = function () {
  17308. return this._physicsEngine;
  17309. };
  17310. /**
  17311. * Enables physics to the current scene
  17312. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17313. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17314. * @return {boolean} was the physics engine initialized
  17315. */
  17316. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17317. if (this._physicsEngine) {
  17318. return true;
  17319. }
  17320. try {
  17321. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17322. return true;
  17323. }
  17324. catch (e) {
  17325. BABYLON.Tools.Error(e.message);
  17326. return false;
  17327. }
  17328. };
  17329. Scene.prototype.disablePhysicsEngine = function () {
  17330. if (!this._physicsEngine) {
  17331. return;
  17332. }
  17333. this._physicsEngine.dispose();
  17334. this._physicsEngine = undefined;
  17335. };
  17336. Scene.prototype.isPhysicsEnabled = function () {
  17337. return this._physicsEngine !== undefined;
  17338. };
  17339. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17340. var mesh = compound.parts[0].mesh;
  17341. mesh.physicsImpostor.dispose();
  17342. mesh.physicsImpostor = null;
  17343. };
  17344. // Misc.
  17345. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  17346. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  17347. // Light
  17348. if (this.lights.length === 0) {
  17349. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17350. }
  17351. // Camera
  17352. if (!this.activeCamera) {
  17353. // Compute position
  17354. var worldExtends = this.getWorldExtends();
  17355. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  17356. var camera;
  17357. if (createArcRotateCamera) {
  17358. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  17359. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  17360. camera.lowerRadiusLimit = 0.5;
  17361. camera.setTarget(worldCenter);
  17362. }
  17363. else {
  17364. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  17365. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  17366. camera.setTarget(worldCenter);
  17367. }
  17368. camera.minZ = 0.1;
  17369. var maxDist = worldExtends.max.subtract(worldExtends.min).length();
  17370. camera.wheelPrecision = 100.0 / maxDist;
  17371. this.activeCamera = camera;
  17372. }
  17373. };
  17374. // Tags
  17375. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17376. if (tagsQuery === undefined) {
  17377. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17378. return list;
  17379. }
  17380. var listByTags = [];
  17381. forEach = forEach || (function (item) { return; });
  17382. for (var i in list) {
  17383. var item = list[i];
  17384. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17385. listByTags.push(item);
  17386. forEach(item);
  17387. }
  17388. }
  17389. return listByTags;
  17390. };
  17391. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17392. return this._getByTags(this.meshes, tagsQuery, forEach);
  17393. };
  17394. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17395. return this._getByTags(this.cameras, tagsQuery, forEach);
  17396. };
  17397. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17398. return this._getByTags(this.lights, tagsQuery, forEach);
  17399. };
  17400. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17401. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17402. };
  17403. /**
  17404. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17405. * This allowed control for front to back rendering or reversly depending of the special needs.
  17406. *
  17407. * @param renderingGroupId The rendering group id corresponding to its index
  17408. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17409. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17410. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17411. */
  17412. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17413. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17414. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17415. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17416. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  17417. };
  17418. /**
  17419. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17420. *
  17421. * @param renderingGroupId The rendering group id corresponding to its index
  17422. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17423. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17424. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17425. */
  17426. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17427. if (depth === void 0) { depth = true; }
  17428. if (stencil === void 0) { stencil = true; }
  17429. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  17430. };
  17431. /**
  17432. * Will flag all materials as dirty to trigger new shader compilation
  17433. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  17434. */
  17435. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  17436. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  17437. var material = _a[_i];
  17438. if (predicate && !predicate(material)) {
  17439. continue;
  17440. }
  17441. material.markAsDirty(flag);
  17442. }
  17443. };
  17444. return Scene;
  17445. }());
  17446. // Statics
  17447. Scene._FOGMODE_NONE = 0;
  17448. Scene._FOGMODE_EXP = 1;
  17449. Scene._FOGMODE_EXP2 = 2;
  17450. Scene._FOGMODE_LINEAR = 3;
  17451. Scene.MinDeltaTime = 1.0;
  17452. Scene.MaxDeltaTime = 1000.0;
  17453. Scene.DragMovementThreshold = 10; // in pixels
  17454. Scene.LongPressDelay = 500; // in milliseconds
  17455. Scene.DoubleClickDelay = 300; // in milliseconds
  17456. Scene.ExclusiveDoubleClickMode = false; // If you need to check double click without raising a single click at first click, enable this flag
  17457. BABYLON.Scene = Scene;
  17458. })(BABYLON || (BABYLON = {}));
  17459. //# sourceMappingURL=babylon.scene.js.map
  17460. var BABYLON;
  17461. (function (BABYLON) {
  17462. var Buffer = (function () {
  17463. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  17464. if (engine instanceof BABYLON.Mesh) {
  17465. this._engine = engine.getScene().getEngine();
  17466. }
  17467. else {
  17468. this._engine = engine;
  17469. }
  17470. this._updatable = updatable;
  17471. this._data = data;
  17472. this._strideSize = stride;
  17473. if (!postponeInternalCreation) {
  17474. this.create();
  17475. }
  17476. this._instanced = instanced;
  17477. }
  17478. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  17479. // a lot of these parameters are ignored as they are overriden by the buffer
  17480. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  17481. };
  17482. // Properties
  17483. Buffer.prototype.isUpdatable = function () {
  17484. return this._updatable;
  17485. };
  17486. Buffer.prototype.getData = function () {
  17487. return this._data;
  17488. };
  17489. Buffer.prototype.getBuffer = function () {
  17490. return this._buffer;
  17491. };
  17492. Buffer.prototype.getStrideSize = function () {
  17493. return this._strideSize;
  17494. };
  17495. Buffer.prototype.getIsInstanced = function () {
  17496. return this._instanced;
  17497. };
  17498. // Methods
  17499. Buffer.prototype.create = function (data) {
  17500. if (!data && this._buffer) {
  17501. return; // nothing to do
  17502. }
  17503. data = data || this._data;
  17504. if (!this._buffer) {
  17505. if (this._updatable) {
  17506. this._buffer = this._engine.createDynamicVertexBuffer(data);
  17507. this._data = data;
  17508. }
  17509. else {
  17510. this._buffer = this._engine.createVertexBuffer(data);
  17511. }
  17512. }
  17513. else if (this._updatable) {
  17514. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  17515. this._data = data;
  17516. }
  17517. };
  17518. Buffer.prototype.update = function (data) {
  17519. this.create(data);
  17520. };
  17521. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  17522. if (!this._buffer) {
  17523. return;
  17524. }
  17525. if (this._updatable) {
  17526. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  17527. this._data = null;
  17528. }
  17529. };
  17530. Buffer.prototype.dispose = function () {
  17531. if (!this._buffer) {
  17532. return;
  17533. }
  17534. if (this._engine._releaseBuffer(this._buffer)) {
  17535. this._buffer = null;
  17536. }
  17537. };
  17538. return Buffer;
  17539. }());
  17540. BABYLON.Buffer = Buffer;
  17541. })(BABYLON || (BABYLON = {}));
  17542. //# sourceMappingURL=babylon.buffer.js.map
  17543. var BABYLON;
  17544. (function (BABYLON) {
  17545. var VertexBuffer = (function () {
  17546. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  17547. if (!stride) {
  17548. // Deduce stride from kind
  17549. switch (kind) {
  17550. case VertexBuffer.PositionKind:
  17551. stride = 3;
  17552. break;
  17553. case VertexBuffer.NormalKind:
  17554. stride = 3;
  17555. break;
  17556. case VertexBuffer.UVKind:
  17557. case VertexBuffer.UV2Kind:
  17558. case VertexBuffer.UV3Kind:
  17559. case VertexBuffer.UV4Kind:
  17560. case VertexBuffer.UV5Kind:
  17561. case VertexBuffer.UV6Kind:
  17562. stride = 2;
  17563. break;
  17564. case VertexBuffer.TangentKind:
  17565. case VertexBuffer.ColorKind:
  17566. stride = 4;
  17567. break;
  17568. case VertexBuffer.MatricesIndicesKind:
  17569. case VertexBuffer.MatricesIndicesExtraKind:
  17570. stride = 4;
  17571. break;
  17572. case VertexBuffer.MatricesWeightsKind:
  17573. case VertexBuffer.MatricesWeightsExtraKind:
  17574. stride = 4;
  17575. break;
  17576. }
  17577. }
  17578. if (data instanceof BABYLON.Buffer) {
  17579. if (!stride) {
  17580. stride = data.getStrideSize();
  17581. }
  17582. this._buffer = data;
  17583. this._ownsBuffer = false;
  17584. }
  17585. else {
  17586. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  17587. this._ownsBuffer = true;
  17588. }
  17589. this._stride = stride;
  17590. this._offset = offset ? offset : 0;
  17591. this._size = size ? size : stride;
  17592. this._kind = kind;
  17593. }
  17594. /**
  17595. * Returns the kind of the VertexBuffer (string).
  17596. */
  17597. VertexBuffer.prototype.getKind = function () {
  17598. return this._kind;
  17599. };
  17600. // Properties
  17601. /**
  17602. * Boolean : is the VertexBuffer updatable ?
  17603. */
  17604. VertexBuffer.prototype.isUpdatable = function () {
  17605. return this._buffer.isUpdatable();
  17606. };
  17607. /**
  17608. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  17609. */
  17610. VertexBuffer.prototype.getData = function () {
  17611. return this._buffer.getData();
  17612. };
  17613. /**
  17614. * Returns the WebGLBuffer associated to the VertexBuffer.
  17615. */
  17616. VertexBuffer.prototype.getBuffer = function () {
  17617. return this._buffer.getBuffer();
  17618. };
  17619. /**
  17620. * Returns the stride of the VertexBuffer (integer).
  17621. */
  17622. VertexBuffer.prototype.getStrideSize = function () {
  17623. return this._stride;
  17624. };
  17625. /**
  17626. * Returns the offset (integer).
  17627. */
  17628. VertexBuffer.prototype.getOffset = function () {
  17629. return this._offset;
  17630. };
  17631. /**
  17632. * Returns the VertexBuffer total size (integer).
  17633. */
  17634. VertexBuffer.prototype.getSize = function () {
  17635. return this._size;
  17636. };
  17637. /**
  17638. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  17639. */
  17640. VertexBuffer.prototype.getIsInstanced = function () {
  17641. return this._buffer.getIsInstanced();
  17642. };
  17643. // Methods
  17644. /**
  17645. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  17646. * Returns the created WebGLBuffer.
  17647. */
  17648. VertexBuffer.prototype.create = function (data) {
  17649. return this._buffer.create(data);
  17650. };
  17651. /**
  17652. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  17653. * Returns the updated WebGLBuffer.
  17654. */
  17655. VertexBuffer.prototype.update = function (data) {
  17656. return this._buffer.update(data);
  17657. };
  17658. /**
  17659. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  17660. * Returns the directly updated WebGLBuffer.
  17661. */
  17662. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  17663. return this._buffer.updateDirectly(data, offset);
  17664. };
  17665. /**
  17666. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  17667. */
  17668. VertexBuffer.prototype.dispose = function () {
  17669. if (this._ownsBuffer) {
  17670. this._buffer.dispose();
  17671. }
  17672. };
  17673. Object.defineProperty(VertexBuffer, "PositionKind", {
  17674. get: function () {
  17675. return VertexBuffer._PositionKind;
  17676. },
  17677. enumerable: true,
  17678. configurable: true
  17679. });
  17680. Object.defineProperty(VertexBuffer, "NormalKind", {
  17681. get: function () {
  17682. return VertexBuffer._NormalKind;
  17683. },
  17684. enumerable: true,
  17685. configurable: true
  17686. });
  17687. Object.defineProperty(VertexBuffer, "TangentKind", {
  17688. get: function () {
  17689. return VertexBuffer._TangentKind;
  17690. },
  17691. enumerable: true,
  17692. configurable: true
  17693. });
  17694. Object.defineProperty(VertexBuffer, "UVKind", {
  17695. get: function () {
  17696. return VertexBuffer._UVKind;
  17697. },
  17698. enumerable: true,
  17699. configurable: true
  17700. });
  17701. Object.defineProperty(VertexBuffer, "UV2Kind", {
  17702. get: function () {
  17703. return VertexBuffer._UV2Kind;
  17704. },
  17705. enumerable: true,
  17706. configurable: true
  17707. });
  17708. Object.defineProperty(VertexBuffer, "UV3Kind", {
  17709. get: function () {
  17710. return VertexBuffer._UV3Kind;
  17711. },
  17712. enumerable: true,
  17713. configurable: true
  17714. });
  17715. Object.defineProperty(VertexBuffer, "UV4Kind", {
  17716. get: function () {
  17717. return VertexBuffer._UV4Kind;
  17718. },
  17719. enumerable: true,
  17720. configurable: true
  17721. });
  17722. Object.defineProperty(VertexBuffer, "UV5Kind", {
  17723. get: function () {
  17724. return VertexBuffer._UV5Kind;
  17725. },
  17726. enumerable: true,
  17727. configurable: true
  17728. });
  17729. Object.defineProperty(VertexBuffer, "UV6Kind", {
  17730. get: function () {
  17731. return VertexBuffer._UV6Kind;
  17732. },
  17733. enumerable: true,
  17734. configurable: true
  17735. });
  17736. Object.defineProperty(VertexBuffer, "ColorKind", {
  17737. get: function () {
  17738. return VertexBuffer._ColorKind;
  17739. },
  17740. enumerable: true,
  17741. configurable: true
  17742. });
  17743. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  17744. get: function () {
  17745. return VertexBuffer._MatricesIndicesKind;
  17746. },
  17747. enumerable: true,
  17748. configurable: true
  17749. });
  17750. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  17751. get: function () {
  17752. return VertexBuffer._MatricesWeightsKind;
  17753. },
  17754. enumerable: true,
  17755. configurable: true
  17756. });
  17757. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  17758. get: function () {
  17759. return VertexBuffer._MatricesIndicesExtraKind;
  17760. },
  17761. enumerable: true,
  17762. configurable: true
  17763. });
  17764. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  17765. get: function () {
  17766. return VertexBuffer._MatricesWeightsExtraKind;
  17767. },
  17768. enumerable: true,
  17769. configurable: true
  17770. });
  17771. return VertexBuffer;
  17772. }());
  17773. // Enums
  17774. VertexBuffer._PositionKind = "position";
  17775. VertexBuffer._NormalKind = "normal";
  17776. VertexBuffer._TangentKind = "tangent";
  17777. VertexBuffer._UVKind = "uv";
  17778. VertexBuffer._UV2Kind = "uv2";
  17779. VertexBuffer._UV3Kind = "uv3";
  17780. VertexBuffer._UV4Kind = "uv4";
  17781. VertexBuffer._UV5Kind = "uv5";
  17782. VertexBuffer._UV6Kind = "uv6";
  17783. VertexBuffer._ColorKind = "color";
  17784. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  17785. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  17786. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  17787. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  17788. BABYLON.VertexBuffer = VertexBuffer;
  17789. })(BABYLON || (BABYLON = {}));
  17790. //# sourceMappingURL=babylon.vertexBuffer.js.map
  17791. var BABYLON;
  17792. (function (BABYLON) {
  17793. var BaseTexture = (function () {
  17794. function BaseTexture(scene) {
  17795. this._hasAlpha = false;
  17796. this.getAlphaFromRGB = false;
  17797. this.level = 1;
  17798. this.coordinatesIndex = 0;
  17799. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  17800. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  17801. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  17802. this.anisotropicFilteringLevel = 4;
  17803. this.isCube = false;
  17804. this.isRenderTarget = false;
  17805. this.animations = new Array();
  17806. /**
  17807. * An event triggered when the texture is disposed.
  17808. * @type {BABYLON.Observable}
  17809. */
  17810. this.onDisposeObservable = new BABYLON.Observable();
  17811. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  17812. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  17813. this._scene.textures.push(this);
  17814. this._uid = null;
  17815. }
  17816. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  17817. get: function () {
  17818. return this._hasAlpha;
  17819. },
  17820. set: function (value) {
  17821. if (this._hasAlpha === value) {
  17822. return;
  17823. }
  17824. this._hasAlpha = value;
  17825. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17826. },
  17827. enumerable: true,
  17828. configurable: true
  17829. });
  17830. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  17831. get: function () {
  17832. return this._coordinatesMode;
  17833. },
  17834. set: function (value) {
  17835. if (this._coordinatesMode === value) {
  17836. return;
  17837. }
  17838. this._coordinatesMode = value;
  17839. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  17840. },
  17841. enumerable: true,
  17842. configurable: true
  17843. });
  17844. Object.defineProperty(BaseTexture.prototype, "uid", {
  17845. get: function () {
  17846. if (!this._uid) {
  17847. this._uid = BABYLON.Tools.RandomId();
  17848. }
  17849. return this._uid;
  17850. },
  17851. enumerable: true,
  17852. configurable: true
  17853. });
  17854. BaseTexture.prototype.toString = function () {
  17855. return this.name;
  17856. };
  17857. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  17858. set: function (callback) {
  17859. if (this._onDisposeObserver) {
  17860. this.onDisposeObservable.remove(this._onDisposeObserver);
  17861. }
  17862. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17863. },
  17864. enumerable: true,
  17865. configurable: true
  17866. });
  17867. BaseTexture.prototype.getScene = function () {
  17868. return this._scene;
  17869. };
  17870. BaseTexture.prototype.getTextureMatrix = function () {
  17871. return null;
  17872. };
  17873. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  17874. return null;
  17875. };
  17876. BaseTexture.prototype.getInternalTexture = function () {
  17877. return this._texture;
  17878. };
  17879. BaseTexture.prototype.isReady = function () {
  17880. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  17881. return true;
  17882. }
  17883. if (this._texture) {
  17884. return this._texture.isReady;
  17885. }
  17886. return false;
  17887. };
  17888. BaseTexture.prototype.getSize = function () {
  17889. if (this._texture._width) {
  17890. return new BABYLON.Size(this._texture._width, this._texture._height);
  17891. }
  17892. if (this._texture._size) {
  17893. return new BABYLON.Size(this._texture._size, this._texture._size);
  17894. }
  17895. return BABYLON.Size.Zero();
  17896. };
  17897. BaseTexture.prototype.getBaseSize = function () {
  17898. if (!this.isReady() || !this._texture)
  17899. return BABYLON.Size.Zero();
  17900. if (this._texture._size) {
  17901. return new BABYLON.Size(this._texture._size, this._texture._size);
  17902. }
  17903. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  17904. };
  17905. BaseTexture.prototype.scale = function (ratio) {
  17906. };
  17907. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  17908. get: function () {
  17909. return false;
  17910. },
  17911. enumerable: true,
  17912. configurable: true
  17913. });
  17914. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  17915. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17916. for (var index = 0; index < texturesCache.length; index++) {
  17917. var texturesCacheEntry = texturesCache[index];
  17918. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17919. texturesCache.splice(index, 1);
  17920. return;
  17921. }
  17922. }
  17923. };
  17924. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  17925. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  17926. for (var index = 0; index < texturesCache.length; index++) {
  17927. var texturesCacheEntry = texturesCache[index];
  17928. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  17929. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  17930. texturesCacheEntry.references++;
  17931. return texturesCacheEntry;
  17932. }
  17933. }
  17934. }
  17935. return null;
  17936. };
  17937. BaseTexture.prototype.delayLoad = function () {
  17938. };
  17939. BaseTexture.prototype.clone = function () {
  17940. return null;
  17941. };
  17942. BaseTexture.prototype.releaseInternalTexture = function () {
  17943. if (this._texture) {
  17944. this._scene.getEngine().releaseInternalTexture(this._texture);
  17945. delete this._texture;
  17946. }
  17947. };
  17948. BaseTexture.prototype.dispose = function () {
  17949. // Animations
  17950. this.getScene().stopAnimation(this);
  17951. // Remove from scene
  17952. this._scene._removePendingData(this);
  17953. var index = this._scene.textures.indexOf(this);
  17954. if (index >= 0) {
  17955. this._scene.textures.splice(index, 1);
  17956. }
  17957. if (this._texture === undefined) {
  17958. return;
  17959. }
  17960. // Release
  17961. this.releaseInternalTexture();
  17962. // Callback
  17963. this.onDisposeObservable.notifyObservers(this);
  17964. this.onDisposeObservable.clear();
  17965. };
  17966. BaseTexture.prototype.serialize = function () {
  17967. if (!this.name) {
  17968. return null;
  17969. }
  17970. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17971. // Animations
  17972. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17973. return serializationObject;
  17974. };
  17975. return BaseTexture;
  17976. }());
  17977. __decorate([
  17978. BABYLON.serialize()
  17979. ], BaseTexture.prototype, "name", void 0);
  17980. __decorate([
  17981. BABYLON.serialize("hasAlpha")
  17982. ], BaseTexture.prototype, "_hasAlpha", void 0);
  17983. __decorate([
  17984. BABYLON.serialize()
  17985. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  17986. __decorate([
  17987. BABYLON.serialize()
  17988. ], BaseTexture.prototype, "level", void 0);
  17989. __decorate([
  17990. BABYLON.serialize()
  17991. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  17992. __decorate([
  17993. BABYLON.serialize("coordinatesMode")
  17994. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  17995. __decorate([
  17996. BABYLON.serialize()
  17997. ], BaseTexture.prototype, "wrapU", void 0);
  17998. __decorate([
  17999. BABYLON.serialize()
  18000. ], BaseTexture.prototype, "wrapV", void 0);
  18001. __decorate([
  18002. BABYLON.serialize()
  18003. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  18004. __decorate([
  18005. BABYLON.serialize()
  18006. ], BaseTexture.prototype, "isCube", void 0);
  18007. __decorate([
  18008. BABYLON.serialize()
  18009. ], BaseTexture.prototype, "isRenderTarget", void 0);
  18010. BABYLON.BaseTexture = BaseTexture;
  18011. })(BABYLON || (BABYLON = {}));
  18012. //# sourceMappingURL=babylon.baseTexture.js.map
  18013. var BABYLON;
  18014. (function (BABYLON) {
  18015. var Texture = (function (_super) {
  18016. __extends(Texture, _super);
  18017. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  18018. if (noMipmap === void 0) { noMipmap = false; }
  18019. if (invertY === void 0) { invertY = true; }
  18020. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18021. if (onLoad === void 0) { onLoad = null; }
  18022. if (onError === void 0) { onError = null; }
  18023. if (buffer === void 0) { buffer = null; }
  18024. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18025. var _this = _super.call(this, scene) || this;
  18026. _this.uOffset = 0;
  18027. _this.vOffset = 0;
  18028. _this.uScale = 1.0;
  18029. _this.vScale = 1.0;
  18030. _this.uAng = 0;
  18031. _this.vAng = 0;
  18032. _this.wAng = 0;
  18033. _this.name = url;
  18034. _this.url = url;
  18035. _this._noMipmap = noMipmap;
  18036. _this._invertY = invertY;
  18037. _this._samplingMode = samplingMode;
  18038. _this._buffer = buffer;
  18039. _this._deleteBuffer = deleteBuffer;
  18040. _this._format = format;
  18041. if (!url) {
  18042. return _this;
  18043. }
  18044. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  18045. var load = function () {
  18046. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  18047. _this.onLoadObservable.notifyObservers(true);
  18048. }
  18049. if (onLoad) {
  18050. onLoad();
  18051. }
  18052. };
  18053. if (!_this._texture) {
  18054. if (!scene.useDelayedTextureLoading) {
  18055. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  18056. if (deleteBuffer) {
  18057. delete _this._buffer;
  18058. }
  18059. }
  18060. else {
  18061. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18062. _this._delayedOnLoad = load;
  18063. _this._delayedOnError = onError;
  18064. }
  18065. }
  18066. else {
  18067. if (_this._texture.isReady) {
  18068. BABYLON.Tools.SetImmediate(function () { return load(); });
  18069. }
  18070. else {
  18071. _this._texture.onLoadedCallbacks.push(load);
  18072. }
  18073. }
  18074. return _this;
  18075. }
  18076. Object.defineProperty(Texture.prototype, "noMipmap", {
  18077. get: function () {
  18078. return this._noMipmap;
  18079. },
  18080. enumerable: true,
  18081. configurable: true
  18082. });
  18083. Texture.prototype.delayLoad = function () {
  18084. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  18085. return;
  18086. }
  18087. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  18088. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  18089. if (!this._texture) {
  18090. 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);
  18091. if (this._deleteBuffer) {
  18092. delete this._buffer;
  18093. }
  18094. }
  18095. };
  18096. Texture.prototype.updateSamplingMode = function (samplingMode) {
  18097. if (!this._texture) {
  18098. return;
  18099. }
  18100. this._samplingMode = samplingMode;
  18101. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  18102. };
  18103. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  18104. x *= this.uScale;
  18105. y *= this.vScale;
  18106. x -= 0.5 * this.uScale;
  18107. y -= 0.5 * this.vScale;
  18108. z -= 0.5;
  18109. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  18110. t.x += 0.5 * this.uScale + this.uOffset;
  18111. t.y += 0.5 * this.vScale + this.vOffset;
  18112. t.z += 0.5;
  18113. };
  18114. Texture.prototype.getTextureMatrix = function () {
  18115. if (this.uOffset === this._cachedUOffset &&
  18116. this.vOffset === this._cachedVOffset &&
  18117. this.uScale === this._cachedUScale &&
  18118. this.vScale === this._cachedVScale &&
  18119. this.uAng === this._cachedUAng &&
  18120. this.vAng === this._cachedVAng &&
  18121. this.wAng === this._cachedWAng) {
  18122. return this._cachedTextureMatrix;
  18123. }
  18124. this._cachedUOffset = this.uOffset;
  18125. this._cachedVOffset = this.vOffset;
  18126. this._cachedUScale = this.uScale;
  18127. this._cachedVScale = this.vScale;
  18128. this._cachedUAng = this.uAng;
  18129. this._cachedVAng = this.vAng;
  18130. this._cachedWAng = this.wAng;
  18131. if (!this._cachedTextureMatrix) {
  18132. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  18133. this._rowGenerationMatrix = new BABYLON.Matrix();
  18134. this._t0 = BABYLON.Vector3.Zero();
  18135. this._t1 = BABYLON.Vector3.Zero();
  18136. this._t2 = BABYLON.Vector3.Zero();
  18137. }
  18138. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  18139. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  18140. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  18141. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  18142. this._t1.subtractInPlace(this._t0);
  18143. this._t2.subtractInPlace(this._t0);
  18144. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18145. this._cachedTextureMatrix.m[0] = this._t1.x;
  18146. this._cachedTextureMatrix.m[1] = this._t1.y;
  18147. this._cachedTextureMatrix.m[2] = this._t1.z;
  18148. this._cachedTextureMatrix.m[4] = this._t2.x;
  18149. this._cachedTextureMatrix.m[5] = this._t2.y;
  18150. this._cachedTextureMatrix.m[6] = this._t2.z;
  18151. this._cachedTextureMatrix.m[8] = this._t0.x;
  18152. this._cachedTextureMatrix.m[9] = this._t0.y;
  18153. this._cachedTextureMatrix.m[10] = this._t0.z;
  18154. return this._cachedTextureMatrix;
  18155. };
  18156. Texture.prototype.getReflectionTextureMatrix = function () {
  18157. if (this.uOffset === this._cachedUOffset &&
  18158. this.vOffset === this._cachedVOffset &&
  18159. this.uScale === this._cachedUScale &&
  18160. this.vScale === this._cachedVScale &&
  18161. this.coordinatesMode === this._cachedCoordinatesMode) {
  18162. return this._cachedTextureMatrix;
  18163. }
  18164. if (!this._cachedTextureMatrix) {
  18165. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  18166. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  18167. }
  18168. this._cachedCoordinatesMode = this.coordinatesMode;
  18169. switch (this.coordinatesMode) {
  18170. case Texture.PLANAR_MODE:
  18171. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18172. this._cachedTextureMatrix[0] = this.uScale;
  18173. this._cachedTextureMatrix[5] = this.vScale;
  18174. this._cachedTextureMatrix[12] = this.uOffset;
  18175. this._cachedTextureMatrix[13] = this.vOffset;
  18176. break;
  18177. case Texture.PROJECTION_MODE:
  18178. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  18179. this._projectionModeMatrix.m[0] = 0.5;
  18180. this._projectionModeMatrix.m[5] = -0.5;
  18181. this._projectionModeMatrix.m[10] = 0.0;
  18182. this._projectionModeMatrix.m[12] = 0.5;
  18183. this._projectionModeMatrix.m[13] = 0.5;
  18184. this._projectionModeMatrix.m[14] = 1.0;
  18185. this._projectionModeMatrix.m[15] = 1.0;
  18186. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  18187. break;
  18188. default:
  18189. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  18190. break;
  18191. }
  18192. return this._cachedTextureMatrix;
  18193. };
  18194. Texture.prototype.clone = function () {
  18195. var _this = this;
  18196. return BABYLON.SerializationHelper.Clone(function () {
  18197. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  18198. }, this);
  18199. };
  18200. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  18201. get: function () {
  18202. if (!this._onLoadObservarble) {
  18203. this._onLoadObservarble = new BABYLON.Observable();
  18204. }
  18205. return this._onLoadObservarble;
  18206. },
  18207. enumerable: true,
  18208. configurable: true
  18209. });
  18210. // Statics
  18211. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  18212. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18213. if (onLoad === void 0) { onLoad = null; }
  18214. if (onError === void 0) { onError = null; }
  18215. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  18216. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  18217. };
  18218. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  18219. if (parsedTexture.customType) {
  18220. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  18221. // Update Sampling Mode
  18222. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  18223. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  18224. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  18225. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  18226. }
  18227. }
  18228. return parsedCustomTexture;
  18229. }
  18230. if (parsedTexture.isCube) {
  18231. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  18232. }
  18233. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18234. return null;
  18235. }
  18236. var texture = BABYLON.SerializationHelper.Parse(function () {
  18237. if (parsedTexture.mirrorPlane) {
  18238. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18239. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  18240. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18241. return mirrorTexture;
  18242. }
  18243. else if (parsedTexture.isRenderTarget) {
  18244. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18245. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  18246. return renderTargetTexture;
  18247. }
  18248. else {
  18249. var texture;
  18250. if (parsedTexture.base64String) {
  18251. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  18252. }
  18253. else {
  18254. texture = new Texture(rootUrl + parsedTexture.name, scene);
  18255. }
  18256. return texture;
  18257. }
  18258. }, parsedTexture, scene);
  18259. // Update Sampling Mode
  18260. if (parsedTexture.samplingMode) {
  18261. var sampling = parsedTexture.samplingMode;
  18262. if (texture._samplingMode !== sampling) {
  18263. texture.updateSamplingMode(sampling);
  18264. }
  18265. }
  18266. // Animations
  18267. if (parsedTexture.animations) {
  18268. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18269. var parsedAnimation = parsedTexture.animations[animationIndex];
  18270. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18271. }
  18272. }
  18273. return texture;
  18274. };
  18275. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  18276. if (deleteBuffer === void 0) { deleteBuffer = false; }
  18277. if (noMipmap === void 0) { noMipmap = false; }
  18278. if (invertY === void 0) { invertY = true; }
  18279. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  18280. if (onLoad === void 0) { onLoad = null; }
  18281. if (onError === void 0) { onError = null; }
  18282. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  18283. if (name.substr(0, 5) !== "data:") {
  18284. name = "data:" + name;
  18285. }
  18286. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  18287. };
  18288. return Texture;
  18289. }(BABYLON.BaseTexture));
  18290. // Constants
  18291. Texture.NEAREST_SAMPLINGMODE = 1;
  18292. Texture.BILINEAR_SAMPLINGMODE = 2;
  18293. Texture.TRILINEAR_SAMPLINGMODE = 3;
  18294. Texture.EXPLICIT_MODE = 0;
  18295. Texture.SPHERICAL_MODE = 1;
  18296. Texture.PLANAR_MODE = 2;
  18297. Texture.CUBIC_MODE = 3;
  18298. Texture.PROJECTION_MODE = 4;
  18299. Texture.SKYBOX_MODE = 5;
  18300. Texture.INVCUBIC_MODE = 6;
  18301. Texture.EQUIRECTANGULAR_MODE = 7;
  18302. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  18303. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18304. Texture.CLAMP_ADDRESSMODE = 0;
  18305. Texture.WRAP_ADDRESSMODE = 1;
  18306. Texture.MIRROR_ADDRESSMODE = 2;
  18307. __decorate([
  18308. BABYLON.serialize()
  18309. ], Texture.prototype, "url", void 0);
  18310. __decorate([
  18311. BABYLON.serialize()
  18312. ], Texture.prototype, "uOffset", void 0);
  18313. __decorate([
  18314. BABYLON.serialize()
  18315. ], Texture.prototype, "vOffset", void 0);
  18316. __decorate([
  18317. BABYLON.serialize()
  18318. ], Texture.prototype, "uScale", void 0);
  18319. __decorate([
  18320. BABYLON.serialize()
  18321. ], Texture.prototype, "vScale", void 0);
  18322. __decorate([
  18323. BABYLON.serialize()
  18324. ], Texture.prototype, "uAng", void 0);
  18325. __decorate([
  18326. BABYLON.serialize()
  18327. ], Texture.prototype, "vAng", void 0);
  18328. __decorate([
  18329. BABYLON.serialize()
  18330. ], Texture.prototype, "wAng", void 0);
  18331. BABYLON.Texture = Texture;
  18332. })(BABYLON || (BABYLON = {}));
  18333. //# sourceMappingURL=babylon.texture.js.map
  18334. var BABYLON;
  18335. (function (BABYLON) {
  18336. var _InstancesBatch = (function () {
  18337. function _InstancesBatch() {
  18338. this.mustReturn = false;
  18339. this.visibleInstances = new Array();
  18340. this.renderSelf = new Array();
  18341. }
  18342. return _InstancesBatch;
  18343. }());
  18344. BABYLON._InstancesBatch = _InstancesBatch;
  18345. var Mesh = (function (_super) {
  18346. __extends(Mesh, _super);
  18347. /**
  18348. * @constructor
  18349. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18350. * @param {Scene} scene The scene to add this mesh to.
  18351. * @param {Node} parent The parent of this mesh, if it has one
  18352. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18353. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18354. * When false, achieved by calling a clone(), also passing False.
  18355. * This will make creation of children, recursive.
  18356. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  18357. */
  18358. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18359. if (parent === void 0) { parent = null; }
  18360. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18361. var _this = _super.call(this, name, scene) || this;
  18362. // Events
  18363. /**
  18364. * An event triggered before rendering the mesh
  18365. * @type {BABYLON.Observable}
  18366. */
  18367. _this.onBeforeRenderObservable = new BABYLON.Observable();
  18368. /**
  18369. * An event triggered after rendering the mesh
  18370. * @type {BABYLON.Observable}
  18371. */
  18372. _this.onAfterRenderObservable = new BABYLON.Observable();
  18373. /**
  18374. * An event triggered before drawing the mesh
  18375. * @type {BABYLON.Observable}
  18376. */
  18377. _this.onBeforeDrawObservable = new BABYLON.Observable();
  18378. // Members
  18379. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18380. _this.instances = new Array();
  18381. _this._LODLevels = new Array();
  18382. _this._visibleInstances = {};
  18383. _this._renderIdForInstances = new Array();
  18384. _this._batchCache = new _InstancesBatch();
  18385. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  18386. _this._sideOrientation = Mesh._DEFAULTSIDE;
  18387. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  18388. // Will be used to save a source mesh reference, If any
  18389. _this._source = null;
  18390. if (source) {
  18391. // Source mesh
  18392. _this._source = source;
  18393. // Geometry
  18394. if (source._geometry) {
  18395. source._geometry.applyToMesh(_this);
  18396. }
  18397. // Deep copy
  18398. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  18399. // Parent
  18400. _this.parent = source.parent;
  18401. // Pivot
  18402. _this.setPivotMatrix(source.getPivotMatrix());
  18403. _this.id = name + "." + source.id;
  18404. // Material
  18405. _this.material = source.material;
  18406. var index;
  18407. if (!doNotCloneChildren) {
  18408. // Children
  18409. for (index = 0; index < scene.meshes.length; index++) {
  18410. var mesh = scene.meshes[index];
  18411. if (mesh.parent === source) {
  18412. // doNotCloneChildren is always going to be False
  18413. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  18414. }
  18415. }
  18416. }
  18417. // Physics clone
  18418. var physicsEngine = _this.getScene().getPhysicsEngine();
  18419. if (clonePhysicsImpostor && physicsEngine) {
  18420. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  18421. if (impostor) {
  18422. _this.physicsImpostor = impostor.clone(_this);
  18423. }
  18424. }
  18425. // Particles
  18426. for (index = 0; index < scene.particleSystems.length; index++) {
  18427. var system = scene.particleSystems[index];
  18428. if (system.emitter === source) {
  18429. system.clone(system.name, _this);
  18430. }
  18431. }
  18432. _this.computeWorldMatrix(true);
  18433. }
  18434. // Parent
  18435. if (parent !== null) {
  18436. _this.parent = parent;
  18437. }
  18438. return _this;
  18439. }
  18440. Object.defineProperty(Mesh, "FRONTSIDE", {
  18441. /**
  18442. * Mesh side orientation : usually the external or front surface
  18443. */
  18444. get: function () {
  18445. return Mesh._FRONTSIDE;
  18446. },
  18447. enumerable: true,
  18448. configurable: true
  18449. });
  18450. Object.defineProperty(Mesh, "BACKSIDE", {
  18451. /**
  18452. * Mesh side orientation : usually the internal or back surface
  18453. */
  18454. get: function () {
  18455. return Mesh._BACKSIDE;
  18456. },
  18457. enumerable: true,
  18458. configurable: true
  18459. });
  18460. Object.defineProperty(Mesh, "DOUBLESIDE", {
  18461. /**
  18462. * Mesh side orientation : both internal and external or front and back surfaces
  18463. */
  18464. get: function () {
  18465. return Mesh._DOUBLESIDE;
  18466. },
  18467. enumerable: true,
  18468. configurable: true
  18469. });
  18470. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  18471. /**
  18472. * Mesh side orientation : by default, `FRONTSIDE`
  18473. */
  18474. get: function () {
  18475. return Mesh._DEFAULTSIDE;
  18476. },
  18477. enumerable: true,
  18478. configurable: true
  18479. });
  18480. Object.defineProperty(Mesh, "NO_CAP", {
  18481. /**
  18482. * Mesh cap setting : no cap
  18483. */
  18484. get: function () {
  18485. return Mesh._NO_CAP;
  18486. },
  18487. enumerable: true,
  18488. configurable: true
  18489. });
  18490. Object.defineProperty(Mesh, "CAP_START", {
  18491. /**
  18492. * Mesh cap setting : one cap at the beginning of the mesh
  18493. */
  18494. get: function () {
  18495. return Mesh._CAP_START;
  18496. },
  18497. enumerable: true,
  18498. configurable: true
  18499. });
  18500. Object.defineProperty(Mesh, "CAP_END", {
  18501. /**
  18502. * Mesh cap setting : one cap at the end of the mesh
  18503. */
  18504. get: function () {
  18505. return Mesh._CAP_END;
  18506. },
  18507. enumerable: true,
  18508. configurable: true
  18509. });
  18510. Object.defineProperty(Mesh, "CAP_ALL", {
  18511. /**
  18512. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  18513. */
  18514. get: function () {
  18515. return Mesh._CAP_ALL;
  18516. },
  18517. enumerable: true,
  18518. configurable: true
  18519. });
  18520. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  18521. set: function (callback) {
  18522. if (this._onBeforeDrawObserver) {
  18523. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18524. }
  18525. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18526. },
  18527. enumerable: true,
  18528. configurable: true
  18529. });
  18530. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  18531. get: function () {
  18532. return this._morphTargetManager;
  18533. },
  18534. set: function (value) {
  18535. if (this._morphTargetManager === value) {
  18536. return;
  18537. }
  18538. this._morphTargetManager = value;
  18539. this._syncGeometryWithMorphTargetManager();
  18540. },
  18541. enumerable: true,
  18542. configurable: true
  18543. });
  18544. Object.defineProperty(Mesh.prototype, "source", {
  18545. get: function () {
  18546. return this._source;
  18547. },
  18548. enumerable: true,
  18549. configurable: true
  18550. });
  18551. // Methods
  18552. /**
  18553. * Returns the string "Mesh".
  18554. */
  18555. Mesh.prototype.getClassName = function () {
  18556. return "Mesh";
  18557. };
  18558. /**
  18559. * Returns a string.
  18560. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18561. */
  18562. Mesh.prototype.toString = function (fullDetails) {
  18563. var ret = _super.prototype.toString.call(this, fullDetails);
  18564. ret += ", n vertices: " + this.getTotalVertices();
  18565. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18566. if (this.animations) {
  18567. for (var i = 0; i < this.animations.length; i++) {
  18568. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18569. }
  18570. }
  18571. if (fullDetails) {
  18572. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18573. }
  18574. return ret;
  18575. };
  18576. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18577. /**
  18578. * True if the mesh has some Levels Of Details (LOD).
  18579. * Returns a boolean.
  18580. */
  18581. get: function () {
  18582. return this._LODLevels.length > 0;
  18583. },
  18584. enumerable: true,
  18585. configurable: true
  18586. });
  18587. Mesh.prototype._sortLODLevels = function () {
  18588. this._LODLevels.sort(function (a, b) {
  18589. if (a.distance < b.distance) {
  18590. return 1;
  18591. }
  18592. if (a.distance > b.distance) {
  18593. return -1;
  18594. }
  18595. return 0;
  18596. });
  18597. };
  18598. /**
  18599. * Add a mesh as LOD level triggered at the given distance.
  18600. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18601. * @param {number} distance The distance from the center of the object to show this level
  18602. * @param {Mesh} mesh The mesh to be added as LOD level
  18603. * @return {Mesh} This mesh (for chaining)
  18604. */
  18605. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18606. if (mesh && mesh._masterMesh) {
  18607. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18608. return this;
  18609. }
  18610. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18611. this._LODLevels.push(level);
  18612. if (mesh) {
  18613. mesh._masterMesh = this;
  18614. }
  18615. this._sortLODLevels();
  18616. return this;
  18617. };
  18618. /**
  18619. * Returns the LOD level mesh at the passed distance or null if not found.
  18620. * It is related to the method `addLODLevel(distance, mesh)`.
  18621. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18622. * Returns an object Mesh or `null`.
  18623. */
  18624. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18625. for (var index = 0; index < this._LODLevels.length; index++) {
  18626. var level = this._LODLevels[index];
  18627. if (level.distance === distance) {
  18628. return level.mesh;
  18629. }
  18630. }
  18631. return null;
  18632. };
  18633. /**
  18634. * Remove a mesh from the LOD array
  18635. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18636. * @param {Mesh} mesh The mesh to be removed.
  18637. * @return {Mesh} This mesh (for chaining)
  18638. */
  18639. Mesh.prototype.removeLODLevel = function (mesh) {
  18640. for (var index = 0; index < this._LODLevels.length; index++) {
  18641. if (this._LODLevels[index].mesh === mesh) {
  18642. this._LODLevels.splice(index, 1);
  18643. if (mesh) {
  18644. mesh._masterMesh = null;
  18645. }
  18646. }
  18647. }
  18648. this._sortLODLevels();
  18649. return this;
  18650. };
  18651. /**
  18652. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  18653. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18654. */
  18655. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  18656. if (!this._LODLevels || this._LODLevels.length === 0) {
  18657. return this;
  18658. }
  18659. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18660. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18661. if (this.onLODLevelSelection) {
  18662. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18663. }
  18664. return this;
  18665. }
  18666. for (var index = 0; index < this._LODLevels.length; index++) {
  18667. var level = this._LODLevels[index];
  18668. if (level.distance < distanceToCamera) {
  18669. if (level.mesh) {
  18670. level.mesh._preActivate();
  18671. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18672. }
  18673. if (this.onLODLevelSelection) {
  18674. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18675. }
  18676. return level.mesh;
  18677. }
  18678. }
  18679. if (this.onLODLevelSelection) {
  18680. this.onLODLevelSelection(distanceToCamera, this, this);
  18681. }
  18682. return this;
  18683. };
  18684. Object.defineProperty(Mesh.prototype, "geometry", {
  18685. /**
  18686. * Returns the mesh internal Geometry object.
  18687. */
  18688. get: function () {
  18689. return this._geometry;
  18690. },
  18691. enumerable: true,
  18692. configurable: true
  18693. });
  18694. /**
  18695. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18696. */
  18697. Mesh.prototype.getTotalVertices = function () {
  18698. if (!this._geometry) {
  18699. return 0;
  18700. }
  18701. return this._geometry.getTotalVertices();
  18702. };
  18703. /**
  18704. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18705. * 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.
  18706. * Returns null if the mesh has no geometry or no vertex buffer.
  18707. * Possible `kind` values :
  18708. * - BABYLON.VertexBuffer.PositionKind
  18709. * - BABYLON.VertexBuffer.UVKind
  18710. * - BABYLON.VertexBuffer.UV2Kind
  18711. * - BABYLON.VertexBuffer.UV3Kind
  18712. * - BABYLON.VertexBuffer.UV4Kind
  18713. * - BABYLON.VertexBuffer.UV5Kind
  18714. * - BABYLON.VertexBuffer.UV6Kind
  18715. * - BABYLON.VertexBuffer.ColorKind
  18716. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18717. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18718. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18719. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18720. */
  18721. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18722. if (!this._geometry) {
  18723. return null;
  18724. }
  18725. return this._geometry.getVerticesData(kind, copyWhenShared);
  18726. };
  18727. /**
  18728. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18729. * Returns `undefined` if the mesh has no geometry.
  18730. * Possible `kind` values :
  18731. * - BABYLON.VertexBuffer.PositionKind
  18732. * - BABYLON.VertexBuffer.UVKind
  18733. * - BABYLON.VertexBuffer.UV2Kind
  18734. * - BABYLON.VertexBuffer.UV3Kind
  18735. * - BABYLON.VertexBuffer.UV4Kind
  18736. * - BABYLON.VertexBuffer.UV5Kind
  18737. * - BABYLON.VertexBuffer.UV6Kind
  18738. * - BABYLON.VertexBuffer.ColorKind
  18739. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18740. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18741. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18742. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18743. */
  18744. Mesh.prototype.getVertexBuffer = function (kind) {
  18745. if (!this._geometry) {
  18746. return undefined;
  18747. }
  18748. return this._geometry.getVertexBuffer(kind);
  18749. };
  18750. /**
  18751. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18752. * Possible `kind` values :
  18753. * - BABYLON.VertexBuffer.PositionKind
  18754. * - BABYLON.VertexBuffer.UVKind
  18755. * - BABYLON.VertexBuffer.UV2Kind
  18756. * - BABYLON.VertexBuffer.UV3Kind
  18757. * - BABYLON.VertexBuffer.UV4Kind
  18758. * - BABYLON.VertexBuffer.UV5Kind
  18759. * - BABYLON.VertexBuffer.UV6Kind
  18760. * - BABYLON.VertexBuffer.ColorKind
  18761. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18762. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18763. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18764. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18765. */
  18766. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18767. if (!this._geometry) {
  18768. if (this._delayInfo) {
  18769. return this._delayInfo.indexOf(kind) !== -1;
  18770. }
  18771. return false;
  18772. }
  18773. return this._geometry.isVerticesDataPresent(kind);
  18774. };
  18775. /**
  18776. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18777. * Possible `kind` values :
  18778. * - BABYLON.VertexBuffer.PositionKind
  18779. * - BABYLON.VertexBuffer.UVKind
  18780. * - BABYLON.VertexBuffer.UV2Kind
  18781. * - BABYLON.VertexBuffer.UV3Kind
  18782. * - BABYLON.VertexBuffer.UV4Kind
  18783. * - BABYLON.VertexBuffer.UV5Kind
  18784. * - BABYLON.VertexBuffer.UV6Kind
  18785. * - BABYLON.VertexBuffer.ColorKind
  18786. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18787. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18788. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18789. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18790. */
  18791. Mesh.prototype.getVerticesDataKinds = function () {
  18792. if (!this._geometry) {
  18793. var result = [];
  18794. if (this._delayInfo) {
  18795. this._delayInfo.forEach(function (kind, index, array) {
  18796. result.push(kind);
  18797. });
  18798. }
  18799. return result;
  18800. }
  18801. return this._geometry.getVerticesDataKinds();
  18802. };
  18803. /**
  18804. * Returns a positive integer : the total number of indices in this mesh geometry.
  18805. * Returns zero if the mesh has no geometry.
  18806. */
  18807. Mesh.prototype.getTotalIndices = function () {
  18808. if (!this._geometry) {
  18809. return 0;
  18810. }
  18811. return this._geometry.getTotalIndices();
  18812. };
  18813. /**
  18814. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  18815. * 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.
  18816. * Returns an empty array if the mesh has no geometry.
  18817. */
  18818. Mesh.prototype.getIndices = function (copyWhenShared) {
  18819. if (!this._geometry) {
  18820. return [];
  18821. }
  18822. return this._geometry.getIndices(copyWhenShared);
  18823. };
  18824. Object.defineProperty(Mesh.prototype, "isBlocked", {
  18825. get: function () {
  18826. return this._masterMesh !== null && this._masterMesh !== undefined;
  18827. },
  18828. enumerable: true,
  18829. configurable: true
  18830. });
  18831. /**
  18832. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  18833. */
  18834. Mesh.prototype.isReady = function () {
  18835. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18836. return false;
  18837. }
  18838. return _super.prototype.isReady.call(this);
  18839. };
  18840. /**
  18841. * Boolean : true if the mesh has been disposed.
  18842. */
  18843. Mesh.prototype.isDisposed = function () {
  18844. return this._isDisposed;
  18845. };
  18846. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  18847. get: function () {
  18848. return this._sideOrientation;
  18849. },
  18850. /**
  18851. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  18852. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  18853. */
  18854. set: function (sideO) {
  18855. this._sideOrientation = sideO;
  18856. },
  18857. enumerable: true,
  18858. configurable: true
  18859. });
  18860. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  18861. /**
  18862. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  18863. * This property is pertinent only for updatable parametric shapes.
  18864. */
  18865. get: function () {
  18866. return this._areNormalsFrozen;
  18867. },
  18868. enumerable: true,
  18869. configurable: true
  18870. });
  18871. /**
  18872. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18873. * It has no effect at all on other shapes.
  18874. * It prevents the mesh normals from being recomputed on next `positions` array update.
  18875. * Returns the Mesh.
  18876. */
  18877. Mesh.prototype.freezeNormals = function () {
  18878. this._areNormalsFrozen = true;
  18879. return this;
  18880. };
  18881. /**
  18882. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18883. * It has no effect at all on other shapes.
  18884. * It reactivates the mesh normals computation if it was previously frozen.
  18885. * Returns the Mesh.
  18886. */
  18887. Mesh.prototype.unfreezeNormals = function () {
  18888. this._areNormalsFrozen = false;
  18889. return this;
  18890. };
  18891. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  18892. /**
  18893. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  18894. */
  18895. set: function (count) {
  18896. this._overridenInstanceCount = count;
  18897. },
  18898. enumerable: true,
  18899. configurable: true
  18900. });
  18901. // Methods
  18902. Mesh.prototype._preActivate = function () {
  18903. var sceneRenderId = this.getScene().getRenderId();
  18904. if (this._preActivateId === sceneRenderId) {
  18905. return this;
  18906. }
  18907. this._preActivateId = sceneRenderId;
  18908. this._visibleInstances = null;
  18909. return this;
  18910. };
  18911. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18912. if (this._visibleInstances) {
  18913. this._visibleInstances.intermediateDefaultRenderId = renderId;
  18914. }
  18915. return this;
  18916. };
  18917. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  18918. if (!this._visibleInstances) {
  18919. this._visibleInstances = {};
  18920. this._visibleInstances.defaultRenderId = renderId;
  18921. this._visibleInstances.selfDefaultRenderId = this._renderId;
  18922. }
  18923. if (!this._visibleInstances[renderId]) {
  18924. this._visibleInstances[renderId] = new Array();
  18925. }
  18926. this._visibleInstances[renderId].push(instance);
  18927. return this;
  18928. };
  18929. /**
  18930. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  18931. * This means the mesh underlying bounding box and sphere are recomputed.
  18932. * Returns the Mesh.
  18933. */
  18934. Mesh.prototype.refreshBoundingInfo = function () {
  18935. if (this._boundingInfo.isLocked) {
  18936. return;
  18937. }
  18938. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18939. if (data) {
  18940. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  18941. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  18942. }
  18943. if (this.subMeshes) {
  18944. for (var index = 0; index < this.subMeshes.length; index++) {
  18945. this.subMeshes[index].refreshBoundingInfo();
  18946. }
  18947. }
  18948. this._updateBoundingInfo();
  18949. return this;
  18950. };
  18951. Mesh.prototype._createGlobalSubMesh = function () {
  18952. var totalVertices = this.getTotalVertices();
  18953. if (!totalVertices || !this.getIndices()) {
  18954. return null;
  18955. }
  18956. this.releaseSubMeshes();
  18957. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  18958. };
  18959. Mesh.prototype.subdivide = function (count) {
  18960. if (count < 1) {
  18961. return;
  18962. }
  18963. var totalIndices = this.getTotalIndices();
  18964. var subdivisionSize = (totalIndices / count) | 0;
  18965. var offset = 0;
  18966. // Ensure that subdivisionSize is a multiple of 3
  18967. while (subdivisionSize % 3 !== 0) {
  18968. subdivisionSize++;
  18969. }
  18970. this.releaseSubMeshes();
  18971. for (var index = 0; index < count; index++) {
  18972. if (offset >= totalIndices) {
  18973. break;
  18974. }
  18975. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  18976. offset += subdivisionSize;
  18977. }
  18978. this.synchronizeInstances();
  18979. };
  18980. /**
  18981. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18982. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18983. * The `data` are either a numeric array either a Float32Array.
  18984. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18985. * 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).
  18986. * Note that a new underlying VertexBuffer object is created each call.
  18987. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18988. *
  18989. * Possible `kind` values :
  18990. * - BABYLON.VertexBuffer.PositionKind
  18991. * - BABYLON.VertexBuffer.UVKind
  18992. * - BABYLON.VertexBuffer.UV2Kind
  18993. * - BABYLON.VertexBuffer.UV3Kind
  18994. * - BABYLON.VertexBuffer.UV4Kind
  18995. * - BABYLON.VertexBuffer.UV5Kind
  18996. * - BABYLON.VertexBuffer.UV6Kind
  18997. * - BABYLON.VertexBuffer.ColorKind
  18998. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18999. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19000. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19001. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19002. *
  19003. * Returns the Mesh.
  19004. */
  19005. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19006. if (!this._geometry) {
  19007. var vertexData = new BABYLON.VertexData();
  19008. vertexData.set(data, kind);
  19009. var scene = this.getScene();
  19010. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19011. }
  19012. else {
  19013. this._geometry.setVerticesData(kind, data, updatable, stride);
  19014. }
  19015. return this;
  19016. };
  19017. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  19018. if (updatable === void 0) { updatable = true; }
  19019. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  19020. return;
  19021. }
  19022. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  19023. };
  19024. /**
  19025. * Sets the mesh VertexBuffer.
  19026. * Returns the Mesh.
  19027. */
  19028. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19029. if (!this._geometry) {
  19030. var scene = this.getScene();
  19031. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19032. }
  19033. this._geometry.setVerticesBuffer(buffer);
  19034. return this;
  19035. };
  19036. /**
  19037. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19038. * If the mesh has no geometry, it is simply returned as it is.
  19039. * The `data` are either a numeric array either a Float32Array.
  19040. * No new underlying VertexBuffer object is created.
  19041. * 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.
  19042. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19043. *
  19044. * Possible `kind` values :
  19045. * - BABYLON.VertexBuffer.PositionKind
  19046. * - BABYLON.VertexBuffer.UVKind
  19047. * - BABYLON.VertexBuffer.UV2Kind
  19048. * - BABYLON.VertexBuffer.UV3Kind
  19049. * - BABYLON.VertexBuffer.UV4Kind
  19050. * - BABYLON.VertexBuffer.UV5Kind
  19051. * - BABYLON.VertexBuffer.UV6Kind
  19052. * - BABYLON.VertexBuffer.ColorKind
  19053. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19054. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19055. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19056. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19057. *
  19058. * Returns the Mesh.
  19059. */
  19060. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19061. if (!this._geometry) {
  19062. return;
  19063. }
  19064. if (!makeItUnique) {
  19065. this._geometry.updateVerticesData(kind, data, updateExtends);
  19066. }
  19067. else {
  19068. this.makeGeometryUnique();
  19069. this.updateVerticesData(kind, data, updateExtends, false);
  19070. }
  19071. return this;
  19072. };
  19073. /**
  19074. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19075. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19076. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19077. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19078. * Returns the Mesh.
  19079. */
  19080. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19081. if (computeNormals === void 0) { computeNormals = true; }
  19082. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19083. positionFunction(positions);
  19084. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19085. if (computeNormals) {
  19086. var indices = this.getIndices();
  19087. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19088. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19089. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19090. }
  19091. return this;
  19092. };
  19093. /**
  19094. * Creates a un-shared specific occurence of the geometry for the mesh.
  19095. * Returns the Mesh.
  19096. */
  19097. Mesh.prototype.makeGeometryUnique = function () {
  19098. if (!this._geometry) {
  19099. return;
  19100. }
  19101. var oldGeometry = this._geometry;
  19102. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19103. oldGeometry.releaseForMesh(this, true);
  19104. geometry.applyToMesh(this);
  19105. return this;
  19106. };
  19107. /**
  19108. * Sets the mesh indices.
  19109. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19110. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19111. * This method creates a new index buffer each call.
  19112. * Returns the Mesh.
  19113. */
  19114. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19115. if (!this._geometry) {
  19116. var vertexData = new BABYLON.VertexData();
  19117. vertexData.indices = indices;
  19118. var scene = this.getScene();
  19119. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19120. }
  19121. else {
  19122. this._geometry.setIndices(indices, totalVertices);
  19123. }
  19124. return this;
  19125. };
  19126. /**
  19127. * Invert the geometry to move from a right handed system to a left handed one.
  19128. * Returns the Mesh.
  19129. */
  19130. Mesh.prototype.toLeftHanded = function () {
  19131. if (!this._geometry) {
  19132. return;
  19133. }
  19134. this._geometry.toLeftHanded();
  19135. return this;
  19136. };
  19137. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19138. var engine = this.getScene().getEngine();
  19139. // Wireframe
  19140. var indexToBind;
  19141. if (this._unIndexed) {
  19142. indexToBind = null;
  19143. }
  19144. else {
  19145. switch (fillMode) {
  19146. case BABYLON.Material.PointFillMode:
  19147. indexToBind = null;
  19148. break;
  19149. case BABYLON.Material.WireFrameFillMode:
  19150. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19151. break;
  19152. default:
  19153. case BABYLON.Material.TriangleFillMode:
  19154. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19155. break;
  19156. }
  19157. }
  19158. // VBOs
  19159. this._geometry._bind(effect, indexToBind);
  19160. return this;
  19161. };
  19162. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19163. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19164. return this;
  19165. }
  19166. this.onBeforeDrawObservable.notifyObservers(this);
  19167. var engine = this.getScene().getEngine();
  19168. // Draw order
  19169. switch (fillMode) {
  19170. case BABYLON.Material.PointFillMode:
  19171. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19172. break;
  19173. case BABYLON.Material.WireFrameFillMode:
  19174. if (this._unIndexed) {
  19175. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19176. }
  19177. else {
  19178. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19179. }
  19180. break;
  19181. default:
  19182. if (this._unIndexed) {
  19183. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19184. }
  19185. else {
  19186. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19187. }
  19188. }
  19189. return this;
  19190. };
  19191. /**
  19192. * Registers for this mesh a javascript function called just before the rendering process.
  19193. * This function is passed the current mesh.
  19194. * Return the Mesh.
  19195. */
  19196. Mesh.prototype.registerBeforeRender = function (func) {
  19197. this.onBeforeRenderObservable.add(func);
  19198. return this;
  19199. };
  19200. /**
  19201. * Disposes a previously registered javascript function called before the rendering.
  19202. * This function is passed the current mesh.
  19203. * Returns the Mesh.
  19204. */
  19205. Mesh.prototype.unregisterBeforeRender = function (func) {
  19206. this.onBeforeRenderObservable.removeCallback(func);
  19207. return this;
  19208. };
  19209. /**
  19210. * Registers for this mesh a javascript function called just after the rendering is complete.
  19211. * This function is passed the current mesh.
  19212. * Returns the Mesh.
  19213. */
  19214. Mesh.prototype.registerAfterRender = function (func) {
  19215. this.onAfterRenderObservable.add(func);
  19216. return this;
  19217. };
  19218. /**
  19219. * Disposes a previously registered javascript function called after the rendering.
  19220. * This function is passed the current mesh.
  19221. * Return the Mesh.
  19222. */
  19223. Mesh.prototype.unregisterAfterRender = function (func) {
  19224. this.onAfterRenderObservable.removeCallback(func);
  19225. return this;
  19226. };
  19227. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19228. var scene = this.getScene();
  19229. this._batchCache.mustReturn = false;
  19230. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19231. this._batchCache.visibleInstances[subMeshId] = null;
  19232. if (this._visibleInstances) {
  19233. var currentRenderId = scene.getRenderId();
  19234. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19235. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19236. var selfRenderId = this._renderId;
  19237. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19238. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19239. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19240. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19241. }
  19242. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19243. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19244. this._batchCache.mustReturn = true;
  19245. return this._batchCache;
  19246. }
  19247. if (currentRenderId !== selfRenderId) {
  19248. this._batchCache.renderSelf[subMeshId] = false;
  19249. }
  19250. }
  19251. this._renderIdForInstances[subMeshId] = currentRenderId;
  19252. }
  19253. return this._batchCache;
  19254. };
  19255. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19256. var visibleInstances = batch.visibleInstances[subMesh._id];
  19257. var matricesCount = visibleInstances.length + 1;
  19258. var bufferSize = matricesCount * 16 * 4;
  19259. var currentInstancesBufferSize = this._instancesBufferSize;
  19260. var instancesBuffer = this._instancesBuffer;
  19261. while (this._instancesBufferSize < bufferSize) {
  19262. this._instancesBufferSize *= 2;
  19263. }
  19264. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19265. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19266. }
  19267. var offset = 0;
  19268. var instancesCount = 0;
  19269. var world = this.getWorldMatrix();
  19270. if (batch.renderSelf[subMesh._id]) {
  19271. world.copyToArray(this._instancesData, offset);
  19272. offset += 16;
  19273. instancesCount++;
  19274. }
  19275. if (visibleInstances) {
  19276. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19277. var instance = visibleInstances[instanceIndex];
  19278. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19279. offset += 16;
  19280. instancesCount++;
  19281. }
  19282. }
  19283. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19284. if (instancesBuffer) {
  19285. instancesBuffer.dispose();
  19286. }
  19287. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19288. this._instancesBuffer = instancesBuffer;
  19289. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19290. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19291. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19292. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19293. }
  19294. else {
  19295. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19296. }
  19297. this.geometry._bind(effect);
  19298. this._draw(subMesh, fillMode, instancesCount);
  19299. engine.unbindInstanceAttributes();
  19300. return this;
  19301. };
  19302. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19303. var scene = this.getScene();
  19304. var engine = scene.getEngine();
  19305. if (hardwareInstancedRendering) {
  19306. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19307. }
  19308. else {
  19309. if (batch.renderSelf[subMesh._id]) {
  19310. // Draw
  19311. if (onBeforeDraw) {
  19312. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19313. }
  19314. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19315. }
  19316. if (batch.visibleInstances[subMesh._id]) {
  19317. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19318. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19319. // World
  19320. var world = instance.getWorldMatrix();
  19321. if (onBeforeDraw) {
  19322. onBeforeDraw(true, world, effectiveMaterial);
  19323. }
  19324. // Draw
  19325. this._draw(subMesh, fillMode);
  19326. }
  19327. }
  19328. }
  19329. return this;
  19330. };
  19331. /**
  19332. * Triggers the draw call for the mesh.
  19333. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19334. * Returns the Mesh.
  19335. */
  19336. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19337. var scene = this.getScene();
  19338. // Managing instances
  19339. var batch = this._getInstancesRenderList(subMesh._id);
  19340. if (batch.mustReturn) {
  19341. return this;
  19342. }
  19343. // Checking geometry state
  19344. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19345. return this;
  19346. }
  19347. var callbackIndex;
  19348. this.onBeforeRenderObservable.notifyObservers(this);
  19349. var engine = scene.getEngine();
  19350. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19351. // Material
  19352. var effectiveMaterial = subMesh.getMaterial();
  19353. if (!effectiveMaterial) {
  19354. return this;
  19355. }
  19356. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19357. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  19358. return this;
  19359. }
  19360. }
  19361. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19362. return this;
  19363. }
  19364. // Outline - step 1
  19365. var savedDepthWrite = engine.getDepthWrite();
  19366. if (this.renderOutline) {
  19367. engine.setDepthWrite(false);
  19368. scene.getOutlineRenderer().render(subMesh, batch);
  19369. engine.setDepthWrite(savedDepthWrite);
  19370. }
  19371. var effect;
  19372. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19373. effect = subMesh.effect;
  19374. }
  19375. else {
  19376. effect = effectiveMaterial.getEffect();
  19377. }
  19378. effectiveMaterial._preBind(effect);
  19379. // Bind
  19380. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19381. this._bind(subMesh, effect, fillMode);
  19382. var world = this.getWorldMatrix();
  19383. if (effectiveMaterial.storeEffectOnSubMeshes) {
  19384. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  19385. }
  19386. else {
  19387. effectiveMaterial.bind(world, this);
  19388. }
  19389. // Alpha mode
  19390. if (enableAlphaMode) {
  19391. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19392. }
  19393. // Draw
  19394. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  19395. // Unbind
  19396. effectiveMaterial.unbind();
  19397. // Outline - step 2
  19398. if (this.renderOutline && savedDepthWrite) {
  19399. engine.setDepthWrite(true);
  19400. engine.setColorWrite(false);
  19401. scene.getOutlineRenderer().render(subMesh, batch);
  19402. engine.setColorWrite(true);
  19403. }
  19404. // Overlay
  19405. if (this.renderOverlay) {
  19406. var currentMode = engine.getAlphaMode();
  19407. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19408. scene.getOutlineRenderer().render(subMesh, batch, true);
  19409. engine.setAlphaMode(currentMode);
  19410. }
  19411. this.onAfterRenderObservable.notifyObservers(this);
  19412. return this;
  19413. };
  19414. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19415. if (isInstance) {
  19416. effectiveMaterial.bindOnlyWorldMatrix(world);
  19417. }
  19418. return this;
  19419. };
  19420. /**
  19421. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19422. */
  19423. Mesh.prototype.getEmittedParticleSystems = function () {
  19424. var results = new Array();
  19425. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19426. var particleSystem = this.getScene().particleSystems[index];
  19427. if (particleSystem.emitter === this) {
  19428. results.push(particleSystem);
  19429. }
  19430. }
  19431. return results;
  19432. };
  19433. /**
  19434. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19435. */
  19436. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19437. var results = new Array();
  19438. var descendants = this.getDescendants();
  19439. descendants.push(this);
  19440. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19441. var particleSystem = this.getScene().particleSystems[index];
  19442. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19443. results.push(particleSystem);
  19444. }
  19445. }
  19446. return results;
  19447. };
  19448. Mesh.prototype._checkDelayState = function () {
  19449. var scene = this.getScene();
  19450. if (this._geometry) {
  19451. this._geometry.load(scene);
  19452. }
  19453. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19454. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19455. this._queueLoad(this, scene);
  19456. }
  19457. return this;
  19458. };
  19459. Mesh.prototype._queueLoad = function (mesh, scene) {
  19460. var _this = this;
  19461. scene._addPendingData(mesh);
  19462. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19463. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19464. if (data instanceof ArrayBuffer) {
  19465. _this._delayLoadingFunction(data, _this);
  19466. }
  19467. else {
  19468. _this._delayLoadingFunction(JSON.parse(data), _this);
  19469. }
  19470. _this.instances.forEach(function (instance) {
  19471. instance._syncSubMeshes();
  19472. });
  19473. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19474. scene._removePendingData(_this);
  19475. }, function () { }, scene.database, getBinaryData);
  19476. return this;
  19477. };
  19478. /**
  19479. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19480. */
  19481. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  19482. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19483. return false;
  19484. }
  19485. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  19486. return false;
  19487. }
  19488. this._checkDelayState();
  19489. return true;
  19490. };
  19491. /**
  19492. * Sets the mesh material by the material or multiMaterial `id` property.
  19493. * The material `id` is a string identifying the material or the multiMaterial.
  19494. * This method returns the Mesh.
  19495. */
  19496. Mesh.prototype.setMaterialByID = function (id) {
  19497. var materials = this.getScene().materials;
  19498. var index;
  19499. for (index = 0; index < materials.length; index++) {
  19500. if (materials[index].id === id) {
  19501. this.material = materials[index];
  19502. return this;
  19503. }
  19504. }
  19505. // Multi
  19506. var multiMaterials = this.getScene().multiMaterials;
  19507. for (index = 0; index < multiMaterials.length; index++) {
  19508. if (multiMaterials[index].id === id) {
  19509. this.material = multiMaterials[index];
  19510. return this;
  19511. }
  19512. }
  19513. return this;
  19514. };
  19515. /**
  19516. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  19517. */
  19518. Mesh.prototype.getAnimatables = function () {
  19519. var results = [];
  19520. if (this.material) {
  19521. results.push(this.material);
  19522. }
  19523. if (this.skeleton) {
  19524. results.push(this.skeleton);
  19525. }
  19526. return results;
  19527. };
  19528. /**
  19529. * Modifies the mesh geometry according to the passed transformation matrix.
  19530. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  19531. * The mesh normals are modified accordingly the same transformation.
  19532. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19533. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19534. * Returns the Mesh.
  19535. */
  19536. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  19537. // Position
  19538. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19539. return this;
  19540. }
  19541. var submeshes = this.subMeshes.splice(0);
  19542. this._resetPointsArrayCache();
  19543. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19544. var temp = [];
  19545. var index;
  19546. for (index = 0; index < data.length; index += 3) {
  19547. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  19548. }
  19549. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  19550. // Normals
  19551. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19552. return this;
  19553. }
  19554. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19555. temp = [];
  19556. for (index = 0; index < data.length; index += 3) {
  19557. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  19558. }
  19559. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  19560. // flip faces?
  19561. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  19562. this.flipFaces();
  19563. }
  19564. // Restore submeshes
  19565. this.releaseSubMeshes();
  19566. this.subMeshes = submeshes;
  19567. return this;
  19568. };
  19569. /**
  19570. * Modifies the mesh geometry according to its own current World Matrix.
  19571. * The mesh World Matrix is then reset.
  19572. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  19573. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19574. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19575. * Returns the Mesh.
  19576. */
  19577. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  19578. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  19579. this.scaling.copyFromFloats(1, 1, 1);
  19580. this.position.copyFromFloats(0, 0, 0);
  19581. this.rotation.copyFromFloats(0, 0, 0);
  19582. //only if quaternion is already set
  19583. if (this.rotationQuaternion) {
  19584. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  19585. }
  19586. this._worldMatrix = BABYLON.Matrix.Identity();
  19587. return this;
  19588. };
  19589. // Cache
  19590. Mesh.prototype._resetPointsArrayCache = function () {
  19591. this._positions = null;
  19592. return this;
  19593. };
  19594. Mesh.prototype._generatePointsArray = function () {
  19595. if (this._positions)
  19596. return true;
  19597. this._positions = [];
  19598. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19599. if (!data) {
  19600. return false;
  19601. }
  19602. for (var index = 0; index < data.length; index += 3) {
  19603. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  19604. }
  19605. return true;
  19606. };
  19607. /**
  19608. * Returns a new Mesh object generated from the current mesh properties.
  19609. * This method must not get confused with createInstance().
  19610. * The parameter `name` is a string, the name given to the new mesh.
  19611. * The optional parameter `newParent` can be any Node object (default `null`).
  19612. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  19613. * 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.
  19614. */
  19615. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  19616. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19617. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  19618. };
  19619. /**
  19620. * Disposes the mesh.
  19621. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  19622. */
  19623. Mesh.prototype.dispose = function (doNotRecurse) {
  19624. var _this = this;
  19625. this.morphTargetManager = undefined;
  19626. if (this._geometry) {
  19627. this._geometry.releaseForMesh(this, true);
  19628. }
  19629. // Sources
  19630. var meshes = this.getScene().meshes;
  19631. meshes.forEach(function (mesh) {
  19632. if (mesh._source && mesh._source === _this) {
  19633. mesh._source = null;
  19634. }
  19635. });
  19636. this._source = null;
  19637. // Instances
  19638. if (this._instancesBuffer) {
  19639. this._instancesBuffer.dispose();
  19640. this._instancesBuffer = null;
  19641. }
  19642. while (this.instances.length) {
  19643. this.instances[0].dispose();
  19644. }
  19645. // Highlight layers.
  19646. var highlightLayers = this.getScene().highlightLayers;
  19647. for (var i = 0; i < highlightLayers.length; i++) {
  19648. var highlightLayer = highlightLayers[i];
  19649. if (highlightLayer) {
  19650. highlightLayer.removeMesh(this);
  19651. highlightLayer.removeExcludedMesh(this);
  19652. }
  19653. }
  19654. _super.prototype.dispose.call(this, doNotRecurse);
  19655. };
  19656. /**
  19657. * Modifies the mesh geometry according to a displacement map.
  19658. * 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.
  19659. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19660. * This method returns nothing.
  19661. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19662. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19663. * 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.
  19664. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  19665. * The parameter `uvScale` is an optional vector2 used to scale UV.
  19666. *
  19667. * Returns the Mesh.
  19668. */
  19669. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  19670. var _this = this;
  19671. var scene = this.getScene();
  19672. var onload = function (img) {
  19673. // Getting height map data
  19674. var canvas = document.createElement("canvas");
  19675. var context = canvas.getContext("2d");
  19676. var heightMapWidth = img.width;
  19677. var heightMapHeight = img.height;
  19678. canvas.width = heightMapWidth;
  19679. canvas.height = heightMapHeight;
  19680. context.drawImage(img, 0, 0);
  19681. // Create VertexData from map data
  19682. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19683. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19684. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  19685. //execute success callback, if set
  19686. if (onSuccess) {
  19687. onSuccess(_this);
  19688. }
  19689. };
  19690. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19691. return this;
  19692. };
  19693. /**
  19694. * Modifies the mesh geometry according to a displacementMap buffer.
  19695. * 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.
  19696. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19697. * This method returns nothing.
  19698. * 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.
  19699. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19700. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19701. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  19702. * The parameter `uvScale` is an optional vector2 used to scale UV.
  19703. *
  19704. * Returns the Mesh.
  19705. */
  19706. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  19707. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19708. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19709. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19710. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19711. return this;
  19712. }
  19713. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19714. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19715. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19716. var position = BABYLON.Vector3.Zero();
  19717. var normal = BABYLON.Vector3.Zero();
  19718. var uv = BABYLON.Vector2.Zero();
  19719. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  19720. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  19721. for (var index = 0; index < positions.length; index += 3) {
  19722. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19723. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19724. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19725. // Compute height
  19726. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  19727. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  19728. var pos = (u + v * heightMapWidth) * 4;
  19729. var r = buffer[pos] / 255.0;
  19730. var g = buffer[pos + 1] / 255.0;
  19731. var b = buffer[pos + 2] / 255.0;
  19732. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19733. normal.normalize();
  19734. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19735. position = position.add(normal);
  19736. position.toArray(positions, index);
  19737. }
  19738. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  19739. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  19740. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19741. return this;
  19742. };
  19743. /**
  19744. * Modify the mesh to get a flat shading rendering.
  19745. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  19746. * This method returns the Mesh.
  19747. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  19748. */
  19749. Mesh.prototype.convertToFlatShadedMesh = function () {
  19750. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  19751. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19752. var kinds = this.getVerticesDataKinds();
  19753. var vbs = [];
  19754. var data = [];
  19755. var newdata = [];
  19756. var updatableNormals = false;
  19757. var kindIndex;
  19758. var kind;
  19759. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19760. kind = kinds[kindIndex];
  19761. var vertexBuffer = this.getVertexBuffer(kind);
  19762. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19763. updatableNormals = vertexBuffer.isUpdatable();
  19764. kinds.splice(kindIndex, 1);
  19765. kindIndex--;
  19766. continue;
  19767. }
  19768. vbs[kind] = vertexBuffer;
  19769. data[kind] = vbs[kind].getData();
  19770. newdata[kind] = [];
  19771. }
  19772. // Save previous submeshes
  19773. var previousSubmeshes = this.subMeshes.slice(0);
  19774. var indices = this.getIndices();
  19775. var totalIndices = this.getTotalIndices();
  19776. // Generating unique vertices per face
  19777. var index;
  19778. for (index = 0; index < totalIndices; index++) {
  19779. var vertexIndex = indices[index];
  19780. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19781. kind = kinds[kindIndex];
  19782. var stride = vbs[kind].getStrideSize();
  19783. for (var offset = 0; offset < stride; offset++) {
  19784. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19785. }
  19786. }
  19787. }
  19788. // Updating faces & normal
  19789. var normals = [];
  19790. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19791. for (index = 0; index < totalIndices; index += 3) {
  19792. indices[index] = index;
  19793. indices[index + 1] = index + 1;
  19794. indices[index + 2] = index + 2;
  19795. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19796. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19797. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19798. var p1p2 = p1.subtract(p2);
  19799. var p3p2 = p3.subtract(p2);
  19800. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19801. // Store same normals for every vertex
  19802. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19803. normals.push(normal.x);
  19804. normals.push(normal.y);
  19805. normals.push(normal.z);
  19806. }
  19807. }
  19808. this.setIndices(indices);
  19809. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19810. // Updating vertex buffers
  19811. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19812. kind = kinds[kindIndex];
  19813. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19814. }
  19815. // Updating submeshes
  19816. this.releaseSubMeshes();
  19817. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19818. var previousOne = previousSubmeshes[submeshIndex];
  19819. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19820. }
  19821. this.synchronizeInstances();
  19822. return this;
  19823. };
  19824. /**
  19825. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  19826. * In other words, more vertices, no more indices and a single bigger VBO.
  19827. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  19828. * Returns the Mesh.
  19829. */
  19830. Mesh.prototype.convertToUnIndexedMesh = function () {
  19831. /// <summary>Remove indices by unfolding faces into buffers</summary>
  19832. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19833. var kinds = this.getVerticesDataKinds();
  19834. var vbs = [];
  19835. var data = [];
  19836. var newdata = [];
  19837. var updatableNormals = false;
  19838. var kindIndex;
  19839. var kind;
  19840. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19841. kind = kinds[kindIndex];
  19842. var vertexBuffer = this.getVertexBuffer(kind);
  19843. vbs[kind] = vertexBuffer;
  19844. data[kind] = vbs[kind].getData();
  19845. newdata[kind] = [];
  19846. }
  19847. // Save previous submeshes
  19848. var previousSubmeshes = this.subMeshes.slice(0);
  19849. var indices = this.getIndices();
  19850. var totalIndices = this.getTotalIndices();
  19851. // Generating unique vertices per face
  19852. var index;
  19853. for (index = 0; index < totalIndices; index++) {
  19854. var vertexIndex = indices[index];
  19855. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19856. kind = kinds[kindIndex];
  19857. var stride = vbs[kind].getStrideSize();
  19858. for (var offset = 0; offset < stride; offset++) {
  19859. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19860. }
  19861. }
  19862. }
  19863. // Updating indices
  19864. for (index = 0; index < totalIndices; index += 3) {
  19865. indices[index] = index;
  19866. indices[index + 1] = index + 1;
  19867. indices[index + 2] = index + 2;
  19868. }
  19869. this.setIndices(indices);
  19870. // Updating vertex buffers
  19871. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19872. kind = kinds[kindIndex];
  19873. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19874. }
  19875. // Updating submeshes
  19876. this.releaseSubMeshes();
  19877. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19878. var previousOne = previousSubmeshes[submeshIndex];
  19879. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19880. }
  19881. this._unIndexed = true;
  19882. this.synchronizeInstances();
  19883. return this;
  19884. };
  19885. /**
  19886. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  19887. * This method returns the Mesh.
  19888. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  19889. */
  19890. Mesh.prototype.flipFaces = function (flipNormals) {
  19891. if (flipNormals === void 0) { flipNormals = false; }
  19892. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  19893. var i;
  19894. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19895. for (i = 0; i < vertex_data.normals.length; i++) {
  19896. vertex_data.normals[i] *= -1;
  19897. }
  19898. }
  19899. var temp;
  19900. for (i = 0; i < vertex_data.indices.length; i += 3) {
  19901. // reassign indices
  19902. temp = vertex_data.indices[i + 1];
  19903. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  19904. vertex_data.indices[i + 2] = temp;
  19905. }
  19906. vertex_data.applyToMesh(this);
  19907. return this;
  19908. };
  19909. // Instances
  19910. /**
  19911. * Creates a new InstancedMesh object from the mesh model.
  19912. * An instance shares the same properties and the same material than its model.
  19913. * Only these properties of each instance can then be set individually :
  19914. * - position
  19915. * - rotation
  19916. * - rotationQuaternion
  19917. * - setPivotMatrix
  19918. * - scaling
  19919. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  19920. * Warning : this method is not supported for Line mesh and LineSystem
  19921. */
  19922. Mesh.prototype.createInstance = function (name) {
  19923. return new BABYLON.InstancedMesh(name, this);
  19924. };
  19925. /**
  19926. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  19927. * After this call, all the mesh instances have the same submeshes than the current mesh.
  19928. * This method returns the Mesh.
  19929. */
  19930. Mesh.prototype.synchronizeInstances = function () {
  19931. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  19932. var instance = this.instances[instanceIndex];
  19933. instance._syncSubMeshes();
  19934. }
  19935. return this;
  19936. };
  19937. /**
  19938. * Simplify the mesh according to the given array of settings.
  19939. * Function will return immediately and will simplify async. It returns the Mesh.
  19940. * @param settings a collection of simplification settings.
  19941. * @param parallelProcessing should all levels calculate parallel or one after the other.
  19942. * @param type the type of simplification to run.
  19943. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  19944. */
  19945. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  19946. if (parallelProcessing === void 0) { parallelProcessing = true; }
  19947. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  19948. this.getScene().simplificationQueue.addTask({
  19949. settings: settings,
  19950. parallelProcessing: parallelProcessing,
  19951. mesh: this,
  19952. simplificationType: simplificationType,
  19953. successCallback: successCallback
  19954. });
  19955. return this;
  19956. };
  19957. /**
  19958. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  19959. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  19960. * This should be used together with the simplification to avoid disappearing triangles.
  19961. * Returns the Mesh.
  19962. * @param successCallback an optional success callback to be called after the optimization finished.
  19963. */
  19964. Mesh.prototype.optimizeIndices = function (successCallback) {
  19965. var _this = this;
  19966. var indices = this.getIndices();
  19967. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19968. var vectorPositions = [];
  19969. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  19970. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  19971. }
  19972. var dupes = [];
  19973. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  19974. var realPos = vectorPositions.length - 1 - iteration;
  19975. var testedPosition = vectorPositions[realPos];
  19976. for (var j = 0; j < realPos; ++j) {
  19977. var againstPosition = vectorPositions[j];
  19978. if (testedPosition.equals(againstPosition)) {
  19979. dupes[realPos] = j;
  19980. break;
  19981. }
  19982. }
  19983. }, function () {
  19984. for (var i = 0; i < indices.length; ++i) {
  19985. indices[i] = dupes[indices[i]] || indices[i];
  19986. }
  19987. //indices are now reordered
  19988. var originalSubMeshes = _this.subMeshes.slice(0);
  19989. _this.setIndices(indices);
  19990. _this.subMeshes = originalSubMeshes;
  19991. if (successCallback) {
  19992. successCallback(_this);
  19993. }
  19994. });
  19995. return this;
  19996. };
  19997. Mesh.prototype.serialize = function (serializationObject) {
  19998. serializationObject.name = this.name;
  19999. serializationObject.id = this.id;
  20000. serializationObject.type = this.getClassName();
  20001. if (BABYLON.Tags.HasTags(this)) {
  20002. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20003. }
  20004. serializationObject.position = this.position.asArray();
  20005. if (this.rotationQuaternion) {
  20006. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  20007. }
  20008. else if (this.rotation) {
  20009. serializationObject.rotation = this.rotation.asArray();
  20010. }
  20011. serializationObject.scaling = this.scaling.asArray();
  20012. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20013. serializationObject.isEnabled = this.isEnabled();
  20014. serializationObject.isVisible = this.isVisible;
  20015. serializationObject.infiniteDistance = this.infiniteDistance;
  20016. serializationObject.pickable = this.isPickable;
  20017. serializationObject.receiveShadows = this.receiveShadows;
  20018. serializationObject.billboardMode = this.billboardMode;
  20019. serializationObject.visibility = this.visibility;
  20020. serializationObject.checkCollisions = this.checkCollisions;
  20021. serializationObject.isBlocker = this.isBlocker;
  20022. // Parent
  20023. if (this.parent) {
  20024. serializationObject.parentId = this.parent.id;
  20025. }
  20026. // Geometry
  20027. var geometry = this._geometry;
  20028. if (geometry) {
  20029. var geometryId = geometry.id;
  20030. serializationObject.geometryId = geometryId;
  20031. // SubMeshes
  20032. serializationObject.subMeshes = [];
  20033. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20034. var subMesh = this.subMeshes[subIndex];
  20035. serializationObject.subMeshes.push({
  20036. materialIndex: subMesh.materialIndex,
  20037. verticesStart: subMesh.verticesStart,
  20038. verticesCount: subMesh.verticesCount,
  20039. indexStart: subMesh.indexStart,
  20040. indexCount: subMesh.indexCount
  20041. });
  20042. }
  20043. }
  20044. // Material
  20045. if (this.material) {
  20046. serializationObject.materialId = this.material.id;
  20047. }
  20048. else {
  20049. this.material = null;
  20050. }
  20051. // Morph targets
  20052. if (this.morphTargetManager) {
  20053. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  20054. }
  20055. // Skeleton
  20056. if (this.skeleton) {
  20057. serializationObject.skeletonId = this.skeleton.id;
  20058. }
  20059. // Physics
  20060. //TODO implement correct serialization for physics impostors.
  20061. if (this.getPhysicsImpostor()) {
  20062. var impostor = this.getPhysicsImpostor();
  20063. serializationObject.physicsMass = impostor.getParam("mass");
  20064. serializationObject.physicsFriction = impostor.getParam("friction");
  20065. serializationObject.physicsRestitution = impostor.getParam("mass");
  20066. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  20067. }
  20068. // Metadata
  20069. if (this.metadata) {
  20070. serializationObject.metadata = this.metadata;
  20071. }
  20072. // Instances
  20073. serializationObject.instances = [];
  20074. for (var index = 0; index < this.instances.length; index++) {
  20075. var instance = this.instances[index];
  20076. var serializationInstance = {
  20077. name: instance.name,
  20078. position: instance.position.asArray(),
  20079. scaling: instance.scaling.asArray()
  20080. };
  20081. if (instance.rotationQuaternion) {
  20082. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  20083. }
  20084. else if (instance.rotation) {
  20085. serializationInstance.rotation = instance.rotation.asArray();
  20086. }
  20087. serializationObject.instances.push(serializationInstance);
  20088. // Animations
  20089. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  20090. serializationInstance.ranges = instance.serializeAnimationRanges();
  20091. }
  20092. //
  20093. // Animations
  20094. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20095. serializationObject.ranges = this.serializeAnimationRanges();
  20096. // Layer mask
  20097. serializationObject.layerMask = this.layerMask;
  20098. // Alpha
  20099. serializationObject.alphaIndex = this.alphaIndex;
  20100. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  20101. // Overlay
  20102. serializationObject.overlayAlpha = this.overlayAlpha;
  20103. serializationObject.overlayColor = this.overlayColor.asArray();
  20104. serializationObject.renderOverlay = this.renderOverlay;
  20105. // Fog
  20106. serializationObject.applyFog = this.applyFog;
  20107. // Action Manager
  20108. if (this.actionManager) {
  20109. serializationObject.actions = this.actionManager.serialize(this.name);
  20110. }
  20111. };
  20112. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  20113. if (!this.geometry) {
  20114. return;
  20115. }
  20116. this._markSubMeshesAsAttributesDirty();
  20117. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  20118. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  20119. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  20120. this.morphTargetManager = undefined;
  20121. return;
  20122. }
  20123. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  20124. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  20125. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  20126. if (morphTarget.hasNormals) {
  20127. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  20128. }
  20129. if (morphTarget.hasTangents) {
  20130. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  20131. }
  20132. }
  20133. }
  20134. else {
  20135. var index = 0;
  20136. // Positions
  20137. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  20138. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  20139. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  20140. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  20141. }
  20142. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  20143. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  20144. }
  20145. index++;
  20146. }
  20147. }
  20148. };
  20149. // Statics
  20150. /**
  20151. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20152. * The parameter `parsedMesh` is the mesh to be copied.
  20153. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20154. */
  20155. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20156. var mesh;
  20157. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  20158. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  20159. }
  20160. else {
  20161. mesh = new Mesh(parsedMesh.name, scene);
  20162. }
  20163. mesh.id = parsedMesh.id;
  20164. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20165. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20166. if (parsedMesh.metadata !== undefined) {
  20167. mesh.metadata = parsedMesh.metadata;
  20168. }
  20169. if (parsedMesh.rotationQuaternion) {
  20170. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20171. }
  20172. else if (parsedMesh.rotation) {
  20173. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20174. }
  20175. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20176. if (parsedMesh.localMatrix) {
  20177. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20178. }
  20179. else if (parsedMesh.pivotMatrix) {
  20180. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20181. }
  20182. mesh.setEnabled(parsedMesh.isEnabled);
  20183. mesh.isVisible = parsedMesh.isVisible;
  20184. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20185. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20186. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20187. if (parsedMesh.applyFog !== undefined) {
  20188. mesh.applyFog = parsedMesh.applyFog;
  20189. }
  20190. if (parsedMesh.pickable !== undefined) {
  20191. mesh.isPickable = parsedMesh.pickable;
  20192. }
  20193. if (parsedMesh.alphaIndex !== undefined) {
  20194. mesh.alphaIndex = parsedMesh.alphaIndex;
  20195. }
  20196. mesh.receiveShadows = parsedMesh.receiveShadows;
  20197. mesh.billboardMode = parsedMesh.billboardMode;
  20198. if (parsedMesh.visibility !== undefined) {
  20199. mesh.visibility = parsedMesh.visibility;
  20200. }
  20201. mesh.checkCollisions = parsedMesh.checkCollisions;
  20202. if (parsedMesh.isBlocker !== undefined) {
  20203. mesh.isBlocker = parsedMesh.isBlocker;
  20204. }
  20205. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20206. // freezeWorldMatrix
  20207. if (parsedMesh.freezeWorldMatrix) {
  20208. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20209. }
  20210. // Parent
  20211. if (parsedMesh.parentId) {
  20212. mesh._waitingParentId = parsedMesh.parentId;
  20213. }
  20214. // Actions
  20215. if (parsedMesh.actions !== undefined) {
  20216. mesh._waitingActions = parsedMesh.actions;
  20217. }
  20218. // Overlay
  20219. if (parsedMesh.overlayAlpha !== undefined) {
  20220. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  20221. }
  20222. if (parsedMesh.overlayColor !== undefined) {
  20223. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  20224. }
  20225. if (parsedMesh.renderOverlay !== undefined) {
  20226. mesh.renderOverlay = parsedMesh.renderOverlay;
  20227. }
  20228. // Geometry
  20229. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20230. if (parsedMesh.delayLoadingFile) {
  20231. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20232. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20233. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20234. if (parsedMesh._binaryInfo) {
  20235. mesh._binaryInfo = parsedMesh._binaryInfo;
  20236. }
  20237. mesh._delayInfo = [];
  20238. if (parsedMesh.hasUVs) {
  20239. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20240. }
  20241. if (parsedMesh.hasUVs2) {
  20242. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20243. }
  20244. if (parsedMesh.hasUVs3) {
  20245. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20246. }
  20247. if (parsedMesh.hasUVs4) {
  20248. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20249. }
  20250. if (parsedMesh.hasUVs5) {
  20251. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20252. }
  20253. if (parsedMesh.hasUVs6) {
  20254. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20255. }
  20256. if (parsedMesh.hasColors) {
  20257. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20258. }
  20259. if (parsedMesh.hasMatricesIndices) {
  20260. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20261. }
  20262. if (parsedMesh.hasMatricesWeights) {
  20263. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20264. }
  20265. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20266. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20267. mesh._checkDelayState();
  20268. }
  20269. }
  20270. else {
  20271. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20272. }
  20273. // Material
  20274. if (parsedMesh.materialId) {
  20275. mesh.setMaterialByID(parsedMesh.materialId);
  20276. }
  20277. else {
  20278. mesh.material = null;
  20279. }
  20280. // Morph targets
  20281. if (parsedMesh.morphTargetManagerId > -1) {
  20282. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  20283. }
  20284. // Skeleton
  20285. if (parsedMesh.skeletonId > -1) {
  20286. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20287. if (parsedMesh.numBoneInfluencers) {
  20288. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20289. }
  20290. }
  20291. // Animations
  20292. if (parsedMesh.animations) {
  20293. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20294. var parsedAnimation = parsedMesh.animations[animationIndex];
  20295. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20296. }
  20297. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20298. }
  20299. if (parsedMesh.autoAnimate) {
  20300. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20301. }
  20302. // Layer Mask
  20303. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20304. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20305. }
  20306. else {
  20307. mesh.layerMask = 0x0FFFFFFF;
  20308. }
  20309. // Physics
  20310. if (parsedMesh.physicsImpostor) {
  20311. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20312. mass: parsedMesh.physicsMass,
  20313. friction: parsedMesh.physicsFriction,
  20314. restitution: parsedMesh.physicsRestitution
  20315. }, scene);
  20316. }
  20317. // Instances
  20318. if (parsedMesh.instances) {
  20319. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20320. var parsedInstance = parsedMesh.instances[index];
  20321. var instance = mesh.createInstance(parsedInstance.name);
  20322. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20323. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20324. if (parsedInstance.parentId) {
  20325. instance._waitingParentId = parsedInstance.parentId;
  20326. }
  20327. if (parsedInstance.rotationQuaternion) {
  20328. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20329. }
  20330. else if (parsedInstance.rotation) {
  20331. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20332. }
  20333. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20334. instance.checkCollisions = mesh.checkCollisions;
  20335. if (parsedMesh.animations) {
  20336. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20337. parsedAnimation = parsedMesh.animations[animationIndex];
  20338. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20339. }
  20340. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20341. }
  20342. }
  20343. }
  20344. return mesh;
  20345. };
  20346. /**
  20347. * Creates a ribbon mesh.
  20348. * Please consider using the same method from the MeshBuilder class instead.
  20349. * 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.
  20350. *
  20351. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20352. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20353. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20354. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20355. * 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.
  20356. * 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.
  20357. * 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
  20358. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20359. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20360. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20361. */
  20362. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20363. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20364. pathArray: pathArray,
  20365. closeArray: closeArray,
  20366. closePath: closePath,
  20367. offset: offset,
  20368. updatable: updatable,
  20369. sideOrientation: sideOrientation,
  20370. instance: instance
  20371. }, scene);
  20372. };
  20373. /**
  20374. * Creates a plane polygonal mesh. By default, this is a disc.
  20375. * Please consider using the same method from the MeshBuilder class instead.
  20376. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20377. * 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.
  20378. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20379. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20380. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20381. */
  20382. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20383. var options = {
  20384. radius: radius,
  20385. tessellation: tessellation,
  20386. sideOrientation: sideOrientation,
  20387. updatable: updatable
  20388. };
  20389. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20390. };
  20391. /**
  20392. * Creates a box mesh.
  20393. * Please consider using the same method from the MeshBuilder class instead.
  20394. * The parameter `size` sets the size (float) of each box side (default 1).
  20395. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20396. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20397. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20398. */
  20399. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20400. var options = {
  20401. size: size,
  20402. sideOrientation: sideOrientation,
  20403. updatable: updatable
  20404. };
  20405. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20406. };
  20407. /**
  20408. * Creates a sphere mesh.
  20409. * Please consider using the same method from the MeshBuilder class instead.
  20410. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20411. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20412. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20413. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20414. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20415. */
  20416. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20417. var options = {
  20418. segments: segments,
  20419. diameterX: diameter,
  20420. diameterY: diameter,
  20421. diameterZ: diameter,
  20422. sideOrientation: sideOrientation,
  20423. updatable: updatable
  20424. };
  20425. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20426. };
  20427. /**
  20428. * Creates a cylinder or a cone mesh.
  20429. * Please consider using the same method from the MeshBuilder class instead.
  20430. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20431. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20432. * 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.
  20433. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20434. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20435. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20436. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20437. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20438. */
  20439. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20440. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20441. if (scene !== undefined) {
  20442. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20443. updatable = scene;
  20444. }
  20445. scene = subdivisions;
  20446. subdivisions = 1;
  20447. }
  20448. var options = {
  20449. height: height,
  20450. diameterTop: diameterTop,
  20451. diameterBottom: diameterBottom,
  20452. tessellation: tessellation,
  20453. subdivisions: subdivisions,
  20454. sideOrientation: sideOrientation,
  20455. updatable: updatable
  20456. };
  20457. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20458. };
  20459. // Torus (Code from SharpDX.org)
  20460. /**
  20461. * Creates a torus mesh.
  20462. * Please consider using the same method from the MeshBuilder class instead.
  20463. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20464. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20465. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20466. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20467. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20468. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20469. */
  20470. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20471. var options = {
  20472. diameter: diameter,
  20473. thickness: thickness,
  20474. tessellation: tessellation,
  20475. sideOrientation: sideOrientation,
  20476. updatable: updatable
  20477. };
  20478. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20479. };
  20480. /**
  20481. * Creates a torus knot mesh.
  20482. * Please consider using the same method from the MeshBuilder class instead.
  20483. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20484. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20485. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20486. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20487. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20488. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20489. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20490. */
  20491. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20492. var options = {
  20493. radius: radius,
  20494. tube: tube,
  20495. radialSegments: radialSegments,
  20496. tubularSegments: tubularSegments,
  20497. p: p,
  20498. q: q,
  20499. sideOrientation: sideOrientation,
  20500. updatable: updatable
  20501. };
  20502. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20503. };
  20504. /**
  20505. * Creates a line mesh.
  20506. * Please consider using the same method from the MeshBuilder class instead.
  20507. * 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.
  20508. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20509. * The parameter `points` is an array successive Vector3.
  20510. * 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
  20511. * When updating an instance, remember that only point positions can change, not the number of points.
  20512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20513. */
  20514. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20515. var options = {
  20516. points: points,
  20517. updatable: updatable,
  20518. instance: instance
  20519. };
  20520. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20521. };
  20522. /**
  20523. * Creates a dashed line mesh.
  20524. * Please consider using the same method from the MeshBuilder class instead.
  20525. * 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.
  20526. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20527. * The parameter `points` is an array successive Vector3.
  20528. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20529. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20530. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20531. * 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
  20532. * When updating an instance, remember that only point positions can change, not the number of points.
  20533. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20534. */
  20535. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20536. var options = {
  20537. points: points,
  20538. dashSize: dashSize,
  20539. gapSize: gapSize,
  20540. dashNb: dashNb,
  20541. updatable: updatable,
  20542. instance: instance
  20543. };
  20544. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20545. };
  20546. /**
  20547. * Creates an extruded shape mesh.
  20548. * 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.
  20549. * Please consider using the same method from the MeshBuilder class instead.
  20550. *
  20551. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20552. * 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
  20553. * extruded along the Z axis.
  20554. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20555. * 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.
  20556. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20557. * 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
  20558. * 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
  20559. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20560. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20561. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20562. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20563. */
  20564. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20565. var options = {
  20566. shape: shape,
  20567. path: path,
  20568. scale: scale,
  20569. rotation: rotation,
  20570. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20571. sideOrientation: sideOrientation,
  20572. instance: instance,
  20573. updatable: updatable
  20574. };
  20575. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20576. };
  20577. /**
  20578. * Creates an custom extruded shape mesh.
  20579. * 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.
  20580. * Please consider using the same method from the MeshBuilder class instead.
  20581. *
  20582. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20583. * 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
  20584. * extruded along the Z axis.
  20585. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20586. * 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
  20587. * and the distance of this point from the begining of the path :
  20588. * ```javascript
  20589. * var rotationFunction = function(i, distance) {
  20590. * // do things
  20591. * return rotationValue; }
  20592. * ```
  20593. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20594. * 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
  20595. * and the distance of this point from the begining of the path :
  20596. * ```javascript
  20597. * var scaleFunction = function(i, distance) {
  20598. * // do things
  20599. * return scaleValue;}
  20600. * ```
  20601. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20602. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20603. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20604. * 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
  20605. * 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
  20606. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20607. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20608. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20609. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20610. */
  20611. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20612. var options = {
  20613. shape: shape,
  20614. path: path,
  20615. scaleFunction: scaleFunction,
  20616. rotationFunction: rotationFunction,
  20617. ribbonCloseArray: ribbonCloseArray,
  20618. ribbonClosePath: ribbonClosePath,
  20619. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20620. sideOrientation: sideOrientation,
  20621. instance: instance,
  20622. updatable: updatable
  20623. };
  20624. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20625. };
  20626. /**
  20627. * Creates lathe mesh.
  20628. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20629. * Please consider using the same method from the MeshBuilder class instead.
  20630. * 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
  20631. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20632. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20633. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20634. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20635. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20636. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20637. */
  20638. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20639. var options = {
  20640. shape: shape,
  20641. radius: radius,
  20642. tessellation: tessellation,
  20643. sideOrientation: sideOrientation,
  20644. updatable: updatable
  20645. };
  20646. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20647. };
  20648. /**
  20649. * Creates a plane mesh.
  20650. * Please consider using the same method from the MeshBuilder class instead.
  20651. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20652. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20653. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20654. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20655. */
  20656. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20657. var options = {
  20658. size: size,
  20659. width: size,
  20660. height: size,
  20661. sideOrientation: sideOrientation,
  20662. updatable: updatable
  20663. };
  20664. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20665. };
  20666. /**
  20667. * Creates a ground mesh.
  20668. * Please consider using the same method from the MeshBuilder class instead.
  20669. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20670. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20671. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20672. */
  20673. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20674. var options = {
  20675. width: width,
  20676. height: height,
  20677. subdivisions: subdivisions,
  20678. updatable: updatable
  20679. };
  20680. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20681. };
  20682. /**
  20683. * Creates a tiled ground mesh.
  20684. * Please consider using the same method from the MeshBuilder class instead.
  20685. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20686. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20687. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20688. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20689. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20690. * numbers of subdivisions on the ground width and height of each tile.
  20691. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20692. */
  20693. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  20694. var options = {
  20695. xmin: xmin,
  20696. zmin: zmin,
  20697. xmax: xmax,
  20698. zmax: zmax,
  20699. subdivisions: subdivisions,
  20700. precision: precision,
  20701. updatable: updatable
  20702. };
  20703. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  20704. };
  20705. /**
  20706. * Creates a ground mesh from a height map.
  20707. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20708. * Please consider using the same method from the MeshBuilder class instead.
  20709. * The parameter `url` sets the URL of the height map image resource.
  20710. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20711. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20712. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20713. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20714. * 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).
  20715. * This function is passed the newly built mesh :
  20716. * ```javascript
  20717. * function(mesh) { // do things
  20718. * return; }
  20719. * ```
  20720. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20721. */
  20722. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  20723. var options = {
  20724. width: width,
  20725. height: height,
  20726. subdivisions: subdivisions,
  20727. minHeight: minHeight,
  20728. maxHeight: maxHeight,
  20729. updatable: updatable,
  20730. onReady: onReady
  20731. };
  20732. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  20733. };
  20734. /**
  20735. * Creates a tube mesh.
  20736. * 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.
  20737. * Please consider using the same method from the MeshBuilder class instead.
  20738. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20739. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20740. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20741. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20742. * 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.
  20743. * It must return a radius value (positive float) :
  20744. * ```javascript
  20745. * var radiusFunction = function(i, distance) {
  20746. * // do things
  20747. * return radius; }
  20748. * ```
  20749. * 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
  20750. * 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
  20751. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20752. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20753. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20754. */
  20755. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  20756. var options = {
  20757. path: path,
  20758. radius: radius,
  20759. tessellation: tessellation,
  20760. radiusFunction: radiusFunction,
  20761. arc: 1,
  20762. cap: cap,
  20763. updatable: updatable,
  20764. sideOrientation: sideOrientation,
  20765. instance: instance
  20766. };
  20767. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  20768. };
  20769. /**
  20770. * Creates a polyhedron mesh.
  20771. * Please consider using the same method from the MeshBuilder class instead.
  20772. * 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
  20773. * to choose the wanted type.
  20774. * The parameter `size` (positive float, default 1) sets the polygon size.
  20775. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20776. * 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`.
  20777. * 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
  20778. * 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)`).
  20779. * 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
  20780. * 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.
  20781. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20782. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20783. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20784. */
  20785. Mesh.CreatePolyhedron = function (name, options, scene) {
  20786. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  20787. };
  20788. /**
  20789. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20790. * Please consider using the same method from the MeshBuilder class instead.
  20791. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20792. * 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`).
  20793. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20794. * 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.
  20795. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20796. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20797. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20798. */
  20799. Mesh.CreateIcoSphere = function (name, options, scene) {
  20800. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  20801. };
  20802. /**
  20803. * Creates a decal mesh.
  20804. * Please consider using the same method from the MeshBuilder class instead.
  20805. * 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.
  20806. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20807. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20808. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  20809. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20810. */
  20811. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  20812. var options = {
  20813. position: position,
  20814. normal: normal,
  20815. size: size,
  20816. angle: angle
  20817. };
  20818. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  20819. };
  20820. // Skeletons
  20821. /**
  20822. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20823. */
  20824. Mesh.prototype.setPositionsForCPUSkinning = function () {
  20825. var source;
  20826. if (!this._sourcePositions) {
  20827. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20828. this._sourcePositions = new Float32Array(source);
  20829. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  20830. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  20831. }
  20832. }
  20833. return this._sourcePositions;
  20834. };
  20835. /**
  20836. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20837. */
  20838. Mesh.prototype.setNormalsForCPUSkinning = function () {
  20839. var source;
  20840. if (!this._sourceNormals) {
  20841. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20842. this._sourceNormals = new Float32Array(source);
  20843. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  20844. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  20845. }
  20846. }
  20847. return this._sourceNormals;
  20848. };
  20849. /**
  20850. * Updates the vertex buffer by applying transformation from the bones.
  20851. * Returns the Mesh.
  20852. *
  20853. * @param {skeleton} skeleton to apply
  20854. */
  20855. Mesh.prototype.applySkeleton = function (skeleton) {
  20856. if (!this.geometry) {
  20857. return this;
  20858. }
  20859. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  20860. return this;
  20861. }
  20862. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  20863. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20864. return this;
  20865. }
  20866. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20867. return this;
  20868. }
  20869. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20870. return this;
  20871. }
  20872. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20873. return this;
  20874. }
  20875. if (!this._sourcePositions) {
  20876. var submeshes = this.subMeshes.slice();
  20877. this.setPositionsForCPUSkinning();
  20878. this.subMeshes = submeshes;
  20879. }
  20880. if (!this._sourceNormals) {
  20881. this.setNormalsForCPUSkinning();
  20882. }
  20883. // positionsData checks for not being Float32Array will only pass at most once
  20884. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20885. if (!(positionsData instanceof Float32Array)) {
  20886. positionsData = new Float32Array(positionsData);
  20887. }
  20888. // normalsData checks for not being Float32Array will only pass at most once
  20889. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20890. if (!(normalsData instanceof Float32Array)) {
  20891. normalsData = new Float32Array(normalsData);
  20892. }
  20893. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20894. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20895. var needExtras = this.numBoneInfluencers > 4;
  20896. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  20897. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  20898. var skeletonMatrices = skeleton.getTransformMatrices(this);
  20899. var tempVector3 = BABYLON.Vector3.Zero();
  20900. var finalMatrix = new BABYLON.Matrix();
  20901. var tempMatrix = new BABYLON.Matrix();
  20902. var matWeightIdx = 0;
  20903. var inf;
  20904. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  20905. var weight;
  20906. for (inf = 0; inf < 4; inf++) {
  20907. weight = matricesWeightsData[matWeightIdx + inf];
  20908. if (weight > 0) {
  20909. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20910. finalMatrix.addToSelf(tempMatrix);
  20911. }
  20912. else
  20913. break;
  20914. }
  20915. if (needExtras) {
  20916. for (inf = 0; inf < 4; inf++) {
  20917. weight = matricesWeightsExtraData[matWeightIdx + inf];
  20918. if (weight > 0) {
  20919. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20920. finalMatrix.addToSelf(tempMatrix);
  20921. }
  20922. else
  20923. break;
  20924. }
  20925. }
  20926. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  20927. tempVector3.toArray(positionsData, index);
  20928. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  20929. tempVector3.toArray(normalsData, index);
  20930. finalMatrix.reset();
  20931. }
  20932. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  20933. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  20934. return this;
  20935. };
  20936. // Tools
  20937. /**
  20938. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  20939. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  20940. */
  20941. Mesh.MinMax = function (meshes) {
  20942. var minVector = null;
  20943. var maxVector = null;
  20944. meshes.forEach(function (mesh, index, array) {
  20945. var boundingBox = mesh.getBoundingInfo().boundingBox;
  20946. if (!minVector) {
  20947. minVector = boundingBox.minimumWorld;
  20948. maxVector = boundingBox.maximumWorld;
  20949. }
  20950. else {
  20951. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  20952. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  20953. }
  20954. });
  20955. return {
  20956. min: minVector,
  20957. max: maxVector
  20958. };
  20959. };
  20960. /**
  20961. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  20962. */
  20963. Mesh.Center = function (meshesOrMinMaxVector) {
  20964. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  20965. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  20966. };
  20967. /**
  20968. * Merge the array of meshes into a single mesh for performance reasons.
  20969. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  20970. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  20971. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  20972. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  20973. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  20974. */
  20975. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  20976. if (disposeSource === void 0) { disposeSource = true; }
  20977. var index;
  20978. if (!allow32BitsIndices) {
  20979. var totalVertices = 0;
  20980. // Counting vertices
  20981. for (index = 0; index < meshes.length; index++) {
  20982. if (meshes[index]) {
  20983. totalVertices += meshes[index].getTotalVertices();
  20984. if (totalVertices > 65536) {
  20985. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  20986. return null;
  20987. }
  20988. }
  20989. }
  20990. }
  20991. // Merge
  20992. var vertexData;
  20993. var otherVertexData;
  20994. var indiceArray = new Array();
  20995. var source;
  20996. for (index = 0; index < meshes.length; index++) {
  20997. if (meshes[index]) {
  20998. meshes[index].computeWorldMatrix(true);
  20999. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21000. otherVertexData.transform(meshes[index].getWorldMatrix());
  21001. if (vertexData) {
  21002. vertexData.merge(otherVertexData);
  21003. }
  21004. else {
  21005. vertexData = otherVertexData;
  21006. source = meshes[index];
  21007. }
  21008. if (subdivideWithSubMeshes) {
  21009. indiceArray.push(meshes[index].getTotalIndices());
  21010. }
  21011. }
  21012. }
  21013. if (!meshSubclass) {
  21014. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21015. }
  21016. vertexData.applyToMesh(meshSubclass);
  21017. // Setting properties
  21018. meshSubclass.material = source.material;
  21019. meshSubclass.checkCollisions = source.checkCollisions;
  21020. // Cleaning
  21021. if (disposeSource) {
  21022. for (index = 0; index < meshes.length; index++) {
  21023. if (meshes[index]) {
  21024. meshes[index].dispose();
  21025. }
  21026. }
  21027. }
  21028. // Subdivide
  21029. if (subdivideWithSubMeshes) {
  21030. //-- Suppresions du submesh global
  21031. meshSubclass.releaseSubMeshes();
  21032. index = 0;
  21033. var offset = 0;
  21034. //-- aplique la subdivision en fonction du tableau d'indices
  21035. while (index < indiceArray.length) {
  21036. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  21037. offset += indiceArray[index];
  21038. index++;
  21039. }
  21040. }
  21041. return meshSubclass;
  21042. };
  21043. return Mesh;
  21044. }(BABYLON.AbstractMesh));
  21045. // Consts
  21046. Mesh._FRONTSIDE = 0;
  21047. Mesh._BACKSIDE = 1;
  21048. Mesh._DOUBLESIDE = 2;
  21049. Mesh._DEFAULTSIDE = 0;
  21050. Mesh._NO_CAP = 0;
  21051. Mesh._CAP_START = 1;
  21052. Mesh._CAP_END = 2;
  21053. Mesh._CAP_ALL = 3;
  21054. BABYLON.Mesh = Mesh;
  21055. })(BABYLON || (BABYLON = {}));
  21056. //# sourceMappingURL=babylon.mesh.js.map
  21057. var BABYLON;
  21058. (function (BABYLON) {
  21059. var SubMesh = (function () {
  21060. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  21061. if (createBoundingBox === void 0) { createBoundingBox = true; }
  21062. this.materialIndex = materialIndex;
  21063. this.verticesStart = verticesStart;
  21064. this.verticesCount = verticesCount;
  21065. this.indexStart = indexStart;
  21066. this.indexCount = indexCount;
  21067. this._renderId = 0;
  21068. this._mesh = mesh;
  21069. this._renderingMesh = renderingMesh || mesh;
  21070. mesh.subMeshes.push(this);
  21071. this._trianglePlanes = [];
  21072. this._id = mesh.subMeshes.length - 1;
  21073. if (createBoundingBox) {
  21074. this.refreshBoundingInfo();
  21075. mesh.computeWorldMatrix(true);
  21076. }
  21077. }
  21078. Object.defineProperty(SubMesh.prototype, "effect", {
  21079. get: function () {
  21080. return this._materialEffect;
  21081. },
  21082. enumerable: true,
  21083. configurable: true
  21084. });
  21085. SubMesh.prototype.setEffect = function (effect, defines) {
  21086. if (this._materialEffect === effect) {
  21087. return;
  21088. }
  21089. this._materialDefines = defines;
  21090. this._materialEffect = effect;
  21091. };
  21092. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21093. get: function () {
  21094. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21095. },
  21096. enumerable: true,
  21097. configurable: true
  21098. });
  21099. /**
  21100. * Returns the submesh BoudingInfo object.
  21101. */
  21102. SubMesh.prototype.getBoundingInfo = function () {
  21103. if (this.IsGlobal) {
  21104. return this._mesh.getBoundingInfo();
  21105. }
  21106. return this._boundingInfo;
  21107. };
  21108. /**
  21109. * Sets the submesh BoundingInfo.
  21110. * Return the SubMesh.
  21111. */
  21112. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21113. this._boundingInfo = boundingInfo;
  21114. return this;
  21115. };
  21116. /**
  21117. * Returns the mesh of the current submesh.
  21118. */
  21119. SubMesh.prototype.getMesh = function () {
  21120. return this._mesh;
  21121. };
  21122. /**
  21123. * Returns the rendering mesh of the submesh.
  21124. */
  21125. SubMesh.prototype.getRenderingMesh = function () {
  21126. return this._renderingMesh;
  21127. };
  21128. /**
  21129. * Returns the submesh material.
  21130. */
  21131. SubMesh.prototype.getMaterial = function () {
  21132. var rootMaterial = this._renderingMesh.material;
  21133. if (rootMaterial && rootMaterial.getSubMaterial) {
  21134. var multiMaterial = rootMaterial;
  21135. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  21136. if (this._currentMaterial !== effectiveMaterial) {
  21137. this._currentMaterial = effectiveMaterial;
  21138. if (this._materialDefines) {
  21139. this._materialDefines.markAllAsDirty();
  21140. }
  21141. }
  21142. return effectiveMaterial;
  21143. }
  21144. if (!rootMaterial) {
  21145. return this._mesh.getScene().defaultMaterial;
  21146. }
  21147. return rootMaterial;
  21148. };
  21149. // Methods
  21150. /**
  21151. * Sets a new updated BoundingInfo object to the submesh.
  21152. * Returns the SubMesh.
  21153. */
  21154. SubMesh.prototype.refreshBoundingInfo = function () {
  21155. this._lastColliderWorldVertices = null;
  21156. if (this.IsGlobal) {
  21157. return;
  21158. }
  21159. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21160. if (!data) {
  21161. this._boundingInfo = this._mesh._boundingInfo;
  21162. return;
  21163. }
  21164. var indices = this._renderingMesh.getIndices();
  21165. var extend;
  21166. //is this the only submesh?
  21167. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21168. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21169. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21170. }
  21171. else {
  21172. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21173. }
  21174. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21175. return this;
  21176. };
  21177. SubMesh.prototype._checkCollision = function (collider) {
  21178. return this.getBoundingInfo()._checkCollision(collider);
  21179. };
  21180. /**
  21181. * Updates the submesh BoundingInfo.
  21182. * Returns the Submesh.
  21183. */
  21184. SubMesh.prototype.updateBoundingInfo = function (world) {
  21185. if (!this.getBoundingInfo()) {
  21186. this.refreshBoundingInfo();
  21187. }
  21188. this.getBoundingInfo().update(world);
  21189. return this;
  21190. };
  21191. /**
  21192. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  21193. * Boolean returned.
  21194. */
  21195. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21196. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21197. };
  21198. /**
  21199. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  21200. * Boolean returned.
  21201. */
  21202. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21203. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21204. };
  21205. /**
  21206. * Renders the submesh.
  21207. * Returns it.
  21208. */
  21209. SubMesh.prototype.render = function (enableAlphaMode) {
  21210. this._renderingMesh.render(this, enableAlphaMode);
  21211. return this;
  21212. };
  21213. /**
  21214. * Returns a new Index Buffer.
  21215. * Type returned : WebGLBuffer.
  21216. */
  21217. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21218. if (!this._linesIndexBuffer) {
  21219. var linesIndices = [];
  21220. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21221. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21222. }
  21223. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21224. this.linesIndexCount = linesIndices.length;
  21225. }
  21226. return this._linesIndexBuffer;
  21227. };
  21228. /**
  21229. * True is the passed Ray intersects the submesh bounding box.
  21230. * Boolean returned.
  21231. */
  21232. SubMesh.prototype.canIntersects = function (ray) {
  21233. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21234. };
  21235. /**
  21236. * Returns an object IntersectionInfo.
  21237. */
  21238. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21239. var intersectInfo = null;
  21240. // LineMesh first as it's also a Mesh...
  21241. if (this._mesh instanceof BABYLON.LinesMesh) {
  21242. var lineMesh = this._mesh;
  21243. // Line test
  21244. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21245. var p0 = positions[indices[index]];
  21246. var p1 = positions[indices[index + 1]];
  21247. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21248. if (length < 0) {
  21249. continue;
  21250. }
  21251. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21252. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21253. if (fastCheck) {
  21254. break;
  21255. }
  21256. }
  21257. }
  21258. }
  21259. else {
  21260. // Triangles test
  21261. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21262. var p0 = positions[indices[index]];
  21263. var p1 = positions[indices[index + 1]];
  21264. var p2 = positions[indices[index + 2]];
  21265. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21266. if (currentIntersectInfo) {
  21267. if (currentIntersectInfo.distance < 0) {
  21268. continue;
  21269. }
  21270. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21271. intersectInfo = currentIntersectInfo;
  21272. intersectInfo.faceId = index / 3;
  21273. if (fastCheck) {
  21274. break;
  21275. }
  21276. }
  21277. }
  21278. }
  21279. }
  21280. return intersectInfo;
  21281. };
  21282. // Clone
  21283. /**
  21284. * Creates a new Submesh from the passed Mesh.
  21285. */
  21286. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21287. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21288. if (!this.IsGlobal) {
  21289. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21290. }
  21291. return result;
  21292. };
  21293. // Dispose
  21294. /**
  21295. * Disposes the Submesh.
  21296. * Returns nothing.
  21297. */
  21298. SubMesh.prototype.dispose = function () {
  21299. if (this._linesIndexBuffer) {
  21300. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21301. this._linesIndexBuffer = null;
  21302. }
  21303. // Remove from mesh
  21304. var index = this._mesh.subMeshes.indexOf(this);
  21305. this._mesh.subMeshes.splice(index, 1);
  21306. };
  21307. // Statics
  21308. /**
  21309. * Creates a new Submesh from the passed parameters :
  21310. * - materialIndex (integer) : the index of the main mesh material.
  21311. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  21312. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  21313. * - mesh (Mesh) : the main mesh to create the submesh from.
  21314. * - renderingMesh (optional Mesh) : rendering mesh.
  21315. */
  21316. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21317. var minVertexIndex = Number.MAX_VALUE;
  21318. var maxVertexIndex = -Number.MAX_VALUE;
  21319. renderingMesh = renderingMesh || mesh;
  21320. var indices = renderingMesh.getIndices();
  21321. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21322. var vertexIndex = indices[index];
  21323. if (vertexIndex < minVertexIndex)
  21324. minVertexIndex = vertexIndex;
  21325. if (vertexIndex > maxVertexIndex)
  21326. maxVertexIndex = vertexIndex;
  21327. }
  21328. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21329. };
  21330. return SubMesh;
  21331. }());
  21332. BABYLON.SubMesh = SubMesh;
  21333. })(BABYLON || (BABYLON = {}));
  21334. //# sourceMappingURL=babylon.subMesh.js.map
  21335. var BABYLON;
  21336. (function (BABYLON) {
  21337. var EffectFallbacks = (function () {
  21338. function EffectFallbacks() {
  21339. this._defines = {};
  21340. this._currentRank = 32;
  21341. this._maxRank = -1;
  21342. }
  21343. EffectFallbacks.prototype.addFallback = function (rank, define) {
  21344. if (!this._defines[rank]) {
  21345. if (rank < this._currentRank) {
  21346. this._currentRank = rank;
  21347. }
  21348. if (rank > this._maxRank) {
  21349. this._maxRank = rank;
  21350. }
  21351. this._defines[rank] = new Array();
  21352. }
  21353. this._defines[rank].push(define);
  21354. };
  21355. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  21356. this._meshRank = rank;
  21357. this._mesh = mesh;
  21358. if (rank < this._currentRank) {
  21359. this._currentRank = rank;
  21360. }
  21361. if (rank > this._maxRank) {
  21362. this._maxRank = rank;
  21363. }
  21364. };
  21365. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  21366. get: function () {
  21367. return this._currentRank <= this._maxRank;
  21368. },
  21369. enumerable: true,
  21370. configurable: true
  21371. });
  21372. EffectFallbacks.prototype.reduce = function (currentDefines) {
  21373. // First we try to switch to CPU skinning
  21374. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  21375. this._mesh.computeBonesUsingShaders = false;
  21376. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  21377. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  21378. var scene = this._mesh.getScene();
  21379. for (var index = 0; index < scene.meshes.length; index++) {
  21380. var otherMesh = scene.meshes[index];
  21381. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  21382. otherMesh.computeBonesUsingShaders = false;
  21383. }
  21384. }
  21385. }
  21386. else {
  21387. var currentFallbacks = this._defines[this._currentRank];
  21388. if (currentFallbacks) {
  21389. for (var index = 0; index < currentFallbacks.length; index++) {
  21390. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  21391. }
  21392. }
  21393. this._currentRank++;
  21394. }
  21395. return currentDefines;
  21396. };
  21397. return EffectFallbacks;
  21398. }());
  21399. BABYLON.EffectFallbacks = EffectFallbacks;
  21400. var EffectCreationOptions = (function () {
  21401. function EffectCreationOptions() {
  21402. }
  21403. return EffectCreationOptions;
  21404. }());
  21405. BABYLON.EffectCreationOptions = EffectCreationOptions;
  21406. var Effect = (function () {
  21407. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  21408. var _this = this;
  21409. this.uniqueId = 0;
  21410. this._uniformBuffersNames = {};
  21411. this._isReady = false;
  21412. this._compilationError = "";
  21413. this._valueCache = {};
  21414. this.name = baseName;
  21415. if (attributesNamesOrOptions.attributes) {
  21416. var options = attributesNamesOrOptions;
  21417. this._engine = uniformsNamesOrEngine;
  21418. this._attributesNames = options.attributes;
  21419. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  21420. this._samplers = options.samplers;
  21421. this.defines = options.defines;
  21422. this.onError = options.onError;
  21423. this.onCompiled = options.onCompiled;
  21424. this._fallbacks = options.fallbacks;
  21425. this._indexParameters = options.indexParameters;
  21426. if (options.uniformBuffersNames) {
  21427. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  21428. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  21429. }
  21430. }
  21431. }
  21432. else {
  21433. this._engine = engine;
  21434. this.defines = defines;
  21435. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  21436. this._samplers = samplers;
  21437. this._attributesNames = attributesNamesOrOptions;
  21438. this.onError = onError;
  21439. this.onCompiled = onCompiled;
  21440. this._indexParameters = indexParameters;
  21441. this._fallbacks = fallbacks;
  21442. }
  21443. this.uniqueId = Effect._uniqueIdSeed++;
  21444. var vertexSource;
  21445. var fragmentSource;
  21446. if (baseName.vertexElement) {
  21447. vertexSource = document.getElementById(baseName.vertexElement);
  21448. if (!vertexSource) {
  21449. vertexSource = baseName.vertexElement;
  21450. }
  21451. }
  21452. else {
  21453. vertexSource = baseName.vertex || baseName;
  21454. }
  21455. if (baseName.fragmentElement) {
  21456. fragmentSource = document.getElementById(baseName.fragmentElement);
  21457. if (!fragmentSource) {
  21458. fragmentSource = baseName.fragmentElement;
  21459. }
  21460. }
  21461. else {
  21462. fragmentSource = baseName.fragment || baseName;
  21463. }
  21464. this._loadVertexShader(vertexSource, function (vertexCode) {
  21465. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  21466. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  21467. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  21468. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  21469. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  21470. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, _this._attributesNames, _this.defines, _this._fallbacks);
  21471. });
  21472. });
  21473. });
  21474. });
  21475. });
  21476. });
  21477. }
  21478. Object.defineProperty(Effect.prototype, "key", {
  21479. get: function () {
  21480. return this._key;
  21481. },
  21482. enumerable: true,
  21483. configurable: true
  21484. });
  21485. // Properties
  21486. Effect.prototype.isReady = function () {
  21487. return this._isReady;
  21488. };
  21489. Effect.prototype.getProgram = function () {
  21490. return this._program;
  21491. };
  21492. Effect.prototype.getAttributesNames = function () {
  21493. return this._attributesNames;
  21494. };
  21495. Effect.prototype.getAttributeLocation = function (index) {
  21496. return this._attributes[index];
  21497. };
  21498. Effect.prototype.getAttributeLocationByName = function (name) {
  21499. var index = this._attributesNames.indexOf(name);
  21500. return this._attributes[index];
  21501. };
  21502. Effect.prototype.getAttributesCount = function () {
  21503. return this._attributes.length;
  21504. };
  21505. Effect.prototype.getUniformIndex = function (uniformName) {
  21506. return this._uniformsNames.indexOf(uniformName);
  21507. };
  21508. Effect.prototype.getUniform = function (uniformName) {
  21509. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  21510. };
  21511. Effect.prototype.getSamplers = function () {
  21512. return this._samplers;
  21513. };
  21514. Effect.prototype.getCompilationError = function () {
  21515. return this._compilationError;
  21516. };
  21517. Effect.prototype.getVertexShaderSource = function () {
  21518. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  21519. };
  21520. Effect.prototype.getFragmentShaderSource = function () {
  21521. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  21522. };
  21523. // Methods
  21524. Effect.prototype._loadVertexShader = function (vertex, callback) {
  21525. // DOM element ?
  21526. if (vertex instanceof HTMLElement) {
  21527. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  21528. callback(vertexCode);
  21529. return;
  21530. }
  21531. // Base64 encoded ?
  21532. if (vertex.substr(0, 7) === "base64:") {
  21533. var vertexBinary = window.atob(vertex.substr(7));
  21534. callback(vertexBinary);
  21535. return;
  21536. }
  21537. // Is in local store ?
  21538. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  21539. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  21540. return;
  21541. }
  21542. var vertexShaderUrl;
  21543. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  21544. vertexShaderUrl = vertex;
  21545. }
  21546. else {
  21547. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  21548. }
  21549. // Vertex shader
  21550. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  21551. };
  21552. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  21553. // DOM element ?
  21554. if (fragment instanceof HTMLElement) {
  21555. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  21556. callback(fragmentCode);
  21557. return;
  21558. }
  21559. // Base64 encoded ?
  21560. if (fragment.substr(0, 7) === "base64:") {
  21561. var fragmentBinary = window.atob(fragment.substr(7));
  21562. callback(fragmentBinary);
  21563. return;
  21564. }
  21565. // Is in local store ?
  21566. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  21567. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  21568. return;
  21569. }
  21570. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  21571. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  21572. return;
  21573. }
  21574. var fragmentShaderUrl;
  21575. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  21576. fragmentShaderUrl = fragment;
  21577. }
  21578. else {
  21579. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  21580. }
  21581. // Fragment shader
  21582. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  21583. };
  21584. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  21585. // Rebuild shaders source code
  21586. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  21587. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  21588. vertexCode = prefix + vertexCode;
  21589. fragmentCode = prefix + fragmentCode;
  21590. // Number lines of shaders source code
  21591. var i = 2;
  21592. var regex = /\n/gm;
  21593. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  21594. i = 2;
  21595. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  21596. // Dump shaders name and formatted source code
  21597. if (this.name.vertexElement) {
  21598. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  21599. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  21600. }
  21601. else if (this.name.vertex) {
  21602. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  21603. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  21604. }
  21605. else {
  21606. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  21607. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  21608. }
  21609. };
  21610. ;
  21611. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  21612. var preparedSourceCode = this._processPrecision(sourceCode);
  21613. if (this._engine.webGLVersion == 1) {
  21614. callback(preparedSourceCode);
  21615. return;
  21616. }
  21617. // Already converted
  21618. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  21619. callback(preparedSourceCode);
  21620. return;
  21621. }
  21622. // Remove extensions
  21623. // #extension GL_OES_standard_derivatives : enable
  21624. // #extension GL_EXT_shader_texture_lod : enable
  21625. // #extension GL_EXT_frag_depth : enable
  21626. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  21627. var result = preparedSourceCode.replace(regex, "");
  21628. // Migrate to GLSL v300
  21629. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  21630. result = result.replace(/attribute[ \t]/g, "in ");
  21631. result = result.replace(/[ \t]attribute/g, " in");
  21632. if (isFragment) {
  21633. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  21634. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  21635. result = result.replace(/texture2D\(/g, "texture(");
  21636. result = result.replace(/textureCube\(/g, "texture(");
  21637. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  21638. result = result.replace(/gl_FragColor/g, "glFragColor");
  21639. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  21640. }
  21641. callback(result);
  21642. };
  21643. Effect.prototype._processIncludes = function (sourceCode, callback) {
  21644. var _this = this;
  21645. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  21646. var match = regex.exec(sourceCode);
  21647. var returnValue = new String(sourceCode);
  21648. while (match != null) {
  21649. var includeFile = match[1];
  21650. // Uniform declaration
  21651. if (includeFile.indexOf("__decl__") !== -1) {
  21652. includeFile = includeFile.replace(/__decl__/, "");
  21653. if (this._engine.webGLVersion != 1) {
  21654. includeFile = includeFile.replace(/Vertex/, "Ubo");
  21655. includeFile = includeFile.replace(/Fragment/, "Ubo");
  21656. }
  21657. includeFile = includeFile + "Declaration";
  21658. }
  21659. if (Effect.IncludesShadersStore[includeFile]) {
  21660. // Substitution
  21661. var includeContent = Effect.IncludesShadersStore[includeFile];
  21662. if (match[2]) {
  21663. var splits = match[3].split(",");
  21664. for (var index = 0; index < splits.length; index += 2) {
  21665. var source = new RegExp(splits[index], "g");
  21666. var dest = splits[index + 1];
  21667. includeContent = includeContent.replace(source, dest);
  21668. }
  21669. }
  21670. if (match[4]) {
  21671. var indexString = match[5];
  21672. if (indexString.indexOf("..") !== -1) {
  21673. var indexSplits = indexString.split("..");
  21674. var minIndex = parseInt(indexSplits[0]);
  21675. var maxIndex = parseInt(indexSplits[1]);
  21676. var sourceIncludeContent = includeContent.slice(0);
  21677. includeContent = "";
  21678. if (isNaN(maxIndex)) {
  21679. maxIndex = this._indexParameters[indexSplits[1]];
  21680. }
  21681. for (var i = minIndex; i < maxIndex; i++) {
  21682. if (this._engine.webGLVersion === 1) {
  21683. // Ubo replacement
  21684. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  21685. return p1 + "{X}";
  21686. });
  21687. }
  21688. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  21689. }
  21690. }
  21691. else {
  21692. if (this._engine.webGLVersion === 1) {
  21693. // Ubo replacement
  21694. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  21695. return p1 + "{X}";
  21696. });
  21697. }
  21698. includeContent = includeContent.replace(/\{X\}/g, indexString);
  21699. }
  21700. }
  21701. // Replace
  21702. returnValue = returnValue.replace(match[0], includeContent);
  21703. }
  21704. else {
  21705. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  21706. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  21707. Effect.IncludesShadersStore[includeFile] = fileContent;
  21708. _this._processIncludes(returnValue, callback);
  21709. });
  21710. return;
  21711. }
  21712. match = regex.exec(sourceCode);
  21713. }
  21714. callback(returnValue);
  21715. };
  21716. Effect.prototype._processPrecision = function (source) {
  21717. if (source.indexOf("precision highp float") === -1) {
  21718. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21719. source = "precision mediump float;\n" + source;
  21720. }
  21721. else {
  21722. source = "precision highp float;\n" + source;
  21723. }
  21724. }
  21725. else {
  21726. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  21727. source = source.replace("precision highp float", "precision mediump float");
  21728. }
  21729. }
  21730. return source;
  21731. };
  21732. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  21733. try {
  21734. var engine = this._engine;
  21735. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  21736. if (engine.webGLVersion > 1) {
  21737. for (var name in this._uniformBuffersNames) {
  21738. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  21739. }
  21740. }
  21741. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  21742. this._attributes = engine.getAttributes(this._program, attributesNames);
  21743. var index;
  21744. for (index = 0; index < this._samplers.length; index++) {
  21745. var sampler = this.getUniform(this._samplers[index]);
  21746. if (sampler == null) {
  21747. this._samplers.splice(index, 1);
  21748. index--;
  21749. }
  21750. }
  21751. engine.bindSamplers(this);
  21752. this._compilationError = "";
  21753. this._isReady = true;
  21754. if (this.onCompiled) {
  21755. this.onCompiled(this);
  21756. }
  21757. }
  21758. catch (e) {
  21759. this._compilationError = e.message;
  21760. // Let's go through fallbacks then
  21761. BABYLON.Tools.Error("Unable to compile effect:");
  21762. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  21763. return " " + uniform;
  21764. }));
  21765. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  21766. return " " + attribute;
  21767. }));
  21768. this._dumpShadersSource(vertexSourceCode, fragmentSourceCode, defines);
  21769. BABYLON.Tools.Error("Error: " + this._compilationError);
  21770. if (fallbacks && fallbacks.isMoreFallbacks) {
  21771. BABYLON.Tools.Error("Trying next fallback.");
  21772. defines = fallbacks.reduce(defines);
  21773. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  21774. }
  21775. else {
  21776. if (this.onError) {
  21777. this.onError(this, this._compilationError);
  21778. }
  21779. }
  21780. }
  21781. };
  21782. Object.defineProperty(Effect.prototype, "isSupported", {
  21783. get: function () {
  21784. return this._compilationError === "";
  21785. },
  21786. enumerable: true,
  21787. configurable: true
  21788. });
  21789. Effect.prototype._bindTexture = function (channel, texture) {
  21790. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  21791. };
  21792. Effect.prototype.setTexture = function (channel, texture) {
  21793. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  21794. };
  21795. Effect.prototype.setTextureArray = function (channel, textures) {
  21796. if (this._samplers.indexOf(channel + "Ex") === -1) {
  21797. var initialPos = this._samplers.indexOf(channel);
  21798. for (var index = 1; index < textures.length; index++) {
  21799. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  21800. }
  21801. }
  21802. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  21803. };
  21804. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  21805. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  21806. };
  21807. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  21808. var cache = this._valueCache[uniformName];
  21809. var flag = matrix.updateFlag;
  21810. if (cache !== undefined && cache === flag) {
  21811. return false;
  21812. }
  21813. this._valueCache[uniformName] = flag;
  21814. return true;
  21815. };
  21816. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  21817. var cache = this._valueCache[uniformName];
  21818. if (!cache) {
  21819. cache = [x, y];
  21820. this._valueCache[uniformName] = cache;
  21821. return true;
  21822. }
  21823. var changed = false;
  21824. if (cache[0] !== x) {
  21825. cache[0] = x;
  21826. changed = true;
  21827. }
  21828. if (cache[1] !== y) {
  21829. cache[1] = y;
  21830. changed = true;
  21831. }
  21832. return changed;
  21833. };
  21834. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  21835. var cache = this._valueCache[uniformName];
  21836. if (!cache) {
  21837. cache = [x, y, z];
  21838. this._valueCache[uniformName] = cache;
  21839. return true;
  21840. }
  21841. var changed = false;
  21842. if (cache[0] !== x) {
  21843. cache[0] = x;
  21844. changed = true;
  21845. }
  21846. if (cache[1] !== y) {
  21847. cache[1] = y;
  21848. changed = true;
  21849. }
  21850. if (cache[2] !== z) {
  21851. cache[2] = z;
  21852. changed = true;
  21853. }
  21854. return changed;
  21855. };
  21856. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  21857. var cache = this._valueCache[uniformName];
  21858. if (!cache) {
  21859. cache = [x, y, z, w];
  21860. this._valueCache[uniformName] = cache;
  21861. return true;
  21862. }
  21863. var changed = false;
  21864. if (cache[0] !== x) {
  21865. cache[0] = x;
  21866. changed = true;
  21867. }
  21868. if (cache[1] !== y) {
  21869. cache[1] = y;
  21870. changed = true;
  21871. }
  21872. if (cache[2] !== z) {
  21873. cache[2] = z;
  21874. changed = true;
  21875. }
  21876. if (cache[3] !== w) {
  21877. cache[3] = w;
  21878. changed = true;
  21879. }
  21880. return changed;
  21881. };
  21882. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  21883. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  21884. return;
  21885. }
  21886. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  21887. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  21888. };
  21889. Effect.prototype.bindUniformBlock = function (blockName, index) {
  21890. this._engine.bindUniformBlock(this._program, blockName, index);
  21891. };
  21892. Effect.prototype.setIntArray = function (uniformName, array) {
  21893. this._valueCache[uniformName] = null;
  21894. this._engine.setIntArray(this.getUniform(uniformName), array);
  21895. return this;
  21896. };
  21897. Effect.prototype.setIntArray2 = function (uniformName, array) {
  21898. this._valueCache[uniformName] = null;
  21899. this._engine.setIntArray2(this.getUniform(uniformName), array);
  21900. return this;
  21901. };
  21902. Effect.prototype.setIntArray3 = function (uniformName, array) {
  21903. this._valueCache[uniformName] = null;
  21904. this._engine.setIntArray3(this.getUniform(uniformName), array);
  21905. return this;
  21906. };
  21907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  21908. this._valueCache[uniformName] = null;
  21909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  21910. return this;
  21911. };
  21912. Effect.prototype.setFloatArray = function (uniformName, array) {
  21913. this._valueCache[uniformName] = null;
  21914. this._engine.setFloatArray(this.getUniform(uniformName), array);
  21915. return this;
  21916. };
  21917. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  21918. this._valueCache[uniformName] = null;
  21919. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  21920. return this;
  21921. };
  21922. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  21923. this._valueCache[uniformName] = null;
  21924. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  21925. return this;
  21926. };
  21927. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  21928. this._valueCache[uniformName] = null;
  21929. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  21930. return this;
  21931. };
  21932. Effect.prototype.setArray = function (uniformName, array) {
  21933. this._valueCache[uniformName] = null;
  21934. this._engine.setArray(this.getUniform(uniformName), array);
  21935. return this;
  21936. };
  21937. Effect.prototype.setArray2 = function (uniformName, array) {
  21938. this._valueCache[uniformName] = null;
  21939. this._engine.setArray2(this.getUniform(uniformName), array);
  21940. return this;
  21941. };
  21942. Effect.prototype.setArray3 = function (uniformName, array) {
  21943. this._valueCache[uniformName] = null;
  21944. this._engine.setArray3(this.getUniform(uniformName), array);
  21945. return this;
  21946. };
  21947. Effect.prototype.setArray4 = function (uniformName, array) {
  21948. this._valueCache[uniformName] = null;
  21949. this._engine.setArray4(this.getUniform(uniformName), array);
  21950. return this;
  21951. };
  21952. Effect.prototype.setMatrices = function (uniformName, matrices) {
  21953. if (!matrices) {
  21954. return;
  21955. }
  21956. this._valueCache[uniformName] = null;
  21957. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  21958. return this;
  21959. };
  21960. Effect.prototype.setMatrix = function (uniformName, matrix) {
  21961. if (this._cacheMatrix(uniformName, matrix)) {
  21962. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  21963. }
  21964. return this;
  21965. };
  21966. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  21967. this._valueCache[uniformName] = null;
  21968. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  21969. return this;
  21970. };
  21971. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  21972. this._valueCache[uniformName] = null;
  21973. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  21974. return this;
  21975. };
  21976. Effect.prototype.setFloat = function (uniformName, value) {
  21977. var cache = this._valueCache[uniformName];
  21978. if (cache !== undefined && cache === value)
  21979. return this;
  21980. this._valueCache[uniformName] = value;
  21981. this._engine.setFloat(this.getUniform(uniformName), value);
  21982. return this;
  21983. };
  21984. Effect.prototype.setBool = function (uniformName, bool) {
  21985. var cache = this._valueCache[uniformName];
  21986. if (cache !== undefined && cache === bool)
  21987. return this;
  21988. this._valueCache[uniformName] = bool;
  21989. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  21990. return this;
  21991. };
  21992. Effect.prototype.setVector2 = function (uniformName, vector2) {
  21993. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  21994. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  21995. }
  21996. return this;
  21997. };
  21998. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  21999. if (this._cacheFloat2(uniformName, x, y)) {
  22000. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  22001. }
  22002. return this;
  22003. };
  22004. Effect.prototype.setVector3 = function (uniformName, vector3) {
  22005. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  22006. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  22007. }
  22008. return this;
  22009. };
  22010. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  22011. if (this._cacheFloat3(uniformName, x, y, z)) {
  22012. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  22013. }
  22014. return this;
  22015. };
  22016. Effect.prototype.setVector4 = function (uniformName, vector4) {
  22017. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  22018. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  22019. }
  22020. return this;
  22021. };
  22022. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  22023. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  22024. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  22025. }
  22026. return this;
  22027. };
  22028. Effect.prototype.setColor3 = function (uniformName, color3) {
  22029. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  22030. this._engine.setColor3(this.getUniform(uniformName), color3);
  22031. }
  22032. return this;
  22033. };
  22034. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  22035. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  22036. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  22037. }
  22038. return this;
  22039. };
  22040. Effect.prototype._recombineShader = function (node) {
  22041. if (node.define) {
  22042. if (node.condition) {
  22043. var defineIndex = this.defines.indexOf("#define " + node.define);
  22044. if (defineIndex === -1) {
  22045. return null;
  22046. }
  22047. var nextComma = this.defines.indexOf("\n", defineIndex);
  22048. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  22049. var condition = defineValue + node.condition;
  22050. if (!eval(condition)) {
  22051. return null;
  22052. }
  22053. }
  22054. else if (node.ndef) {
  22055. if (this.defines.indexOf("#define " + node.define) !== -1) {
  22056. return null;
  22057. }
  22058. }
  22059. else if (this.defines.indexOf("#define " + node.define) === -1) {
  22060. return null;
  22061. }
  22062. }
  22063. var result = "";
  22064. for (var index = 0; index < node.children.length; index++) {
  22065. var line = node.children[index];
  22066. if (line.children) {
  22067. var combined = this._recombineShader(line);
  22068. if (combined !== null) {
  22069. result += combined + "\r\n";
  22070. }
  22071. continue;
  22072. }
  22073. if (line.length > 0) {
  22074. result += line + "\r\n";
  22075. }
  22076. }
  22077. return result;
  22078. };
  22079. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  22080. var root = {
  22081. children: []
  22082. };
  22083. var currentNode = root;
  22084. var lines = shaderString.split("\n");
  22085. for (var index = 0; index < lines.length; index++) {
  22086. var line = lines[index].trim();
  22087. // #ifdef
  22088. var pos = line.indexOf("#ifdef ");
  22089. if (pos !== -1) {
  22090. var define = line.substr(pos + 7);
  22091. var newNode = {
  22092. condition: null,
  22093. ndef: false,
  22094. define: define,
  22095. children: [],
  22096. parent: currentNode
  22097. };
  22098. currentNode.children.push(newNode);
  22099. currentNode = newNode;
  22100. continue;
  22101. }
  22102. // #ifndef
  22103. var pos = line.indexOf("#ifndef ");
  22104. if (pos !== -1) {
  22105. var define = line.substr(pos + 8);
  22106. newNode = {
  22107. condition: null,
  22108. define: define,
  22109. ndef: true,
  22110. children: [],
  22111. parent: currentNode
  22112. };
  22113. currentNode.children.push(newNode);
  22114. currentNode = newNode;
  22115. continue;
  22116. }
  22117. // #if
  22118. var pos = line.indexOf("#if ");
  22119. if (pos !== -1) {
  22120. var define = line.substr(pos + 4).trim();
  22121. var conditionPos = define.indexOf(" ");
  22122. newNode = {
  22123. condition: define.substr(conditionPos + 1),
  22124. define: define.substr(0, conditionPos),
  22125. ndef: false,
  22126. children: [],
  22127. parent: currentNode
  22128. };
  22129. currentNode.children.push(newNode);
  22130. currentNode = newNode;
  22131. continue;
  22132. }
  22133. // #endif
  22134. pos = line.indexOf("#endif");
  22135. if (pos !== -1) {
  22136. currentNode = currentNode.parent;
  22137. continue;
  22138. }
  22139. currentNode.children.push(line);
  22140. }
  22141. // Recombine
  22142. return this._recombineShader(root);
  22143. };
  22144. return Effect;
  22145. }());
  22146. Effect._uniqueIdSeed = 0;
  22147. Effect._baseCache = {};
  22148. // Statics
  22149. Effect.ShadersStore = {};
  22150. Effect.IncludesShadersStore = {};
  22151. BABYLON.Effect = Effect;
  22152. })(BABYLON || (BABYLON = {}));
  22153. //# sourceMappingURL=babylon.effect.js.map
  22154. var BABYLON;
  22155. (function (BABYLON) {
  22156. var MaterialHelper = (function () {
  22157. function MaterialHelper() {
  22158. }
  22159. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  22160. if (defines._areMiscDirty) {
  22161. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  22162. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  22163. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  22164. }
  22165. };
  22166. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances) {
  22167. var changed = false;
  22168. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  22169. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  22170. changed = true;
  22171. }
  22172. if (defines["ALPHATEST"] !== engine.getAlphaTesting()) {
  22173. defines["ALPHATEST"] = !defines["ALPHATEST"];
  22174. changed = true;
  22175. }
  22176. if (defines["INSTANCES"] !== useInstances) {
  22177. defines["INSTANCES"] = useInstances;
  22178. changed = true;
  22179. }
  22180. if (changed) {
  22181. defines.markAsUnprocessed();
  22182. }
  22183. };
  22184. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  22185. if (useMorphTargets === void 0) { useMorphTargets = false; }
  22186. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  22187. return;
  22188. }
  22189. defines._normals = defines._needNormals;
  22190. defines._uvs = defines._needUVs;
  22191. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  22192. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  22193. defines["TANGENT"] = true;
  22194. }
  22195. if (defines._needUVs) {
  22196. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  22197. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  22198. }
  22199. else {
  22200. defines["UV1"] = false;
  22201. defines["UV2"] = false;
  22202. }
  22203. if (useVertexColor) {
  22204. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  22205. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  22206. }
  22207. if (useBones) {
  22208. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  22209. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  22210. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  22211. }
  22212. else {
  22213. defines["NUM_BONE_INFLUENCERS"] = 0;
  22214. defines["BonesPerMesh"] = 0;
  22215. }
  22216. }
  22217. if (useMorphTargets) {
  22218. if (mesh.morphTargetManager) {
  22219. var manager = mesh.morphTargetManager;
  22220. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  22221. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  22222. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  22223. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  22224. }
  22225. else {
  22226. defines["MORPHTARGETS_TANGENT"] = false;
  22227. defines["MORPHTARGETS_NORMAL"] = false;
  22228. defines["MORPHTARGETS"] = false;
  22229. defines["NUM_MORPH_INFLUENCERS"] = 0;
  22230. }
  22231. }
  22232. };
  22233. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  22234. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22235. if (disableLighting === void 0) { disableLighting = false; }
  22236. if (!defines._areLightsDirty) {
  22237. return defines._needNormals;
  22238. }
  22239. var lightIndex = 0;
  22240. var needNormals = false;
  22241. var needRebuild = false;
  22242. var lightmapMode = false;
  22243. var shadowEnabled = false;
  22244. var specularEnabled = false;
  22245. if (scene.lightsEnabled && !disableLighting) {
  22246. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  22247. var light = _a[_i];
  22248. needNormals = true;
  22249. if (defines["LIGHT" + lightIndex] === undefined) {
  22250. needRebuild = true;
  22251. }
  22252. defines["LIGHT" + lightIndex] = true;
  22253. defines["SPOTLIGHT" + lightIndex] = false;
  22254. defines["HEMILIGHT" + lightIndex] = false;
  22255. defines["POINTLIGHT" + lightIndex] = false;
  22256. defines["DIRLIGHT" + lightIndex] = false;
  22257. var type;
  22258. if (light.getTypeID() === 2) {
  22259. type = "SPOTLIGHT" + lightIndex;
  22260. }
  22261. else if (light.getTypeID() === 3) {
  22262. type = "HEMILIGHT" + lightIndex;
  22263. }
  22264. else if (light.getTypeID() === 0) {
  22265. type = "POINTLIGHT" + lightIndex;
  22266. }
  22267. else {
  22268. type = "DIRLIGHT" + lightIndex;
  22269. }
  22270. defines[type] = true;
  22271. // Specular
  22272. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  22273. specularEnabled = true;
  22274. }
  22275. // Shadows
  22276. defines["SHADOW" + lightIndex] = false;
  22277. if (scene.shadowsEnabled) {
  22278. var shadowGenerator = light.getShadowGenerator();
  22279. if (mesh && mesh.receiveShadows && shadowGenerator) {
  22280. defines["SHADOW" + lightIndex] = true;
  22281. shadowEnabled = true;
  22282. defines["SHADOWPCF" + lightIndex] = false;
  22283. defines["SHADOWESM" + lightIndex] = false;
  22284. if (shadowGenerator.usePoissonSampling) {
  22285. defines["SHADOWPCF" + lightIndex] = true;
  22286. }
  22287. else if (shadowGenerator.useExponentialShadowMap || shadowGenerator.useBlurExponentialShadowMap) {
  22288. defines["SHADOWESM" + lightIndex] = true;
  22289. }
  22290. }
  22291. }
  22292. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  22293. lightmapMode = true;
  22294. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  22295. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  22296. }
  22297. else {
  22298. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  22299. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  22300. }
  22301. lightIndex++;
  22302. if (lightIndex === maxSimultaneousLights)
  22303. break;
  22304. }
  22305. }
  22306. defines["SPECULARTERM"] = specularEnabled;
  22307. defines["SHADOWS"] = shadowEnabled;
  22308. // Resetting all other lights if any
  22309. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  22310. if (defines["LIGHT" + index] !== undefined) {
  22311. defines["LIGHT" + index] = false;
  22312. }
  22313. }
  22314. var caps = scene.getEngine().getCaps();
  22315. if (defines["SHADOWFULLFLOAT"] === undefined) {
  22316. needRebuild = true;
  22317. }
  22318. defines["SHADOWFULLFLOAT"] = (shadowEnabled && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender);
  22319. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  22320. if (needRebuild) {
  22321. defines.rebuild();
  22322. }
  22323. return needNormals;
  22324. };
  22325. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  22326. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22327. var uniformsList, uniformBuffersList, samplersList, defines;
  22328. if (uniformsListOrOptions.uniformsNames) {
  22329. var options = uniformsListOrOptions;
  22330. uniformsList = options.uniformsNames;
  22331. uniformBuffersList = options.uniformBuffersNames;
  22332. samplersList = options.samplers;
  22333. defines = options.defines;
  22334. maxSimultaneousLights = options.maxSimultaneousLights;
  22335. }
  22336. else {
  22337. uniformsList = uniformsListOrOptions;
  22338. }
  22339. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22340. if (!defines["LIGHT" + lightIndex]) {
  22341. break;
  22342. }
  22343. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  22344. if (uniformBuffersList) {
  22345. uniformBuffersList.push("Light" + lightIndex);
  22346. }
  22347. samplersList.push("shadowSampler" + lightIndex);
  22348. }
  22349. if (defines["NUM_MORPH_INFLUENCERS"]) {
  22350. uniformsList.push("morphTargetInfluences");
  22351. }
  22352. };
  22353. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  22354. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22355. if (!defines["SHADOWS"]) {
  22356. return;
  22357. }
  22358. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  22359. if (!defines["LIGHT" + lightIndex]) {
  22360. break;
  22361. }
  22362. if (lightIndex > 0) {
  22363. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  22364. }
  22365. if (defines["SHADOW" + lightIndex]) {
  22366. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  22367. }
  22368. if (defines["SHADOWPCF" + lightIndex]) {
  22369. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  22370. }
  22371. if (defines["SHADOWESM" + lightIndex]) {
  22372. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  22373. }
  22374. }
  22375. };
  22376. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  22377. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  22378. if (influencers > 0) {
  22379. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  22380. var manager = mesh.morphTargetManager;
  22381. var normal = manager.supportsNormals && defines["NORMAL"];
  22382. var tangent = manager.supportsTangents && defines["TANGENT"];
  22383. for (var index = 0; index < influencers; index++) {
  22384. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  22385. if (normal) {
  22386. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  22387. }
  22388. if (tangent) {
  22389. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  22390. }
  22391. if (attribs.length > maxAttributesCount) {
  22392. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  22393. }
  22394. }
  22395. }
  22396. };
  22397. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  22398. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  22399. fallbacks.addCPUSkinningFallback(0, mesh);
  22400. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22401. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22402. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  22403. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  22404. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  22405. }
  22406. }
  22407. };
  22408. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  22409. if (defines["INSTANCES"]) {
  22410. attribs.push("world0");
  22411. attribs.push("world1");
  22412. attribs.push("world2");
  22413. attribs.push("world3");
  22414. }
  22415. };
  22416. // Bindings
  22417. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  22418. var shadowGenerator = light.getShadowGenerator();
  22419. if (mesh.receiveShadows && shadowGenerator) {
  22420. if (!light.needCube()) {
  22421. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  22422. }
  22423. else {
  22424. if (!depthValuesAlreadySet) {
  22425. depthValuesAlreadySet = true;
  22426. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  22427. }
  22428. }
  22429. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  22430. light._uniformBuffer.updateFloat3("shadowsInfo", shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.depthScale, lightIndex);
  22431. }
  22432. return depthValuesAlreadySet;
  22433. };
  22434. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  22435. light.transferToEffect(effect, lightIndex + "");
  22436. };
  22437. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  22438. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  22439. var lightIndex = 0;
  22440. var depthValuesAlreadySet = false;
  22441. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  22442. var light = _a[_i];
  22443. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  22444. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  22445. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  22446. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], light.range, lightIndex + "");
  22447. if (defines["SPECULARTERM"]) {
  22448. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  22449. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  22450. }
  22451. // Shadows
  22452. if (scene.shadowsEnabled) {
  22453. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  22454. }
  22455. light._uniformBuffer.update();
  22456. lightIndex++;
  22457. if (lightIndex === maxSimultaneousLights)
  22458. break;
  22459. }
  22460. };
  22461. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  22462. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  22463. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  22464. effect.setColor3("vFogColor", scene.fogColor);
  22465. }
  22466. };
  22467. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  22468. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  22469. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  22470. if (matrices) {
  22471. effect.setMatrices("mBones", matrices);
  22472. }
  22473. }
  22474. };
  22475. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  22476. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  22477. return;
  22478. }
  22479. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  22480. };
  22481. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  22482. if (defines["LOGARITHMICDEPTH"]) {
  22483. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  22484. }
  22485. };
  22486. MaterialHelper.BindClipPlane = function (effect, scene) {
  22487. if (scene.clipPlane) {
  22488. var clipPlane = scene.clipPlane;
  22489. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  22490. }
  22491. };
  22492. return MaterialHelper;
  22493. }());
  22494. BABYLON.MaterialHelper = MaterialHelper;
  22495. })(BABYLON || (BABYLON = {}));
  22496. //# sourceMappingURL=babylon.materialHelper.js.map
  22497. var BABYLON;
  22498. (function (BABYLON) {
  22499. var MaterialDefines = (function () {
  22500. function MaterialDefines() {
  22501. this._isDirty = true;
  22502. this._areLightsDirty = true;
  22503. this._areAttributesDirty = true;
  22504. this._areTexturesDirty = true;
  22505. this._areFresnelDirty = true;
  22506. this._areMiscDirty = true;
  22507. this._normals = false;
  22508. this._uvs = false;
  22509. this._needNormals = false;
  22510. this._needUVs = false;
  22511. }
  22512. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  22513. get: function () {
  22514. return this._isDirty;
  22515. },
  22516. enumerable: true,
  22517. configurable: true
  22518. });
  22519. MaterialDefines.prototype.markAsProcessed = function () {
  22520. this._isDirty = false;
  22521. this._areAttributesDirty = false;
  22522. this._areTexturesDirty = false;
  22523. this._areFresnelDirty = false;
  22524. this._areLightsDirty = false;
  22525. this._areMiscDirty = false;
  22526. };
  22527. MaterialDefines.prototype.markAsUnprocessed = function () {
  22528. this._isDirty = true;
  22529. };
  22530. MaterialDefines.prototype.markAllAsDirty = function () {
  22531. this._areTexturesDirty = true;
  22532. this._areAttributesDirty = true;
  22533. this._areLightsDirty = true;
  22534. this._areFresnelDirty = true;
  22535. this._areMiscDirty = true;
  22536. this._isDirty = true;
  22537. };
  22538. MaterialDefines.prototype.markAsLightDirty = function () {
  22539. this._areLightsDirty = true;
  22540. this._isDirty = true;
  22541. };
  22542. MaterialDefines.prototype.markAsAttributesDirty = function () {
  22543. this._areAttributesDirty = true;
  22544. this._isDirty = true;
  22545. };
  22546. MaterialDefines.prototype.markAsTexturesDirty = function () {
  22547. this._areTexturesDirty = true;
  22548. this._isDirty = true;
  22549. };
  22550. MaterialDefines.prototype.markAsFresnelDirty = function () {
  22551. this._areFresnelDirty = true;
  22552. this._isDirty = true;
  22553. };
  22554. MaterialDefines.prototype.markAsMiscDirty = function () {
  22555. this._areMiscDirty = true;
  22556. this._isDirty = true;
  22557. };
  22558. MaterialDefines.prototype.rebuild = function () {
  22559. if (this._keys) {
  22560. delete this._keys;
  22561. }
  22562. this._keys = [];
  22563. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  22564. var key = _a[_i];
  22565. if (key[0] === "_") {
  22566. continue;
  22567. }
  22568. this._keys.push(key);
  22569. }
  22570. };
  22571. MaterialDefines.prototype.isEqual = function (other) {
  22572. if (this._keys.length !== other._keys.length) {
  22573. return false;
  22574. }
  22575. for (var index = 0; index < this._keys.length; index++) {
  22576. var prop = this._keys[index];
  22577. if (this[prop] !== other[prop]) {
  22578. return false;
  22579. }
  22580. }
  22581. return true;
  22582. };
  22583. MaterialDefines.prototype.cloneTo = function (other) {
  22584. if (this._keys.length !== other._keys.length) {
  22585. other._keys = this._keys.slice(0);
  22586. }
  22587. for (var index = 0; index < this._keys.length; index++) {
  22588. var prop = this._keys[index];
  22589. other[prop] = this[prop];
  22590. }
  22591. };
  22592. MaterialDefines.prototype.reset = function () {
  22593. for (var index = 0; index < this._keys.length; index++) {
  22594. var prop = this._keys[index];
  22595. if (typeof (this[prop]) === "number") {
  22596. this[prop] = 0;
  22597. }
  22598. else {
  22599. this[prop] = false;
  22600. }
  22601. }
  22602. };
  22603. MaterialDefines.prototype.toString = function () {
  22604. var result = "";
  22605. for (var index = 0; index < this._keys.length; index++) {
  22606. var prop = this._keys[index];
  22607. var value = this[prop];
  22608. if (typeof (value) === "number") {
  22609. result += "#define " + prop + " " + this[prop] + "\n";
  22610. }
  22611. else if (value) {
  22612. result += "#define " + prop + "\n";
  22613. }
  22614. }
  22615. return result;
  22616. };
  22617. return MaterialDefines;
  22618. }());
  22619. BABYLON.MaterialDefines = MaterialDefines;
  22620. var Material = (function () {
  22621. function Material(name, scene, doNotAdd) {
  22622. this.checkReadyOnEveryCall = false;
  22623. this.checkReadyOnlyOnce = false;
  22624. this.state = "";
  22625. this.alpha = 1.0;
  22626. this._backFaceCulling = true;
  22627. this.doNotSerialize = false;
  22628. this.storeEffectOnSubMeshes = false;
  22629. /**
  22630. * An event triggered when the material is disposed.
  22631. * @type {BABYLON.Observable}
  22632. */
  22633. this.onDisposeObservable = new BABYLON.Observable();
  22634. /**
  22635. * An event triggered when the material is bound.
  22636. * @type {BABYLON.Observable}
  22637. */
  22638. this.onBindObservable = new BABYLON.Observable();
  22639. /**
  22640. * An event triggered when the material is unbound.
  22641. * @type {BABYLON.Observable}
  22642. */
  22643. this.onUnBindObservable = new BABYLON.Observable();
  22644. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  22645. this.disableDepthWrite = false;
  22646. this._fogEnabled = true;
  22647. this.pointSize = 1.0;
  22648. this.zOffset = 0;
  22649. this._wasPreviouslyReady = false;
  22650. this._fillMode = Material.TriangleFillMode;
  22651. this.name = name;
  22652. this.id = name;
  22653. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22654. if (this._scene.useRightHandedSystem) {
  22655. this.sideOrientation = Material.ClockWiseSideOrientation;
  22656. }
  22657. else {
  22658. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  22659. }
  22660. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  22661. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  22662. if (!doNotAdd) {
  22663. this._scene.materials.push(this);
  22664. }
  22665. }
  22666. Object.defineProperty(Material, "TriangleFillMode", {
  22667. get: function () {
  22668. return Material._TriangleFillMode;
  22669. },
  22670. enumerable: true,
  22671. configurable: true
  22672. });
  22673. Object.defineProperty(Material, "WireFrameFillMode", {
  22674. get: function () {
  22675. return Material._WireFrameFillMode;
  22676. },
  22677. enumerable: true,
  22678. configurable: true
  22679. });
  22680. Object.defineProperty(Material, "PointFillMode", {
  22681. get: function () {
  22682. return Material._PointFillMode;
  22683. },
  22684. enumerable: true,
  22685. configurable: true
  22686. });
  22687. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  22688. get: function () {
  22689. return Material._ClockWiseSideOrientation;
  22690. },
  22691. enumerable: true,
  22692. configurable: true
  22693. });
  22694. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  22695. get: function () {
  22696. return Material._CounterClockWiseSideOrientation;
  22697. },
  22698. enumerable: true,
  22699. configurable: true
  22700. });
  22701. Object.defineProperty(Material, "TextureDirtyFlag", {
  22702. get: function () {
  22703. return Material._TextureDirtyFlag;
  22704. },
  22705. enumerable: true,
  22706. configurable: true
  22707. });
  22708. Object.defineProperty(Material, "LightDirtyFlag", {
  22709. get: function () {
  22710. return Material._LightDirtyFlag;
  22711. },
  22712. enumerable: true,
  22713. configurable: true
  22714. });
  22715. Object.defineProperty(Material, "FresnelDirtyFlag", {
  22716. get: function () {
  22717. return Material._FresnelDirtyFlag;
  22718. },
  22719. enumerable: true,
  22720. configurable: true
  22721. });
  22722. Object.defineProperty(Material, "AttributesDirtyFlag", {
  22723. get: function () {
  22724. return Material._AttributesDirtyFlag;
  22725. },
  22726. enumerable: true,
  22727. configurable: true
  22728. });
  22729. Object.defineProperty(Material, "MiscDirtyFlag", {
  22730. get: function () {
  22731. return Material._MiscDirtyFlag;
  22732. },
  22733. enumerable: true,
  22734. configurable: true
  22735. });
  22736. Object.defineProperty(Material.prototype, "backFaceCulling", {
  22737. get: function () {
  22738. return this._backFaceCulling;
  22739. },
  22740. set: function (value) {
  22741. if (this._backFaceCulling === value) {
  22742. return;
  22743. }
  22744. this._backFaceCulling = value;
  22745. this.markAsDirty(Material.TextureDirtyFlag);
  22746. },
  22747. enumerable: true,
  22748. configurable: true
  22749. });
  22750. Object.defineProperty(Material.prototype, "onDispose", {
  22751. set: function (callback) {
  22752. if (this._onDisposeObserver) {
  22753. this.onDisposeObservable.remove(this._onDisposeObserver);
  22754. }
  22755. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22756. },
  22757. enumerable: true,
  22758. configurable: true
  22759. });
  22760. Object.defineProperty(Material.prototype, "onBind", {
  22761. set: function (callback) {
  22762. if (this._onBindObserver) {
  22763. this.onBindObservable.remove(this._onBindObserver);
  22764. }
  22765. this._onBindObserver = this.onBindObservable.add(callback);
  22766. },
  22767. enumerable: true,
  22768. configurable: true
  22769. });
  22770. Object.defineProperty(Material.prototype, "fogEnabled", {
  22771. get: function () {
  22772. return this._fogEnabled;
  22773. },
  22774. set: function (value) {
  22775. if (this._fogEnabled === value) {
  22776. return;
  22777. }
  22778. this._fogEnabled = value;
  22779. this.markAsDirty(Material.MiscDirtyFlag);
  22780. },
  22781. enumerable: true,
  22782. configurable: true
  22783. });
  22784. Object.defineProperty(Material.prototype, "wireframe", {
  22785. get: function () {
  22786. return this._fillMode === Material.WireFrameFillMode;
  22787. },
  22788. set: function (value) {
  22789. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  22790. },
  22791. enumerable: true,
  22792. configurable: true
  22793. });
  22794. Object.defineProperty(Material.prototype, "pointsCloud", {
  22795. get: function () {
  22796. return this._fillMode === Material.PointFillMode;
  22797. },
  22798. set: function (value) {
  22799. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  22800. },
  22801. enumerable: true,
  22802. configurable: true
  22803. });
  22804. Object.defineProperty(Material.prototype, "fillMode", {
  22805. get: function () {
  22806. return this._fillMode;
  22807. },
  22808. set: function (value) {
  22809. if (this._fillMode === value) {
  22810. return;
  22811. }
  22812. this._fillMode = value;
  22813. this.markAsDirty(Material.MiscDirtyFlag);
  22814. },
  22815. enumerable: true,
  22816. configurable: true
  22817. });
  22818. /**
  22819. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22820. * subclasses should override adding information pertainent to themselves
  22821. */
  22822. Material.prototype.toString = function (fullDetails) {
  22823. var ret = "Name: " + this.name;
  22824. if (fullDetails) {
  22825. }
  22826. return ret;
  22827. };
  22828. /**
  22829. * Child classes can use it to update shaders
  22830. */
  22831. Material.prototype.markAsDirty = function (flag) {
  22832. };
  22833. Material.prototype.getClassName = function () {
  22834. return "Material";
  22835. };
  22836. Object.defineProperty(Material.prototype, "isFrozen", {
  22837. get: function () {
  22838. return this.checkReadyOnlyOnce;
  22839. },
  22840. enumerable: true,
  22841. configurable: true
  22842. });
  22843. Material.prototype.freeze = function () {
  22844. this.checkReadyOnlyOnce = true;
  22845. };
  22846. Material.prototype.unfreeze = function () {
  22847. this.checkReadyOnlyOnce = false;
  22848. };
  22849. Material.prototype.isReady = function (mesh, useInstances) {
  22850. return true;
  22851. };
  22852. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  22853. return false;
  22854. };
  22855. Material.prototype.getEffect = function () {
  22856. return this._effect;
  22857. };
  22858. Material.prototype.getScene = function () {
  22859. return this._scene;
  22860. };
  22861. Material.prototype.needAlphaBlending = function () {
  22862. return (this.alpha < 1.0);
  22863. };
  22864. Material.prototype.needAlphaTesting = function () {
  22865. return false;
  22866. };
  22867. Material.prototype.getAlphaTestTexture = function () {
  22868. return null;
  22869. };
  22870. Material.prototype.markDirty = function () {
  22871. this._wasPreviouslyReady = false;
  22872. };
  22873. Material.prototype._preBind = function (effect) {
  22874. var engine = this._scene.getEngine();
  22875. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  22876. engine.enableEffect(effect ? effect : this._effect);
  22877. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  22878. };
  22879. Material.prototype.bind = function (world, mesh) {
  22880. };
  22881. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  22882. };
  22883. Material.prototype.bindOnlyWorldMatrix = function (world) {
  22884. };
  22885. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  22886. sceneUbo.bindToEffect(effect, "Scene");
  22887. };
  22888. Material.prototype.bindView = function (effect) {
  22889. if (!this._useUBO) {
  22890. effect.setMatrix("view", this.getScene().getViewMatrix());
  22891. }
  22892. else {
  22893. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  22894. }
  22895. };
  22896. Material.prototype.bindViewProjection = function (effect) {
  22897. if (!this._useUBO) {
  22898. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  22899. }
  22900. else {
  22901. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  22902. }
  22903. };
  22904. Material.prototype._afterBind = function (mesh) {
  22905. this._scene._cachedMaterial = this;
  22906. this.onBindObservable.notifyObservers(mesh);
  22907. if (this.disableDepthWrite) {
  22908. var engine = this._scene.getEngine();
  22909. this._cachedDepthWriteState = engine.getDepthWrite();
  22910. engine.setDepthWrite(false);
  22911. }
  22912. };
  22913. Material.prototype.unbind = function () {
  22914. this.onUnBindObservable.notifyObservers(this);
  22915. if (this.disableDepthWrite) {
  22916. var engine = this._scene.getEngine();
  22917. engine.setDepthWrite(this._cachedDepthWriteState);
  22918. }
  22919. };
  22920. Material.prototype.clone = function (name) {
  22921. return null;
  22922. };
  22923. Material.prototype.getBindedMeshes = function () {
  22924. var result = new Array();
  22925. for (var index = 0; index < this._scene.meshes.length; index++) {
  22926. var mesh = this._scene.meshes[index];
  22927. if (mesh.material === this) {
  22928. result.push(mesh);
  22929. }
  22930. }
  22931. return result;
  22932. };
  22933. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  22934. // Animations
  22935. this.getScene().stopAnimation(this);
  22936. // Remove from scene
  22937. var index = this._scene.materials.indexOf(this);
  22938. if (index >= 0) {
  22939. this._scene.materials.splice(index, 1);
  22940. }
  22941. // Remove from meshes
  22942. for (index = 0; index < this._scene.meshes.length; index++) {
  22943. var mesh = this._scene.meshes[index];
  22944. if (mesh.material === this) {
  22945. mesh.material = null;
  22946. if (mesh.geometry) {
  22947. var geometry = mesh.geometry;
  22948. if (this.storeEffectOnSubMeshes) {
  22949. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  22950. var subMesh = _a[_i];
  22951. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  22952. }
  22953. }
  22954. else {
  22955. geometry._releaseVertexArrayObject(this._effect);
  22956. }
  22957. }
  22958. }
  22959. }
  22960. this._uniformBuffer.dispose();
  22961. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  22962. if (forceDisposeEffect && this._effect) {
  22963. if (this.storeEffectOnSubMeshes) {
  22964. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22965. var subMesh = _c[_b];
  22966. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  22967. }
  22968. }
  22969. else {
  22970. this._scene.getEngine()._releaseEffect(this._effect);
  22971. }
  22972. this._effect = null;
  22973. }
  22974. // Callback
  22975. this.onDisposeObservable.notifyObservers(this);
  22976. this.onDisposeObservable.clear();
  22977. this.onBindObservable.clear();
  22978. this.onUnBindObservable.clear();
  22979. };
  22980. Material.prototype.serialize = function () {
  22981. return BABYLON.SerializationHelper.Serialize(this);
  22982. };
  22983. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  22984. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  22985. multiMaterial.id = parsedMultiMaterial.id;
  22986. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  22987. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  22988. var subMatId = parsedMultiMaterial.materials[matIndex];
  22989. if (subMatId) {
  22990. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  22991. }
  22992. else {
  22993. multiMaterial.subMaterials.push(null);
  22994. }
  22995. }
  22996. return multiMaterial;
  22997. };
  22998. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  22999. if (!parsedMaterial.customType) {
  23000. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  23001. }
  23002. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  23003. return materialType.Parse(parsedMaterial, scene, rootUrl);
  23004. ;
  23005. };
  23006. return Material;
  23007. }());
  23008. Material._TriangleFillMode = 0;
  23009. Material._WireFrameFillMode = 1;
  23010. Material._PointFillMode = 2;
  23011. Material._ClockWiseSideOrientation = 0;
  23012. Material._CounterClockWiseSideOrientation = 1;
  23013. Material._TextureDirtyFlag = 0;
  23014. Material._LightDirtyFlag = 1;
  23015. Material._FresnelDirtyFlag = 2;
  23016. Material._AttributesDirtyFlag = 4;
  23017. Material._MiscDirtyFlag = 8;
  23018. __decorate([
  23019. BABYLON.serialize()
  23020. ], Material.prototype, "id", void 0);
  23021. __decorate([
  23022. BABYLON.serialize()
  23023. ], Material.prototype, "name", void 0);
  23024. __decorate([
  23025. BABYLON.serialize()
  23026. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  23027. __decorate([
  23028. BABYLON.serialize()
  23029. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  23030. __decorate([
  23031. BABYLON.serialize()
  23032. ], Material.prototype, "state", void 0);
  23033. __decorate([
  23034. BABYLON.serialize()
  23035. ], Material.prototype, "alpha", void 0);
  23036. __decorate([
  23037. BABYLON.serialize("backFaceCulling")
  23038. ], Material.prototype, "_backFaceCulling", void 0);
  23039. __decorate([
  23040. BABYLON.serialize()
  23041. ], Material.prototype, "sideOrientation", void 0);
  23042. __decorate([
  23043. BABYLON.serialize()
  23044. ], Material.prototype, "alphaMode", void 0);
  23045. __decorate([
  23046. BABYLON.serialize()
  23047. ], Material.prototype, "disableDepthWrite", void 0);
  23048. __decorate([
  23049. BABYLON.serialize("fogEnabled")
  23050. ], Material.prototype, "_fogEnabled", void 0);
  23051. __decorate([
  23052. BABYLON.serialize()
  23053. ], Material.prototype, "pointSize", void 0);
  23054. __decorate([
  23055. BABYLON.serialize()
  23056. ], Material.prototype, "zOffset", void 0);
  23057. __decorate([
  23058. BABYLON.serialize()
  23059. ], Material.prototype, "wireframe", null);
  23060. __decorate([
  23061. BABYLON.serialize()
  23062. ], Material.prototype, "pointsCloud", null);
  23063. __decorate([
  23064. BABYLON.serialize()
  23065. ], Material.prototype, "fillMode", null);
  23066. BABYLON.Material = Material;
  23067. })(BABYLON || (BABYLON = {}));
  23068. //# sourceMappingURL=babylon.material.js.map
  23069. var BABYLON;
  23070. (function (BABYLON) {
  23071. var UniformBuffer = (function () {
  23072. /**
  23073. * Uniform buffer objects.
  23074. *
  23075. * Handles blocks of uniform on the GPU.
  23076. *
  23077. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  23078. *
  23079. * For more information, please refer to :
  23080. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  23081. */
  23082. function UniformBuffer(engine, data, dynamic) {
  23083. this._engine = engine;
  23084. this._noUBO = engine.webGLVersion === 1;
  23085. this._dynamic = dynamic;
  23086. this._data = data || [];
  23087. this._uniformLocations = {};
  23088. this._uniformSizes = {};
  23089. this._uniformLocationPointer = 0;
  23090. this._needSync = false;
  23091. if (this._noUBO) {
  23092. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  23093. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  23094. this.updateFloat = this._updateFloatForEffect;
  23095. this.updateFloat2 = this._updateFloat2ForEffect;
  23096. this.updateFloat3 = this._updateFloat3ForEffect;
  23097. this.updateFloat4 = this._updateFloat4ForEffect;
  23098. this.updateMatrix = this._updateMatrixForEffect;
  23099. this.updateVector3 = this._updateVector3ForEffect;
  23100. this.updateVector4 = this._updateVector4ForEffect;
  23101. this.updateColor3 = this._updateColor3ForEffect;
  23102. this.updateColor4 = this._updateColor4ForEffect;
  23103. }
  23104. else {
  23105. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  23106. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  23107. this.updateFloat = this._updateFloatForUniform;
  23108. this.updateFloat2 = this._updateFloat2ForUniform;
  23109. this.updateFloat3 = this._updateFloat3ForUniform;
  23110. this.updateFloat4 = this._updateFloat4ForUniform;
  23111. this.updateMatrix = this._updateMatrixForUniform;
  23112. this.updateVector3 = this._updateVector3ForUniform;
  23113. this.updateVector4 = this._updateVector4ForUniform;
  23114. this.updateColor3 = this._updateColor3ForUniform;
  23115. this.updateColor4 = this._updateColor4ForUniform;
  23116. }
  23117. }
  23118. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  23119. // Properties
  23120. /**
  23121. * Indicates if the buffer is using the WebGL2 UBO implementation,
  23122. * or just falling back on setUniformXXX calls.
  23123. */
  23124. get: function () {
  23125. return !this._noUBO;
  23126. },
  23127. enumerable: true,
  23128. configurable: true
  23129. });
  23130. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  23131. /**
  23132. * Indicates if the WebGL underlying uniform buffer is in sync
  23133. * with the javascript cache data.
  23134. */
  23135. get: function () {
  23136. return !this._needSync;
  23137. },
  23138. enumerable: true,
  23139. configurable: true
  23140. });
  23141. /**
  23142. * Indicates if the WebGL underlying uniform buffer is dynamic.
  23143. * Also, a dynamic UniformBuffer will disable cache verification and always
  23144. * update the underlying WebGL uniform buffer to the GPU.
  23145. */
  23146. UniformBuffer.prototype.isDynamic = function () {
  23147. return this._dynamic;
  23148. };
  23149. /**
  23150. * The data cache on JS side.
  23151. */
  23152. UniformBuffer.prototype.getData = function () {
  23153. return this._bufferData;
  23154. };
  23155. /**
  23156. * The underlying WebGL Uniform buffer.
  23157. */
  23158. UniformBuffer.prototype.getBuffer = function () {
  23159. return this._buffer;
  23160. };
  23161. /**
  23162. * std140 layout specifies how to align data within an UBO structure.
  23163. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  23164. * for specs.
  23165. */
  23166. UniformBuffer.prototype._fillAlignment = function (size) {
  23167. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  23168. // and 4x4 matrices
  23169. // TODO : change if other types are used
  23170. var alignment;
  23171. if (size <= 2) {
  23172. alignment = size;
  23173. }
  23174. else {
  23175. alignment = 4;
  23176. }
  23177. if ((this._uniformLocationPointer % alignment) !== 0) {
  23178. var oldPointer = this._uniformLocationPointer;
  23179. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  23180. var diff = this._uniformLocationPointer - oldPointer;
  23181. for (var i = 0; i < diff; i++) {
  23182. this._data.push(0);
  23183. }
  23184. }
  23185. };
  23186. /**
  23187. * Adds an uniform in the buffer.
  23188. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  23189. * for the layout to be correct !
  23190. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23191. * @param {number|number[]} size Data size, or data directly.
  23192. */
  23193. UniformBuffer.prototype.addUniform = function (name, size) {
  23194. if (this._noUBO) {
  23195. return;
  23196. }
  23197. if (this._uniformLocations[name] !== undefined) {
  23198. // Already existing uniform
  23199. return;
  23200. }
  23201. // This function must be called in the order of the shader layout !
  23202. // size can be the size of the uniform, or data directly
  23203. var data;
  23204. if (size instanceof Array) {
  23205. data = size;
  23206. size = data.length;
  23207. }
  23208. else {
  23209. size = size;
  23210. data = [];
  23211. // Fill with zeros
  23212. for (var i = 0; i < size; i++) {
  23213. data.push(0);
  23214. }
  23215. }
  23216. this._fillAlignment(size);
  23217. this._uniformSizes[name] = size;
  23218. this._uniformLocations[name] = this._uniformLocationPointer;
  23219. this._uniformLocationPointer += size;
  23220. for (var i = 0; i < size; i++) {
  23221. this._data.push(data[i]);
  23222. }
  23223. this._needSync = true;
  23224. };
  23225. /**
  23226. * Wrapper for addUniform.
  23227. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23228. * @param {Matrix} mat A 4x4 matrix.
  23229. */
  23230. UniformBuffer.prototype.addMatrix = function (name, mat) {
  23231. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  23232. };
  23233. /**
  23234. * Wrapper for addUniform.
  23235. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23236. * @param {number} x
  23237. * @param {number} y
  23238. */
  23239. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  23240. var temp = [x, y];
  23241. this.addUniform(name, temp);
  23242. };
  23243. /**
  23244. * Wrapper for addUniform.
  23245. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23246. * @param {number} x
  23247. * @param {number} y
  23248. * @param {number} z
  23249. */
  23250. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  23251. var temp = [x, y, z];
  23252. this.addUniform(name, temp);
  23253. };
  23254. /**
  23255. * Wrapper for addUniform.
  23256. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23257. * @param {Color3} color
  23258. */
  23259. UniformBuffer.prototype.addColor3 = function (name, color) {
  23260. var temp = [];
  23261. color.toArray(temp);
  23262. this.addUniform(name, temp);
  23263. };
  23264. /**
  23265. * Wrapper for addUniform.
  23266. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23267. * @param {Color3} color
  23268. * @param {number} alpha
  23269. */
  23270. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  23271. var temp = [];
  23272. color.toArray(temp);
  23273. temp.push(alpha);
  23274. this.addUniform(name, temp);
  23275. };
  23276. /**
  23277. * Wrapper for addUniform.
  23278. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23279. * @param {Vector3} vector
  23280. */
  23281. UniformBuffer.prototype.addVector3 = function (name, vector) {
  23282. var temp = [];
  23283. vector.toArray(temp);
  23284. this.addUniform(name, temp);
  23285. };
  23286. /**
  23287. * Wrapper for addUniform.
  23288. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23289. */
  23290. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  23291. this.addUniform(name, 12);
  23292. };
  23293. /**
  23294. * Wrapper for addUniform.
  23295. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  23296. */
  23297. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  23298. this.addUniform(name, 8);
  23299. };
  23300. /**
  23301. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  23302. */
  23303. UniformBuffer.prototype.create = function () {
  23304. if (this._noUBO) {
  23305. return;
  23306. }
  23307. if (this._buffer) {
  23308. return; // nothing to do
  23309. }
  23310. // See spec, alignment must be filled as a vec4
  23311. this._fillAlignment(4);
  23312. this._bufferData = new Float32Array(this._data);
  23313. if (this._dynamic) {
  23314. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  23315. }
  23316. else {
  23317. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  23318. }
  23319. this._needSync = true;
  23320. };
  23321. /**
  23322. * Updates the WebGL Uniform Buffer on the GPU.
  23323. * If the `dynamic` flag is set to true, no cache comparison is done.
  23324. * Otherwise, the buffer will be updated only if the cache differs.
  23325. */
  23326. UniformBuffer.prototype.update = function () {
  23327. if (!this._buffer) {
  23328. this.create();
  23329. return;
  23330. }
  23331. if (!this._dynamic && !this._needSync) {
  23332. return;
  23333. }
  23334. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  23335. this._needSync = false;
  23336. };
  23337. /**
  23338. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  23339. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  23340. * @param {number[]|Float32Array} data Flattened data
  23341. * @param {number} size Size of the data.
  23342. */
  23343. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  23344. var location = this._uniformLocations[uniformName];
  23345. if (location === undefined) {
  23346. if (this._buffer) {
  23347. // Cannot add an uniform if the buffer is already created
  23348. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  23349. return;
  23350. }
  23351. this.addUniform(uniformName, size);
  23352. location = this._uniformLocations[uniformName];
  23353. }
  23354. if (!this._buffer) {
  23355. this.create();
  23356. }
  23357. if (!this._dynamic) {
  23358. // Cache for static uniform buffers
  23359. var changed = false;
  23360. for (var i = 0; i < size; i++) {
  23361. if (this._bufferData[location + i] !== data[i]) {
  23362. changed = true;
  23363. this._bufferData[location + i] = data[i];
  23364. }
  23365. }
  23366. this._needSync = this._needSync || changed;
  23367. }
  23368. else {
  23369. // No cache for dynamic
  23370. for (var i = 0; i < size; i++) {
  23371. this._bufferData[location + i] = data[i];
  23372. }
  23373. }
  23374. };
  23375. // Update methods
  23376. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  23377. // To match std140, matrix must be realigned
  23378. for (var i = 0; i < 3; i++) {
  23379. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  23380. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  23381. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  23382. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  23383. }
  23384. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  23385. };
  23386. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  23387. this._currentEffect.setMatrix3x3(name, matrix);
  23388. };
  23389. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  23390. this._currentEffect.setMatrix2x2(name, matrix);
  23391. };
  23392. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  23393. // To match std140, matrix must be realigned
  23394. for (var i = 0; i < 2; i++) {
  23395. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  23396. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  23397. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  23398. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  23399. }
  23400. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  23401. };
  23402. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  23403. this._currentEffect.setFloat(name, x);
  23404. };
  23405. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  23406. UniformBuffer._tempBuffer[0] = x;
  23407. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  23408. };
  23409. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y) {
  23410. this._currentEffect.setFloat2(name, x, y);
  23411. };
  23412. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y) {
  23413. UniformBuffer._tempBuffer[0] = x;
  23414. UniformBuffer._tempBuffer[1] = y;
  23415. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  23416. };
  23417. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  23418. if (suffix === void 0) { suffix = ""; }
  23419. this._currentEffect.setFloat3(name + suffix, x, y, z);
  23420. };
  23421. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  23422. if (suffix === void 0) { suffix = ""; }
  23423. UniformBuffer._tempBuffer[0] = x;
  23424. UniformBuffer._tempBuffer[1] = y;
  23425. UniformBuffer._tempBuffer[2] = z;
  23426. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  23427. };
  23428. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  23429. if (suffix === void 0) { suffix = ""; }
  23430. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  23431. };
  23432. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  23433. if (suffix === void 0) { suffix = ""; }
  23434. UniformBuffer._tempBuffer[0] = x;
  23435. UniformBuffer._tempBuffer[1] = y;
  23436. UniformBuffer._tempBuffer[2] = z;
  23437. UniformBuffer._tempBuffer[3] = w;
  23438. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  23439. };
  23440. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  23441. this._currentEffect.setMatrix(name, mat);
  23442. };
  23443. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  23444. this.updateUniform(name, mat.toArray(), 16);
  23445. };
  23446. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  23447. this._currentEffect.setVector3(name, vector);
  23448. };
  23449. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  23450. vector.toArray(UniformBuffer._tempBuffer);
  23451. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  23452. };
  23453. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  23454. this._currentEffect.setVector4(name, vector);
  23455. };
  23456. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  23457. vector.toArray(UniformBuffer._tempBuffer);
  23458. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  23459. };
  23460. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  23461. if (suffix === void 0) { suffix = ""; }
  23462. this._currentEffect.setColor3(name + suffix, color);
  23463. };
  23464. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  23465. if (suffix === void 0) { suffix = ""; }
  23466. color.toArray(UniformBuffer._tempBuffer);
  23467. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  23468. };
  23469. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  23470. if (suffix === void 0) { suffix = ""; }
  23471. this._currentEffect.setColor4(name + suffix, color, alpha);
  23472. };
  23473. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  23474. if (suffix === void 0) { suffix = ""; }
  23475. color.toArray(UniformBuffer._tempBuffer);
  23476. UniformBuffer._tempBuffer[3] = alpha;
  23477. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  23478. };
  23479. /**
  23480. * Sets a sampler uniform on the effect.
  23481. * @param {string} name Name of the sampler.
  23482. * @param {Texture} texture
  23483. */
  23484. UniformBuffer.prototype.setTexture = function (name, texture) {
  23485. this._currentEffect.setTexture(name, texture);
  23486. };
  23487. /**
  23488. * Directly updates the value of the uniform in the cache AND on the GPU.
  23489. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  23490. * @param {number[]|Float32Array} data Flattened data
  23491. */
  23492. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  23493. this.updateUniform(uniformName, data, data.length);
  23494. this.update();
  23495. };
  23496. /**
  23497. * Binds this uniform buffer to an effect.
  23498. * @param {Effect} effect
  23499. * @param {string} name Name of the uniform block in the shader.
  23500. */
  23501. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  23502. this._currentEffect = effect;
  23503. if (this._noUBO) {
  23504. return;
  23505. }
  23506. effect.bindUniformBuffer(this._buffer, name);
  23507. };
  23508. /**
  23509. * Disposes the uniform buffer.
  23510. */
  23511. UniformBuffer.prototype.dispose = function () {
  23512. if (!this._buffer) {
  23513. return;
  23514. }
  23515. if (this._engine._releaseBuffer(this._buffer)) {
  23516. this._buffer = null;
  23517. }
  23518. };
  23519. return UniformBuffer;
  23520. }());
  23521. // Pool for avoiding memory leaks
  23522. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  23523. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  23524. BABYLON.UniformBuffer = UniformBuffer;
  23525. })(BABYLON || (BABYLON = {}));
  23526. //# sourceMappingURL=babylon.uniformBuffer.js.map
  23527. var BABYLON;
  23528. (function (BABYLON) {
  23529. var PushMaterial = (function (_super) {
  23530. __extends(PushMaterial, _super);
  23531. function PushMaterial(name, scene) {
  23532. var _this = _super.call(this, name, scene) || this;
  23533. _this.storeEffectOnSubMeshes = true;
  23534. return _this;
  23535. }
  23536. PushMaterial.prototype.getEffect = function () {
  23537. return this._activeEffect;
  23538. };
  23539. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  23540. if (!mesh) {
  23541. return false;
  23542. }
  23543. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23544. return true;
  23545. }
  23546. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  23547. };
  23548. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  23549. this._activeEffect.setMatrix("world", world);
  23550. };
  23551. PushMaterial.prototype.bind = function (world, mesh) {
  23552. if (!mesh) {
  23553. return;
  23554. }
  23555. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  23556. };
  23557. PushMaterial.prototype._afterBind = function (mesh, effect) {
  23558. _super.prototype._afterBind.call(this, mesh);
  23559. this.getScene()._cachedEffect = effect;
  23560. };
  23561. PushMaterial.prototype._mustRebind = function (scene, effect) {
  23562. return scene.getCachedEffect() !== effect || scene.getCachedMaterial() !== this;
  23563. };
  23564. PushMaterial.prototype.markAsDirty = function (flag) {
  23565. if (flag & BABYLON.Material.TextureDirtyFlag) {
  23566. this._markAllSubMeshesAsTexturesDirty();
  23567. }
  23568. if (flag & BABYLON.Material.LightDirtyFlag) {
  23569. this._markAllSubMeshesAsLightsDirty();
  23570. }
  23571. if (flag & BABYLON.Material.FresnelDirtyFlag) {
  23572. this._markAllSubMeshesAsFresnelDirty();
  23573. }
  23574. if (flag & BABYLON.Material.AttributesDirtyFlag) {
  23575. this._markAllSubMeshesAsAttributesDirty();
  23576. }
  23577. if (flag & BABYLON.Material.MiscDirtyFlag) {
  23578. this._markAllSubMeshesAsMiscDirty();
  23579. }
  23580. };
  23581. PushMaterial.prototype._markAllSubMeshesAsDirty = function (func) {
  23582. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  23583. var mesh = _a[_i];
  23584. if (!mesh.subMeshes) {
  23585. continue;
  23586. }
  23587. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23588. var subMesh = _c[_b];
  23589. if (subMesh.getMaterial() !== this) {
  23590. continue;
  23591. }
  23592. if (!subMesh._materialDefines) {
  23593. return;
  23594. }
  23595. func(subMesh._materialDefines);
  23596. }
  23597. }
  23598. };
  23599. PushMaterial.prototype._markAllSubMeshesAsTexturesDirty = function () {
  23600. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  23601. };
  23602. PushMaterial.prototype._markAllSubMeshesAsFresnelDirty = function () {
  23603. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  23604. };
  23605. PushMaterial.prototype._markAllSubMeshesAsLightsDirty = function () {
  23606. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  23607. };
  23608. PushMaterial.prototype._markAllSubMeshesAsAttributesDirty = function () {
  23609. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  23610. };
  23611. PushMaterial.prototype._markAllSubMeshesAsMiscDirty = function () {
  23612. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  23613. };
  23614. return PushMaterial;
  23615. }(BABYLON.Material));
  23616. BABYLON.PushMaterial = PushMaterial;
  23617. })(BABYLON || (BABYLON = {}));
  23618. //# sourceMappingURL=babylon.pushMaterial.js.map
  23619. var BABYLON;
  23620. (function (BABYLON) {
  23621. var VertexData = (function () {
  23622. function VertexData() {
  23623. }
  23624. VertexData.prototype.set = function (data, kind) {
  23625. switch (kind) {
  23626. case BABYLON.VertexBuffer.PositionKind:
  23627. this.positions = data;
  23628. break;
  23629. case BABYLON.VertexBuffer.NormalKind:
  23630. this.normals = data;
  23631. break;
  23632. case BABYLON.VertexBuffer.TangentKind:
  23633. this.tangents = data;
  23634. break;
  23635. case BABYLON.VertexBuffer.UVKind:
  23636. this.uvs = data;
  23637. break;
  23638. case BABYLON.VertexBuffer.UV2Kind:
  23639. this.uvs2 = data;
  23640. break;
  23641. case BABYLON.VertexBuffer.UV3Kind:
  23642. this.uvs3 = data;
  23643. break;
  23644. case BABYLON.VertexBuffer.UV4Kind:
  23645. this.uvs4 = data;
  23646. break;
  23647. case BABYLON.VertexBuffer.UV5Kind:
  23648. this.uvs5 = data;
  23649. break;
  23650. case BABYLON.VertexBuffer.UV6Kind:
  23651. this.uvs6 = data;
  23652. break;
  23653. case BABYLON.VertexBuffer.ColorKind:
  23654. this.colors = data;
  23655. break;
  23656. case BABYLON.VertexBuffer.MatricesIndicesKind:
  23657. this.matricesIndices = data;
  23658. break;
  23659. case BABYLON.VertexBuffer.MatricesWeightsKind:
  23660. this.matricesWeights = data;
  23661. break;
  23662. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  23663. this.matricesIndicesExtra = data;
  23664. break;
  23665. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  23666. this.matricesWeightsExtra = data;
  23667. break;
  23668. }
  23669. };
  23670. /**
  23671. * Associates the vertexData to the passed Mesh.
  23672. * Sets it as updatable or not (default `false`).
  23673. * Returns the VertexData.
  23674. */
  23675. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  23676. this._applyTo(mesh, updatable);
  23677. return this;
  23678. };
  23679. /**
  23680. * Associates the vertexData to the passed Geometry.
  23681. * Sets it as updatable or not (default `false`).
  23682. * Returns the VertexData.
  23683. */
  23684. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  23685. this._applyTo(geometry, updatable);
  23686. return this;
  23687. };
  23688. /**
  23689. * Updates the associated mesh.
  23690. * Returns the VertexData.
  23691. */
  23692. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  23693. this._update(mesh);
  23694. return this;
  23695. };
  23696. /**
  23697. * Updates the associated geometry.
  23698. * Returns the VertexData.
  23699. */
  23700. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  23701. this._update(geometry);
  23702. return this;
  23703. };
  23704. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  23705. if (this.positions) {
  23706. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  23707. }
  23708. if (this.normals) {
  23709. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  23710. }
  23711. if (this.tangents) {
  23712. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  23713. }
  23714. if (this.uvs) {
  23715. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  23716. }
  23717. if (this.uvs2) {
  23718. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  23719. }
  23720. if (this.uvs3) {
  23721. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  23722. }
  23723. if (this.uvs4) {
  23724. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  23725. }
  23726. if (this.uvs5) {
  23727. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  23728. }
  23729. if (this.uvs6) {
  23730. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  23731. }
  23732. if (this.colors) {
  23733. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  23734. }
  23735. if (this.matricesIndices) {
  23736. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  23737. }
  23738. if (this.matricesWeights) {
  23739. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  23740. }
  23741. if (this.matricesIndicesExtra) {
  23742. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  23743. }
  23744. if (this.matricesWeightsExtra) {
  23745. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  23746. }
  23747. if (this.indices) {
  23748. meshOrGeometry.setIndices(this.indices);
  23749. }
  23750. return this;
  23751. };
  23752. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  23753. if (this.positions) {
  23754. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  23755. }
  23756. if (this.normals) {
  23757. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  23758. }
  23759. if (this.tangents) {
  23760. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  23761. }
  23762. if (this.uvs) {
  23763. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  23764. }
  23765. if (this.uvs2) {
  23766. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  23767. }
  23768. if (this.uvs3) {
  23769. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  23770. }
  23771. if (this.uvs4) {
  23772. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  23773. }
  23774. if (this.uvs5) {
  23775. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  23776. }
  23777. if (this.uvs6) {
  23778. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  23779. }
  23780. if (this.colors) {
  23781. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  23782. }
  23783. if (this.matricesIndices) {
  23784. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  23785. }
  23786. if (this.matricesWeights) {
  23787. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  23788. }
  23789. if (this.matricesIndicesExtra) {
  23790. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  23791. }
  23792. if (this.matricesWeightsExtra) {
  23793. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  23794. }
  23795. if (this.indices) {
  23796. meshOrGeometry.setIndices(this.indices);
  23797. }
  23798. return this;
  23799. };
  23800. /**
  23801. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  23802. * Returns the VertexData.
  23803. */
  23804. VertexData.prototype.transform = function (matrix) {
  23805. var transformed = BABYLON.Vector3.Zero();
  23806. var index;
  23807. if (this.positions) {
  23808. var position = BABYLON.Vector3.Zero();
  23809. for (index = 0; index < this.positions.length; index += 3) {
  23810. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  23811. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  23812. this.positions[index] = transformed.x;
  23813. this.positions[index + 1] = transformed.y;
  23814. this.positions[index + 2] = transformed.z;
  23815. }
  23816. }
  23817. if (this.normals) {
  23818. var normal = BABYLON.Vector3.Zero();
  23819. for (index = 0; index < this.normals.length; index += 3) {
  23820. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  23821. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  23822. this.normals[index] = transformed.x;
  23823. this.normals[index + 1] = transformed.y;
  23824. this.normals[index + 2] = transformed.z;
  23825. }
  23826. }
  23827. if (this.tangents) {
  23828. var tangent = BABYLON.Vector4.Zero();
  23829. var tangentTransformed = BABYLON.Vector4.Zero();
  23830. for (index = 0; index < this.tangents.length; index += 4) {
  23831. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  23832. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  23833. this.tangents[index] = tangentTransformed.x;
  23834. this.tangents[index + 1] = tangentTransformed.y;
  23835. this.tangents[index + 2] = tangentTransformed.z;
  23836. this.tangents[index + 3] = tangentTransformed.w;
  23837. }
  23838. }
  23839. return this;
  23840. };
  23841. /**
  23842. * Merges the passed VertexData into the current one.
  23843. * Returns the modified VertexData.
  23844. */
  23845. VertexData.prototype.merge = function (other) {
  23846. if (other.indices) {
  23847. if (!this.indices) {
  23848. this.indices = [];
  23849. }
  23850. var offset = this.positions ? this.positions.length / 3 : 0;
  23851. for (var index = 0; index < other.indices.length; index++) {
  23852. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  23853. this.indices.push(other.indices[index] + offset);
  23854. }
  23855. }
  23856. this.positions = this._mergeElement(this.positions, other.positions);
  23857. this.normals = this._mergeElement(this.normals, other.normals);
  23858. this.tangents = this._mergeElement(this.tangents, other.tangents);
  23859. this.uvs = this._mergeElement(this.uvs, other.uvs);
  23860. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  23861. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  23862. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  23863. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  23864. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  23865. this.colors = this._mergeElement(this.colors, other.colors);
  23866. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  23867. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  23868. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  23869. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  23870. return this;
  23871. };
  23872. VertexData.prototype._mergeElement = function (source, other) {
  23873. if (!other)
  23874. return source;
  23875. if (!source)
  23876. return other;
  23877. var len = other.length + source.length;
  23878. var isSrcTypedArray = source instanceof Float32Array;
  23879. var isOthTypedArray = other instanceof Float32Array;
  23880. // use non-loop method when the source is Float32Array
  23881. if (isSrcTypedArray) {
  23882. var ret32 = new Float32Array(len);
  23883. ret32.set(source);
  23884. ret32.set(other, source.length);
  23885. return ret32;
  23886. // source is number[], when other is also use concat
  23887. }
  23888. else if (!isOthTypedArray) {
  23889. return source.concat(other);
  23890. // source is a number[], but other is a Float32Array, loop required
  23891. }
  23892. else {
  23893. var ret = source.slice(0); // copy source to a separate array
  23894. for (var i = 0, len = other.length; i < len; i++) {
  23895. ret.push(other[i]);
  23896. }
  23897. return ret;
  23898. }
  23899. };
  23900. /**
  23901. * Serializes the VertexData.
  23902. * Returns a serialized object.
  23903. */
  23904. VertexData.prototype.serialize = function () {
  23905. var serializationObject = this.serialize();
  23906. if (this.positions) {
  23907. serializationObject.positions = this.positions;
  23908. }
  23909. if (this.normals) {
  23910. serializationObject.normals = this.normals;
  23911. }
  23912. if (this.tangents) {
  23913. serializationObject.tangents = this.tangents;
  23914. }
  23915. if (this.uvs) {
  23916. serializationObject.uvs = this.uvs;
  23917. }
  23918. if (this.uvs2) {
  23919. serializationObject.uvs2 = this.uvs2;
  23920. }
  23921. if (this.uvs3) {
  23922. serializationObject.uvs3 = this.uvs3;
  23923. }
  23924. if (this.uvs4) {
  23925. serializationObject.uvs4 = this.uvs4;
  23926. }
  23927. if (this.uvs5) {
  23928. serializationObject.uvs5 = this.uvs5;
  23929. }
  23930. if (this.uvs6) {
  23931. serializationObject.uvs6 = this.uvs6;
  23932. }
  23933. if (this.colors) {
  23934. serializationObject.colors = this.colors;
  23935. }
  23936. if (this.matricesIndices) {
  23937. serializationObject.matricesIndices = this.matricesIndices;
  23938. serializationObject.matricesIndices._isExpanded = true;
  23939. }
  23940. if (this.matricesWeights) {
  23941. serializationObject.matricesWeights = this.matricesWeights;
  23942. }
  23943. if (this.matricesIndicesExtra) {
  23944. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  23945. serializationObject.matricesIndicesExtra._isExpanded = true;
  23946. }
  23947. if (this.matricesWeightsExtra) {
  23948. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  23949. }
  23950. serializationObject.indices = this.indices;
  23951. return serializationObject;
  23952. };
  23953. // Statics
  23954. /**
  23955. * Returns the object VertexData associated to the passed mesh.
  23956. */
  23957. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  23958. return VertexData._ExtractFrom(mesh, copyWhenShared);
  23959. };
  23960. /**
  23961. * Returns the object VertexData associated to the passed geometry.
  23962. */
  23963. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  23964. return VertexData._ExtractFrom(geometry, copyWhenShared);
  23965. };
  23966. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  23967. var result = new VertexData();
  23968. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23969. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  23970. }
  23971. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23972. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  23973. }
  23974. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  23975. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared);
  23976. }
  23977. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23978. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  23979. }
  23980. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23981. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  23982. }
  23983. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  23984. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  23985. }
  23986. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  23987. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  23988. }
  23989. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  23990. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  23991. }
  23992. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  23993. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  23994. }
  23995. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23996. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  23997. }
  23998. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23999. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24000. }
  24001. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24002. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24003. }
  24004. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  24005. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  24006. }
  24007. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  24008. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  24009. }
  24010. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24011. return result;
  24012. };
  24013. /**
  24014. * Creates the vertexData of the Ribbon.
  24015. */
  24016. VertexData.CreateRibbon = function (options) {
  24017. var pathArray = options.pathArray;
  24018. var closeArray = options.closeArray || false;
  24019. var closePath = options.closePath || false;
  24020. var invertUV = options.invertUV || false;
  24021. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24022. var offset = options.offset || defaultOffset;
  24023. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24024. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24025. var customUV = options.uvs;
  24026. var customColors = options.colors;
  24027. var positions = [];
  24028. var indices = [];
  24029. var normals = [];
  24030. var uvs = [];
  24031. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24032. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24033. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24034. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24035. var minlg; // minimal length among all paths from pathArray
  24036. var lg = []; // array of path lengths : nb of vertex per path
  24037. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  24038. var p; // path iterator
  24039. var i; // point iterator
  24040. var j; // point iterator
  24041. // if single path in pathArray
  24042. if (pathArray.length < 2) {
  24043. var ar1 = [];
  24044. var ar2 = [];
  24045. for (i = 0; i < pathArray[0].length - offset; i++) {
  24046. ar1.push(pathArray[0][i]);
  24047. ar2.push(pathArray[0][i + offset]);
  24048. }
  24049. pathArray = [ar1, ar2];
  24050. }
  24051. // positions and horizontal distances (u)
  24052. var idc = 0;
  24053. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  24054. var path;
  24055. var l;
  24056. minlg = pathArray[0].length;
  24057. var vectlg;
  24058. var dist;
  24059. for (p = 0; p < pathArray.length; p++) {
  24060. uTotalDistance[p] = 0;
  24061. us[p] = [0];
  24062. path = pathArray[p];
  24063. l = path.length;
  24064. minlg = (minlg < l) ? minlg : l;
  24065. j = 0;
  24066. while (j < l) {
  24067. positions.push(path[j].x, path[j].y, path[j].z);
  24068. if (j > 0) {
  24069. vectlg = path[j].subtract(path[j - 1]).length();
  24070. dist = vectlg + uTotalDistance[p];
  24071. us[p].push(dist);
  24072. uTotalDistance[p] = dist;
  24073. }
  24074. j++;
  24075. }
  24076. if (closePath) {
  24077. j--;
  24078. positions.push(path[0].x, path[0].y, path[0].z);
  24079. vectlg = path[j].subtract(path[0]).length();
  24080. dist = vectlg + uTotalDistance[p];
  24081. us[p].push(dist);
  24082. uTotalDistance[p] = dist;
  24083. }
  24084. lg[p] = l + closePathCorr;
  24085. idx[p] = idc;
  24086. idc += (l + closePathCorr);
  24087. }
  24088. // vertical distances (v)
  24089. var path1;
  24090. var path2;
  24091. var vertex1;
  24092. var vertex2;
  24093. for (i = 0; i < minlg + closePathCorr; i++) {
  24094. vTotalDistance[i] = 0;
  24095. vs[i] = [0];
  24096. for (p = 0; p < pathArray.length - 1; p++) {
  24097. path1 = pathArray[p];
  24098. path2 = pathArray[p + 1];
  24099. if (i === minlg) {
  24100. vertex1 = path1[0];
  24101. vertex2 = path2[0];
  24102. }
  24103. else {
  24104. vertex1 = path1[i];
  24105. vertex2 = path2[i];
  24106. }
  24107. vectlg = vertex2.subtract(vertex1).length();
  24108. dist = vectlg + vTotalDistance[i];
  24109. vs[i].push(dist);
  24110. vTotalDistance[i] = dist;
  24111. }
  24112. if (closeArray) {
  24113. path1 = pathArray[p];
  24114. path2 = pathArray[0];
  24115. if (i === minlg) {
  24116. vertex2 = path2[0];
  24117. }
  24118. vectlg = vertex2.subtract(vertex1).length();
  24119. dist = vectlg + vTotalDistance[i];
  24120. vTotalDistance[i] = dist;
  24121. }
  24122. }
  24123. // uvs
  24124. var u;
  24125. var v;
  24126. if (customUV) {
  24127. for (p = 0; p < customUV.length; p++) {
  24128. uvs.push(customUV[p].x, customUV[p].y);
  24129. }
  24130. }
  24131. else {
  24132. for (p = 0; p < pathArray.length; p++) {
  24133. for (i = 0; i < minlg + closePathCorr; i++) {
  24134. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  24135. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  24136. if (invertUV) {
  24137. uvs.push(v, u);
  24138. }
  24139. else {
  24140. uvs.push(u, v);
  24141. }
  24142. }
  24143. }
  24144. }
  24145. // indices
  24146. p = 0; // path index
  24147. var pi = 0; // positions array index
  24148. var l1 = lg[p] - 1; // path1 length
  24149. var l2 = lg[p + 1] - 1; // path2 length
  24150. var min = (l1 < l2) ? l1 : l2; // current path stop index
  24151. var shft = idx[1] - idx[0]; // shift
  24152. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  24153. while (pi <= min && p < path1nb) {
  24154. // 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
  24155. indices.push(pi, pi + shft, pi + 1);
  24156. indices.push(pi + shft + 1, pi + 1, pi + shft);
  24157. pi += 1;
  24158. if (pi === min) {
  24159. p++;
  24160. if (p === lg.length - 1) {
  24161. shft = idx[0] - idx[p];
  24162. l1 = lg[p] - 1;
  24163. l2 = lg[0] - 1;
  24164. }
  24165. else {
  24166. shft = idx[p + 1] - idx[p];
  24167. l1 = lg[p] - 1;
  24168. l2 = lg[p + 1] - 1;
  24169. }
  24170. pi = idx[p];
  24171. min = (l1 < l2) ? l1 + pi : l2 + pi;
  24172. }
  24173. }
  24174. // normals
  24175. VertexData.ComputeNormals(positions, indices, normals);
  24176. if (closePath) {
  24177. var indexFirst = 0;
  24178. var indexLast = 0;
  24179. for (p = 0; p < pathArray.length; p++) {
  24180. indexFirst = idx[p] * 3;
  24181. if (p + 1 < pathArray.length) {
  24182. indexLast = (idx[p + 1] - 1) * 3;
  24183. }
  24184. else {
  24185. indexLast = normals.length - 3;
  24186. }
  24187. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  24188. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  24189. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  24190. normals[indexLast] = normals[indexFirst];
  24191. normals[indexLast + 1] = normals[indexFirst + 1];
  24192. normals[indexLast + 2] = normals[indexFirst + 2];
  24193. }
  24194. }
  24195. // sides
  24196. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24197. // Colors
  24198. if (customColors) {
  24199. var colors = new Float32Array(customColors.length * 4);
  24200. for (var c = 0; c < customColors.length; c++) {
  24201. colors[c * 4] = customColors[c].r;
  24202. colors[c * 4 + 1] = customColors[c].g;
  24203. colors[c * 4 + 2] = customColors[c].b;
  24204. colors[c * 4 + 3] = customColors[c].a;
  24205. }
  24206. }
  24207. // Result
  24208. var vertexData = new VertexData();
  24209. var positions32 = new Float32Array(positions);
  24210. var normals32 = new Float32Array(normals);
  24211. var uvs32 = new Float32Array(uvs);
  24212. vertexData.indices = indices;
  24213. vertexData.positions = positions32;
  24214. vertexData.normals = normals32;
  24215. vertexData.uvs = uvs32;
  24216. if (customColors) {
  24217. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  24218. }
  24219. if (closePath) {
  24220. vertexData._idx = idx;
  24221. }
  24222. return vertexData;
  24223. };
  24224. /**
  24225. * Creates the VertexData of the Box.
  24226. */
  24227. VertexData.CreateBox = function (options) {
  24228. var normalsSource = [
  24229. new BABYLON.Vector3(0, 0, 1),
  24230. new BABYLON.Vector3(0, 0, -1),
  24231. new BABYLON.Vector3(1, 0, 0),
  24232. new BABYLON.Vector3(-1, 0, 0),
  24233. new BABYLON.Vector3(0, 1, 0),
  24234. new BABYLON.Vector3(0, -1, 0)
  24235. ];
  24236. var indices = [];
  24237. var positions = [];
  24238. var normals = [];
  24239. var uvs = [];
  24240. var width = options.width || options.size || 1;
  24241. var height = options.height || options.size || 1;
  24242. var depth = options.depth || options.size || 1;
  24243. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24244. var faceUV = options.faceUV || new Array(6);
  24245. var faceColors = options.faceColors;
  24246. var colors = [];
  24247. // default face colors and UV if undefined
  24248. for (var f = 0; f < 6; f++) {
  24249. if (faceUV[f] === undefined) {
  24250. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24251. }
  24252. if (faceColors && faceColors[f] === undefined) {
  24253. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24254. }
  24255. }
  24256. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  24257. // Create each face in turn.
  24258. for (var index = 0; index < normalsSource.length; index++) {
  24259. var normal = normalsSource[index];
  24260. // Get two vectors perpendicular to the face normal and to each other.
  24261. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  24262. var side2 = BABYLON.Vector3.Cross(normal, side1);
  24263. // Six indices (two triangles) per face.
  24264. var verticesLength = positions.length / 3;
  24265. indices.push(verticesLength);
  24266. indices.push(verticesLength + 1);
  24267. indices.push(verticesLength + 2);
  24268. indices.push(verticesLength);
  24269. indices.push(verticesLength + 2);
  24270. indices.push(verticesLength + 3);
  24271. // Four vertices per face.
  24272. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  24273. positions.push(vertex.x, vertex.y, vertex.z);
  24274. normals.push(normal.x, normal.y, normal.z);
  24275. uvs.push(faceUV[index].z, faceUV[index].w);
  24276. if (faceColors) {
  24277. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24278. }
  24279. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  24280. positions.push(vertex.x, vertex.y, vertex.z);
  24281. normals.push(normal.x, normal.y, normal.z);
  24282. uvs.push(faceUV[index].x, faceUV[index].w);
  24283. if (faceColors) {
  24284. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24285. }
  24286. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  24287. positions.push(vertex.x, vertex.y, vertex.z);
  24288. normals.push(normal.x, normal.y, normal.z);
  24289. uvs.push(faceUV[index].x, faceUV[index].y);
  24290. if (faceColors) {
  24291. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24292. }
  24293. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  24294. positions.push(vertex.x, vertex.y, vertex.z);
  24295. normals.push(normal.x, normal.y, normal.z);
  24296. uvs.push(faceUV[index].z, faceUV[index].y);
  24297. if (faceColors) {
  24298. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  24299. }
  24300. }
  24301. // sides
  24302. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24303. // Result
  24304. var vertexData = new VertexData();
  24305. vertexData.indices = indices;
  24306. vertexData.positions = positions;
  24307. vertexData.normals = normals;
  24308. vertexData.uvs = uvs;
  24309. if (faceColors) {
  24310. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  24311. vertexData.colors = totalColors;
  24312. }
  24313. return vertexData;
  24314. };
  24315. /**
  24316. * Creates the VertexData of the Sphere.
  24317. */
  24318. VertexData.CreateSphere = function (options) {
  24319. var segments = options.segments || 32;
  24320. var diameterX = options.diameterX || options.diameter || 1;
  24321. var diameterY = options.diameterY || options.diameter || 1;
  24322. var diameterZ = options.diameterZ || options.diameter || 1;
  24323. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24324. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  24325. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24326. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  24327. var totalZRotationSteps = 2 + segments;
  24328. var totalYRotationSteps = 2 * totalZRotationSteps;
  24329. var indices = [];
  24330. var positions = [];
  24331. var normals = [];
  24332. var uvs = [];
  24333. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  24334. var normalizedZ = zRotationStep / totalZRotationSteps;
  24335. var angleZ = normalizedZ * Math.PI * slice;
  24336. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  24337. var normalizedY = yRotationStep / totalYRotationSteps;
  24338. var angleY = normalizedY * Math.PI * 2 * arc;
  24339. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  24340. var rotationY = BABYLON.Matrix.RotationY(angleY);
  24341. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  24342. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  24343. var vertex = complete.multiply(radius);
  24344. var normal = complete.divide(radius).normalize();
  24345. positions.push(vertex.x, vertex.y, vertex.z);
  24346. normals.push(normal.x, normal.y, normal.z);
  24347. uvs.push(normalizedY, normalizedZ);
  24348. }
  24349. if (zRotationStep > 0) {
  24350. var verticesCount = positions.length / 3;
  24351. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  24352. indices.push((firstIndex));
  24353. indices.push((firstIndex + 1));
  24354. indices.push(firstIndex + totalYRotationSteps + 1);
  24355. indices.push((firstIndex + totalYRotationSteps + 1));
  24356. indices.push((firstIndex + 1));
  24357. indices.push((firstIndex + totalYRotationSteps + 2));
  24358. }
  24359. }
  24360. }
  24361. // Sides
  24362. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24363. // Result
  24364. var vertexData = new VertexData();
  24365. vertexData.indices = indices;
  24366. vertexData.positions = positions;
  24367. vertexData.normals = normals;
  24368. vertexData.uvs = uvs;
  24369. return vertexData;
  24370. };
  24371. /**
  24372. * Creates the VertexData of the Cylinder or Cone.
  24373. */
  24374. VertexData.CreateCylinder = function (options) {
  24375. var height = options.height || 2;
  24376. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  24377. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  24378. var tessellation = options.tessellation || 24;
  24379. var subdivisions = options.subdivisions || 1;
  24380. var hasRings = options.hasRings;
  24381. var enclose = options.enclose;
  24382. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24383. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24384. var faceUV = options.faceUV || new Array(3);
  24385. var faceColors = options.faceColors;
  24386. // default face colors and UV if undefined
  24387. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  24388. var ringNb = (hasRings) ? subdivisions : 1;
  24389. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  24390. var f;
  24391. for (f = 0; f < surfaceNb; f++) {
  24392. if (faceColors && faceColors[f] === undefined) {
  24393. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  24394. }
  24395. }
  24396. for (f = 0; f < surfaceNb; f++) {
  24397. if (faceUV && faceUV[f] === undefined) {
  24398. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  24399. }
  24400. }
  24401. var indices = [];
  24402. var positions = [];
  24403. var normals = [];
  24404. var uvs = [];
  24405. var colors = [];
  24406. var angle_step = Math.PI * 2 * arc / tessellation;
  24407. var angle;
  24408. var h;
  24409. var radius;
  24410. var tan = (diameterBottom - diameterTop) / 2 / height;
  24411. var ringVertex = BABYLON.Vector3.Zero();
  24412. var ringNormal = BABYLON.Vector3.Zero();
  24413. var ringFirstVertex = BABYLON.Vector3.Zero();
  24414. var ringFirstNormal = BABYLON.Vector3.Zero();
  24415. var quadNormal = BABYLON.Vector3.Zero();
  24416. var Y = BABYLON.Axis.Y;
  24417. // positions, normals, uvs
  24418. var i;
  24419. var j;
  24420. var r;
  24421. var ringIdx = 1;
  24422. var s = 1; // surface index
  24423. var cs = 0;
  24424. var v = 0;
  24425. for (i = 0; i <= subdivisions; i++) {
  24426. h = i / subdivisions;
  24427. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  24428. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  24429. for (r = 0; r < ringIdx; r++) {
  24430. if (hasRings) {
  24431. s += r;
  24432. }
  24433. if (enclose) {
  24434. s += 2 * r;
  24435. }
  24436. for (j = 0; j <= tessellation; j++) {
  24437. angle = j * angle_step;
  24438. // position
  24439. ringVertex.x = Math.cos(-angle) * radius;
  24440. ringVertex.y = -height / 2 + h * height;
  24441. ringVertex.z = Math.sin(-angle) * radius;
  24442. // normal
  24443. if (diameterTop === 0 && i === subdivisions) {
  24444. // if no top cap, reuse former normals
  24445. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  24446. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  24447. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  24448. }
  24449. else {
  24450. ringNormal.x = ringVertex.x;
  24451. ringNormal.z = ringVertex.z;
  24452. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  24453. ringNormal.normalize();
  24454. }
  24455. // keep first ring vertex values for enclose
  24456. if (j === 0) {
  24457. ringFirstVertex.copyFrom(ringVertex);
  24458. ringFirstNormal.copyFrom(ringNormal);
  24459. }
  24460. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24461. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  24462. if (hasRings) {
  24463. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  24464. }
  24465. else {
  24466. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  24467. }
  24468. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  24469. if (faceColors) {
  24470. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  24471. }
  24472. }
  24473. // if enclose, add four vertices and their dedicated normals
  24474. if (arc !== 1 && enclose) {
  24475. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  24476. positions.push(0, ringVertex.y, 0);
  24477. positions.push(0, ringVertex.y, 0);
  24478. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  24479. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  24480. quadNormal.normalize();
  24481. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24482. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  24483. quadNormal.normalize();
  24484. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  24485. if (hasRings) {
  24486. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  24487. }
  24488. else {
  24489. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  24490. }
  24491. uvs.push(faceUV[s + 1].x, v);
  24492. uvs.push(faceUV[s + 1].z, v);
  24493. if (hasRings) {
  24494. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  24495. }
  24496. else {
  24497. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  24498. }
  24499. uvs.push(faceUV[s + 2].x, v);
  24500. uvs.push(faceUV[s + 2].z, v);
  24501. if (faceColors) {
  24502. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24503. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  24504. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24505. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  24506. }
  24507. }
  24508. if (cs !== s) {
  24509. cs = s;
  24510. }
  24511. }
  24512. }
  24513. // indices
  24514. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  24515. var s;
  24516. i = 0;
  24517. for (s = 0; s < subdivisions; s++) {
  24518. for (j = 0; j < tessellation; j++) {
  24519. var i0 = i * (e + 1) + j;
  24520. var i1 = (i + 1) * (e + 1) + j;
  24521. var i2 = i * (e + 1) + (j + 1);
  24522. var i3 = (i + 1) * (e + 1) + (j + 1);
  24523. indices.push(i0, i1, i2);
  24524. indices.push(i3, i2, i1);
  24525. }
  24526. if (arc !== 1 && enclose) {
  24527. indices.push(i0 + 2, i1 + 2, i2 + 2);
  24528. indices.push(i3 + 2, i2 + 2, i1 + 2);
  24529. indices.push(i0 + 4, i1 + 4, i2 + 4);
  24530. indices.push(i3 + 4, i2 + 4, i1 + 4);
  24531. }
  24532. i = (hasRings) ? (i + 2) : (i + 1);
  24533. }
  24534. // Caps
  24535. var createCylinderCap = function (isTop) {
  24536. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  24537. if (radius === 0) {
  24538. return;
  24539. }
  24540. // Cap positions, normals & uvs
  24541. var angle;
  24542. var circleVector;
  24543. var i;
  24544. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  24545. var c;
  24546. if (faceColors) {
  24547. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  24548. }
  24549. // cap center
  24550. var vbase = positions.length / 3;
  24551. var offset = isTop ? height / 2 : -height / 2;
  24552. var center = new BABYLON.Vector3(0, offset, 0);
  24553. positions.push(center.x, center.y, center.z);
  24554. normals.push(0, isTop ? 1 : -1, 0);
  24555. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  24556. if (faceColors) {
  24557. colors.push(c.r, c.g, c.b, c.a);
  24558. }
  24559. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  24560. for (i = 0; i <= tessellation; i++) {
  24561. angle = Math.PI * 2 * i * arc / tessellation;
  24562. var cos = Math.cos(-angle);
  24563. var sin = Math.sin(-angle);
  24564. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  24565. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  24566. positions.push(circleVector.x, circleVector.y, circleVector.z);
  24567. normals.push(0, isTop ? 1 : -1, 0);
  24568. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  24569. if (faceColors) {
  24570. colors.push(c.r, c.g, c.b, c.a);
  24571. }
  24572. }
  24573. // Cap indices
  24574. for (i = 0; i < tessellation; i++) {
  24575. if (!isTop) {
  24576. indices.push(vbase);
  24577. indices.push(vbase + (i + 1));
  24578. indices.push(vbase + (i + 2));
  24579. }
  24580. else {
  24581. indices.push(vbase);
  24582. indices.push(vbase + (i + 2));
  24583. indices.push(vbase + (i + 1));
  24584. }
  24585. }
  24586. };
  24587. // add caps to geometry
  24588. createCylinderCap(false);
  24589. createCylinderCap(true);
  24590. // Sides
  24591. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24592. var vertexData = new VertexData();
  24593. vertexData.indices = indices;
  24594. vertexData.positions = positions;
  24595. vertexData.normals = normals;
  24596. vertexData.uvs = uvs;
  24597. if (faceColors) {
  24598. vertexData.colors = colors;
  24599. }
  24600. return vertexData;
  24601. };
  24602. /**
  24603. * Creates the VertexData of the Torus.
  24604. */
  24605. VertexData.CreateTorus = function (options) {
  24606. var indices = [];
  24607. var positions = [];
  24608. var normals = [];
  24609. var uvs = [];
  24610. var diameter = options.diameter || 1;
  24611. var thickness = options.thickness || 0.5;
  24612. var tessellation = options.tessellation || 16;
  24613. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24614. var stride = tessellation + 1;
  24615. for (var i = 0; i <= tessellation; i++) {
  24616. var u = i / tessellation;
  24617. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  24618. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  24619. for (var j = 0; j <= tessellation; j++) {
  24620. var v = 1 - j / tessellation;
  24621. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  24622. var dx = Math.cos(innerAngle);
  24623. var dy = Math.sin(innerAngle);
  24624. // Create a vertex.
  24625. var normal = new BABYLON.Vector3(dx, dy, 0);
  24626. var position = normal.scale(thickness / 2);
  24627. var textureCoordinate = new BABYLON.Vector2(u, v);
  24628. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  24629. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  24630. positions.push(position.x, position.y, position.z);
  24631. normals.push(normal.x, normal.y, normal.z);
  24632. uvs.push(textureCoordinate.x, textureCoordinate.y);
  24633. // And create indices for two triangles.
  24634. var nextI = (i + 1) % stride;
  24635. var nextJ = (j + 1) % stride;
  24636. indices.push(i * stride + j);
  24637. indices.push(i * stride + nextJ);
  24638. indices.push(nextI * stride + j);
  24639. indices.push(i * stride + nextJ);
  24640. indices.push(nextI * stride + nextJ);
  24641. indices.push(nextI * stride + j);
  24642. }
  24643. }
  24644. // Sides
  24645. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24646. // Result
  24647. var vertexData = new VertexData();
  24648. vertexData.indices = indices;
  24649. vertexData.positions = positions;
  24650. vertexData.normals = normals;
  24651. vertexData.uvs = uvs;
  24652. return vertexData;
  24653. };
  24654. /**
  24655. * Creates the VertexData of the LineSystem.
  24656. */
  24657. VertexData.CreateLineSystem = function (options) {
  24658. var indices = [];
  24659. var positions = [];
  24660. var lines = options.lines;
  24661. var idx = 0;
  24662. for (var l = 0; l < lines.length; l++) {
  24663. var points = lines[l];
  24664. for (var index = 0; index < points.length; index++) {
  24665. positions.push(points[index].x, points[index].y, points[index].z);
  24666. if (index > 0) {
  24667. indices.push(idx - 1);
  24668. indices.push(idx);
  24669. }
  24670. idx++;
  24671. }
  24672. }
  24673. var vertexData = new VertexData();
  24674. vertexData.indices = indices;
  24675. vertexData.positions = positions;
  24676. return vertexData;
  24677. };
  24678. /**
  24679. * Create the VertexData of the DashedLines.
  24680. */
  24681. VertexData.CreateDashedLines = function (options) {
  24682. var dashSize = options.dashSize || 3;
  24683. var gapSize = options.gapSize || 1;
  24684. var dashNb = options.dashNb || 200;
  24685. var points = options.points;
  24686. var positions = new Array();
  24687. var indices = new Array();
  24688. var curvect = BABYLON.Vector3.Zero();
  24689. var lg = 0;
  24690. var nb = 0;
  24691. var shft = 0;
  24692. var dashshft = 0;
  24693. var curshft = 0;
  24694. var idx = 0;
  24695. var i = 0;
  24696. for (i = 0; i < points.length - 1; i++) {
  24697. points[i + 1].subtractToRef(points[i], curvect);
  24698. lg += curvect.length();
  24699. }
  24700. shft = lg / dashNb;
  24701. dashshft = dashSize * shft / (dashSize + gapSize);
  24702. for (i = 0; i < points.length - 1; i++) {
  24703. points[i + 1].subtractToRef(points[i], curvect);
  24704. nb = Math.floor(curvect.length() / shft);
  24705. curvect.normalize();
  24706. for (var j = 0; j < nb; j++) {
  24707. curshft = shft * j;
  24708. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  24709. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  24710. indices.push(idx, idx + 1);
  24711. idx += 2;
  24712. }
  24713. }
  24714. // Result
  24715. var vertexData = new VertexData();
  24716. vertexData.positions = positions;
  24717. vertexData.indices = indices;
  24718. return vertexData;
  24719. };
  24720. /**
  24721. * Creates the VertexData of the Ground.
  24722. */
  24723. VertexData.CreateGround = function (options) {
  24724. var indices = [];
  24725. var positions = [];
  24726. var normals = [];
  24727. var uvs = [];
  24728. var row, col;
  24729. var width = options.width || 1;
  24730. var height = options.height || 1;
  24731. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  24732. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  24733. for (row = 0; row <= subdivisionsY; row++) {
  24734. for (col = 0; col <= subdivisionsX; col++) {
  24735. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  24736. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24737. positions.push(position.x, position.y, position.z);
  24738. normals.push(normal.x, normal.y, normal.z);
  24739. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  24740. }
  24741. }
  24742. for (row = 0; row < subdivisionsY; row++) {
  24743. for (col = 0; col < subdivisionsX; col++) {
  24744. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  24745. indices.push(col + 1 + row * (subdivisionsX + 1));
  24746. indices.push(col + row * (subdivisionsX + 1));
  24747. indices.push(col + (row + 1) * (subdivisionsX + 1));
  24748. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  24749. indices.push(col + row * (subdivisionsX + 1));
  24750. }
  24751. }
  24752. // Result
  24753. var vertexData = new VertexData();
  24754. vertexData.indices = indices;
  24755. vertexData.positions = positions;
  24756. vertexData.normals = normals;
  24757. vertexData.uvs = uvs;
  24758. return vertexData;
  24759. };
  24760. /**
  24761. * Creates the VertexData of the TiledGround.
  24762. */
  24763. VertexData.CreateTiledGround = function (options) {
  24764. var xmin = options.xmin || -1.0;
  24765. var zmin = options.zmin || -1.0;
  24766. var xmax = options.xmax || 1.0;
  24767. var zmax = options.zmax || 1.0;
  24768. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  24769. var precision = options.precision || { w: 1, h: 1 };
  24770. var indices = [];
  24771. var positions = [];
  24772. var normals = [];
  24773. var uvs = [];
  24774. var row, col, tileRow, tileCol;
  24775. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  24776. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  24777. precision.w = (precision.w < 1) ? 1 : precision.w;
  24778. precision.h = (precision.h < 1) ? 1 : precision.h;
  24779. var tileSize = {
  24780. 'w': (xmax - xmin) / subdivisions.w,
  24781. 'h': (zmax - zmin) / subdivisions.h
  24782. };
  24783. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  24784. // Indices
  24785. var base = positions.length / 3;
  24786. var rowLength = precision.w + 1;
  24787. for (row = 0; row < precision.h; row++) {
  24788. for (col = 0; col < precision.w; col++) {
  24789. var square = [
  24790. base + col + row * rowLength,
  24791. base + (col + 1) + row * rowLength,
  24792. base + (col + 1) + (row + 1) * rowLength,
  24793. base + col + (row + 1) * rowLength
  24794. ];
  24795. indices.push(square[1]);
  24796. indices.push(square[2]);
  24797. indices.push(square[3]);
  24798. indices.push(square[0]);
  24799. indices.push(square[1]);
  24800. indices.push(square[3]);
  24801. }
  24802. }
  24803. // Position, normals and uvs
  24804. var position = BABYLON.Vector3.Zero();
  24805. var normal = new BABYLON.Vector3(0, 1.0, 0);
  24806. for (row = 0; row <= precision.h; row++) {
  24807. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  24808. for (col = 0; col <= precision.w; col++) {
  24809. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  24810. position.y = 0;
  24811. positions.push(position.x, position.y, position.z);
  24812. normals.push(normal.x, normal.y, normal.z);
  24813. uvs.push(col / precision.w, row / precision.h);
  24814. }
  24815. }
  24816. }
  24817. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  24818. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  24819. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  24820. }
  24821. }
  24822. // Result
  24823. var vertexData = new VertexData();
  24824. vertexData.indices = indices;
  24825. vertexData.positions = positions;
  24826. vertexData.normals = normals;
  24827. vertexData.uvs = uvs;
  24828. return vertexData;
  24829. };
  24830. /**
  24831. * Creates the VertexData of the Ground designed from a heightmap.
  24832. */
  24833. VertexData.CreateGroundFromHeightMap = function (options) {
  24834. var indices = [];
  24835. var positions = [];
  24836. var normals = [];
  24837. var uvs = [];
  24838. var row, col;
  24839. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  24840. // Vertices
  24841. for (row = 0; row <= options.subdivisions; row++) {
  24842. for (col = 0; col <= options.subdivisions; col++) {
  24843. 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));
  24844. // Compute height
  24845. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  24846. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  24847. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  24848. var r = options.buffer[pos] / 255.0;
  24849. var g = options.buffer[pos + 1] / 255.0;
  24850. var b = options.buffer[pos + 2] / 255.0;
  24851. var gradient = r * filter.r + g * filter.g + b * filter.b;
  24852. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  24853. // Add vertex
  24854. positions.push(position.x, position.y, position.z);
  24855. normals.push(0, 0, 0);
  24856. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  24857. }
  24858. }
  24859. // Indices
  24860. for (row = 0; row < options.subdivisions; row++) {
  24861. for (col = 0; col < options.subdivisions; col++) {
  24862. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24863. indices.push(col + 1 + row * (options.subdivisions + 1));
  24864. indices.push(col + row * (options.subdivisions + 1));
  24865. indices.push(col + (row + 1) * (options.subdivisions + 1));
  24866. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  24867. indices.push(col + row * (options.subdivisions + 1));
  24868. }
  24869. }
  24870. // Normals
  24871. VertexData.ComputeNormals(positions, indices, normals);
  24872. // Result
  24873. var vertexData = new VertexData();
  24874. vertexData.indices = indices;
  24875. vertexData.positions = positions;
  24876. vertexData.normals = normals;
  24877. vertexData.uvs = uvs;
  24878. return vertexData;
  24879. };
  24880. /**
  24881. * Creates the VertexData of the Plane.
  24882. */
  24883. VertexData.CreatePlane = function (options) {
  24884. var indices = [];
  24885. var positions = [];
  24886. var normals = [];
  24887. var uvs = [];
  24888. var width = options.width || options.size || 1;
  24889. var height = options.height || options.size || 1;
  24890. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24891. // Vertices
  24892. var halfWidth = width / 2.0;
  24893. var halfHeight = height / 2.0;
  24894. positions.push(-halfWidth, -halfHeight, 0);
  24895. normals.push(0, 0, -1.0);
  24896. uvs.push(0.0, 0.0);
  24897. positions.push(halfWidth, -halfHeight, 0);
  24898. normals.push(0, 0, -1.0);
  24899. uvs.push(1.0, 0.0);
  24900. positions.push(halfWidth, halfHeight, 0);
  24901. normals.push(0, 0, -1.0);
  24902. uvs.push(1.0, 1.0);
  24903. positions.push(-halfWidth, halfHeight, 0);
  24904. normals.push(0, 0, -1.0);
  24905. uvs.push(0.0, 1.0);
  24906. // Indices
  24907. indices.push(0);
  24908. indices.push(1);
  24909. indices.push(2);
  24910. indices.push(0);
  24911. indices.push(2);
  24912. indices.push(3);
  24913. // Sides
  24914. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  24915. // Result
  24916. var vertexData = new VertexData();
  24917. vertexData.indices = indices;
  24918. vertexData.positions = positions;
  24919. vertexData.normals = normals;
  24920. vertexData.uvs = uvs;
  24921. return vertexData;
  24922. };
  24923. /**
  24924. * Creates the VertexData of the Disc or regular Polygon.
  24925. */
  24926. VertexData.CreateDisc = function (options) {
  24927. var positions = [];
  24928. var indices = [];
  24929. var normals = [];
  24930. var uvs = [];
  24931. var radius = options.radius || 0.5;
  24932. var tessellation = options.tessellation || 64;
  24933. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  24934. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24935. // positions and uvs
  24936. positions.push(0, 0, 0); // disc center first
  24937. uvs.push(0.5, 0.5);
  24938. var theta = Math.PI * 2 * arc;
  24939. var step = theta / tessellation;
  24940. for (var a = 0; a < theta; a += step) {
  24941. var x = Math.cos(a);
  24942. var y = Math.sin(a);
  24943. var u = (x + 1) / 2;
  24944. var v = (1 - y) / 2;
  24945. positions.push(radius * x, radius * y, 0);
  24946. uvs.push(u, v);
  24947. }
  24948. if (arc === 1) {
  24949. positions.push(positions[3], positions[4], positions[5]); // close the circle
  24950. uvs.push(uvs[2], uvs[3]);
  24951. }
  24952. //indices
  24953. var vertexNb = positions.length / 3;
  24954. for (var i = 1; i < vertexNb - 1; i++) {
  24955. indices.push(i + 1, 0, i);
  24956. }
  24957. // result
  24958. VertexData.ComputeNormals(positions, indices, normals);
  24959. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  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 IcoSphere.
  24969. */
  24970. VertexData.CreateIcoSphere = function (options) {
  24971. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  24972. var radius = options.radius || 1;
  24973. var flat = (options.flat === undefined) ? true : options.flat;
  24974. var subdivisions = options.subdivisions || 4;
  24975. var radiusX = options.radiusX || radius;
  24976. var radiusY = options.radiusY || radius;
  24977. var radiusZ = options.radiusZ || radius;
  24978. var t = (1 + Math.sqrt(5)) / 2;
  24979. // 12 vertex x,y,z
  24980. var ico_vertices = [
  24981. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  24982. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  24983. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  24984. ];
  24985. // index of 3 vertex makes a face of icopshere
  24986. var ico_indices = [
  24987. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  24988. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  24989. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  24990. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  24991. ];
  24992. // vertex for uv have aliased position, not for UV
  24993. var vertices_unalias_id = [
  24994. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  24995. // vertex alias
  24996. 0,
  24997. 2,
  24998. 3,
  24999. 3,
  25000. 3,
  25001. 4,
  25002. 7,
  25003. 8,
  25004. 9,
  25005. 9,
  25006. 10,
  25007. 11 // 23: B + 12
  25008. ];
  25009. // uv as integer step (not pixels !)
  25010. var ico_vertexuv = [
  25011. 5, 1, 3, 1, 6, 4, 0, 0,
  25012. 5, 3, 4, 2, 2, 2, 4, 0,
  25013. 2, 0, 1, 1, 6, 0, 6, 2,
  25014. // vertex alias (for same vertex on different faces)
  25015. 0, 4,
  25016. 3, 3,
  25017. 4, 4,
  25018. 3, 1,
  25019. 4, 2,
  25020. 4, 4,
  25021. 0, 2,
  25022. 1, 1,
  25023. 2, 2,
  25024. 3, 3,
  25025. 1, 3,
  25026. 2, 4 // 23: B + 12
  25027. ];
  25028. // Vertices[0, 1, ...9, A, B] : position on UV plane
  25029. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  25030. // First island of uv mapping
  25031. // v = 4h 3+ 2
  25032. // v = 3h 9+ 4
  25033. // v = 2h 9+ 5 B
  25034. // v = 1h 9 1 0
  25035. // v = 0h 3 8 7 A
  25036. // u = 0 1 2 3 4 5 6 *a
  25037. // Second island of uv mapping
  25038. // v = 4h 0+ B+ 4+
  25039. // v = 3h A+ 2+
  25040. // v = 2h 7+ 6 3+
  25041. // v = 1h 8+ 3+
  25042. // v = 0h
  25043. // u = 0 1 2 3 4 5 6 *a
  25044. // Face layout on texture UV mapping
  25045. // ============
  25046. // \ 4 /\ 16 / ======
  25047. // \ / \ / /\ 11 /
  25048. // \/ 7 \/ / \ /
  25049. // ======= / 10 \/
  25050. // /\ 17 /\ =======
  25051. // / \ / \ \ 15 /\
  25052. // / 8 \/ 12 \ \ / \
  25053. // ============ \/ 6 \
  25054. // \ 18 /\ ============
  25055. // \ / \ \ 5 /\ 0 /
  25056. // \/ 13 \ \ / \ /
  25057. // ======= \/ 1 \/
  25058. // =============
  25059. // /\ 19 /\ 2 /\
  25060. // / \ / \ / \
  25061. // / 14 \/ 9 \/ 3 \
  25062. // ===================
  25063. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  25064. var ustep = 138 / 1024;
  25065. var vstep = 239 / 1024;
  25066. var uoffset = 60 / 1024;
  25067. var voffset = 26 / 1024;
  25068. // Second island should have margin, not to touch the first island
  25069. // avoid any borderline artefact in pixel rounding
  25070. var island_u_offset = -40 / 1024;
  25071. var island_v_offset = +20 / 1024;
  25072. // face is either island 0 or 1 :
  25073. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  25074. var island = [
  25075. 0, 0, 0, 0, 1,
  25076. 0, 0, 1, 1, 0,
  25077. 0, 0, 1, 1, 0,
  25078. 0, 1, 1, 1, 0 // 15 - 19
  25079. ];
  25080. var indices = [];
  25081. var positions = [];
  25082. var normals = [];
  25083. var uvs = [];
  25084. var current_indice = 0;
  25085. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  25086. var face_vertex_pos = new Array(3);
  25087. var face_vertex_uv = new Array(3);
  25088. var v012;
  25089. for (v012 = 0; v012 < 3; v012++) {
  25090. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  25091. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  25092. }
  25093. // create all with normals
  25094. for (var face = 0; face < 20; face++) {
  25095. // 3 vertex per face
  25096. for (v012 = 0; v012 < 3; v012++) {
  25097. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  25098. var v_id = ico_indices[3 * face + v012];
  25099. // vertex have 3D position (x,y,z)
  25100. 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]);
  25101. // Normalize to get normal, then scale to radius
  25102. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  25103. // uv Coordinates from vertex ID
  25104. 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);
  25105. }
  25106. // Subdivide the face (interpolate pos, norm, uv)
  25107. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  25108. // - norm is linear interpolation of vertex corner normal
  25109. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  25110. // - uv is linear interpolation
  25111. //
  25112. // Topology is as below for sub-divide by 2
  25113. // vertex shown as v0,v1,v2
  25114. // interp index is i1 to progress in range [v0,v1[
  25115. // interp index is i2 to progress in range [v0,v2[
  25116. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  25117. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25118. //
  25119. //
  25120. // i2 v2
  25121. // ^ ^
  25122. // / / \
  25123. // / / \
  25124. // / / \
  25125. // / / (0,1) \
  25126. // / #---------\
  25127. // / / \ (0,0)'/ \
  25128. // / / \ / \
  25129. // / / \ / \
  25130. // / / (0,0) \ / (1,0) \
  25131. // / #---------#---------\
  25132. // v0 v1
  25133. //
  25134. // --------------------> i1
  25135. //
  25136. // interp of (i1,i2):
  25137. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  25138. // along i1 : lerp(x0,x1, i1/(S-i2))
  25139. //
  25140. // centroid of triangle is needed to get help normal computation
  25141. // (c1,c2) are used for centroid location
  25142. var interp_vertex = function (i1, i2, c1, c2) {
  25143. // vertex is interpolated from
  25144. // - face_vertex_pos[0..2]
  25145. // - face_vertex_uv[0..2]
  25146. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  25147. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  25148. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  25149. pos_interp.normalize();
  25150. var vertex_normal;
  25151. if (flat) {
  25152. // in flat mode, recalculate normal as face centroid normal
  25153. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  25154. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  25155. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  25156. }
  25157. else {
  25158. // in smooth mode, recalculate normal from each single vertex position
  25159. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  25160. }
  25161. // Vertex normal need correction due to X,Y,Z radius scaling
  25162. vertex_normal.x /= radiusX;
  25163. vertex_normal.y /= radiusY;
  25164. vertex_normal.z /= radiusZ;
  25165. vertex_normal.normalize();
  25166. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  25167. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  25168. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  25169. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  25170. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  25171. uvs.push(uv_interp.x, uv_interp.y);
  25172. // push each vertex has member of a face
  25173. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  25174. indices.push(current_indice);
  25175. current_indice++;
  25176. };
  25177. for (var i2 = 0; i2 < subdivisions; i2++) {
  25178. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  25179. // face : (i1,i2) for /\ :
  25180. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  25181. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25182. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25183. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  25184. if (i1 + i2 + 1 < subdivisions) {
  25185. // face : (i1,i2)' for \/ :
  25186. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  25187. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25188. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25189. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  25190. }
  25191. }
  25192. }
  25193. }
  25194. // Sides
  25195. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25196. // Result
  25197. var vertexData = new VertexData();
  25198. vertexData.indices = indices;
  25199. vertexData.positions = positions;
  25200. vertexData.normals = normals;
  25201. vertexData.uvs = uvs;
  25202. return vertexData;
  25203. };
  25204. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  25205. /**
  25206. * Creates the VertexData of the Polyhedron.
  25207. */
  25208. VertexData.CreatePolyhedron = function (options) {
  25209. // provided polyhedron types :
  25210. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  25211. // 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)
  25212. var polyhedra = [];
  25213. 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]] };
  25214. 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]] };
  25215. polyhedra[2] = {
  25216. 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]],
  25217. 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]]
  25218. };
  25219. polyhedra[3] = {
  25220. 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]],
  25221. 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]]
  25222. };
  25223. polyhedra[4] = {
  25224. 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]],
  25225. 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]]
  25226. };
  25227. 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]] };
  25228. 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]] };
  25229. 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]] };
  25230. 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]] };
  25231. 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]] };
  25232. 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]] };
  25233. 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]] };
  25234. 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]] };
  25235. 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]] };
  25236. polyhedra[14] = {
  25237. 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]],
  25238. 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]]
  25239. };
  25240. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  25241. var size = options.size;
  25242. var sizeX = options.sizeX || size || 1;
  25243. var sizeY = options.sizeY || size || 1;
  25244. var sizeZ = options.sizeZ || size || 1;
  25245. var data = options.custom || polyhedra[type];
  25246. var nbfaces = data.face.length;
  25247. var faceUV = options.faceUV || new Array(nbfaces);
  25248. var faceColors = options.faceColors;
  25249. var flat = (options.flat === undefined) ? true : options.flat;
  25250. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25251. var positions = [];
  25252. var indices = [];
  25253. var normals = [];
  25254. var uvs = [];
  25255. var colors = [];
  25256. var index = 0;
  25257. var faceIdx = 0; // face cursor in the array "indexes"
  25258. var indexes = [];
  25259. var i = 0;
  25260. var f = 0;
  25261. var u, v, ang, x, y, tmp;
  25262. // default face colors and UV if undefined
  25263. if (flat) {
  25264. for (f = 0; f < nbfaces; f++) {
  25265. if (faceColors && faceColors[f] === undefined) {
  25266. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  25267. }
  25268. if (faceUV && faceUV[f] === undefined) {
  25269. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  25270. }
  25271. }
  25272. }
  25273. if (!flat) {
  25274. for (i = 0; i < data.vertex.length; i++) {
  25275. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  25276. uvs.push(0, 0);
  25277. }
  25278. for (f = 0; f < nbfaces; f++) {
  25279. for (i = 0; i < data.face[f].length - 2; i++) {
  25280. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  25281. }
  25282. }
  25283. }
  25284. else {
  25285. for (f = 0; f < nbfaces; f++) {
  25286. var fl = data.face[f].length; // number of vertices of the current face
  25287. ang = 2 * Math.PI / fl;
  25288. x = 0.5 * Math.tan(ang / 2);
  25289. y = 0.5;
  25290. // positions, uvs, colors
  25291. for (i = 0; i < fl; i++) {
  25292. // positions
  25293. 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);
  25294. indexes.push(index);
  25295. index++;
  25296. // uvs
  25297. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  25298. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  25299. uvs.push(u, v);
  25300. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  25301. y = x * Math.sin(ang) + y * Math.cos(ang);
  25302. x = tmp;
  25303. // colors
  25304. if (faceColors) {
  25305. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  25306. }
  25307. }
  25308. // indices from indexes
  25309. for (i = 0; i < fl - 2; i++) {
  25310. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  25311. }
  25312. faceIdx += fl;
  25313. }
  25314. }
  25315. VertexData.ComputeNormals(positions, indices, normals);
  25316. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25317. var vertexData = new VertexData();
  25318. vertexData.positions = positions;
  25319. vertexData.indices = indices;
  25320. vertexData.normals = normals;
  25321. vertexData.uvs = uvs;
  25322. if (faceColors && flat) {
  25323. vertexData.colors = colors;
  25324. }
  25325. return vertexData;
  25326. };
  25327. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25328. /**
  25329. * Creates the VertexData of the Torus Knot.
  25330. */
  25331. VertexData.CreateTorusKnot = function (options) {
  25332. var indices = [];
  25333. var positions = [];
  25334. var normals = [];
  25335. var uvs = [];
  25336. var radius = options.radius || 2;
  25337. var tube = options.tube || 0.5;
  25338. var radialSegments = options.radialSegments || 32;
  25339. var tubularSegments = options.tubularSegments || 32;
  25340. var p = options.p || 2;
  25341. var q = options.q || 3;
  25342. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25343. // Helper
  25344. var getPos = function (angle) {
  25345. var cu = Math.cos(angle);
  25346. var su = Math.sin(angle);
  25347. var quOverP = q / p * angle;
  25348. var cs = Math.cos(quOverP);
  25349. var tx = radius * (2 + cs) * 0.5 * cu;
  25350. var ty = radius * (2 + cs) * su * 0.5;
  25351. var tz = radius * Math.sin(quOverP) * 0.5;
  25352. return new BABYLON.Vector3(tx, ty, tz);
  25353. };
  25354. // Vertices
  25355. var i;
  25356. var j;
  25357. for (i = 0; i <= radialSegments; i++) {
  25358. var modI = i % radialSegments;
  25359. var u = modI / radialSegments * 2 * p * Math.PI;
  25360. var p1 = getPos(u);
  25361. var p2 = getPos(u + 0.01);
  25362. var tang = p2.subtract(p1);
  25363. var n = p2.add(p1);
  25364. var bitan = BABYLON.Vector3.Cross(tang, n);
  25365. n = BABYLON.Vector3.Cross(bitan, tang);
  25366. bitan.normalize();
  25367. n.normalize();
  25368. for (j = 0; j < tubularSegments; j++) {
  25369. var modJ = j % tubularSegments;
  25370. var v = modJ / tubularSegments * 2 * Math.PI;
  25371. var cx = -tube * Math.cos(v);
  25372. var cy = tube * Math.sin(v);
  25373. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25374. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25375. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25376. uvs.push(i / radialSegments);
  25377. uvs.push(j / tubularSegments);
  25378. }
  25379. }
  25380. for (i = 0; i < radialSegments; i++) {
  25381. for (j = 0; j < tubularSegments; j++) {
  25382. var jNext = (j + 1) % tubularSegments;
  25383. var a = i * tubularSegments + j;
  25384. var b = (i + 1) * tubularSegments + j;
  25385. var c = (i + 1) * tubularSegments + jNext;
  25386. var d = i * tubularSegments + jNext;
  25387. indices.push(d);
  25388. indices.push(b);
  25389. indices.push(a);
  25390. indices.push(d);
  25391. indices.push(c);
  25392. indices.push(b);
  25393. }
  25394. }
  25395. // Normals
  25396. VertexData.ComputeNormals(positions, indices, normals);
  25397. // Sides
  25398. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25399. // Result
  25400. var vertexData = new VertexData();
  25401. vertexData.indices = indices;
  25402. vertexData.positions = positions;
  25403. vertexData.normals = normals;
  25404. vertexData.uvs = uvs;
  25405. return vertexData;
  25406. };
  25407. // Tools
  25408. /**
  25409. * @param {any} - positions (number[] or Float32Array)
  25410. * @param {any} - indices (number[] or Uint16Array)
  25411. * @param {any} - normals (number[] or Float32Array)
  25412. * options (optional) :
  25413. * facetPositions : optional array of facet positions (vector3)
  25414. * facetNormals : optional array of facet normals (vector3)
  25415. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  25416. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  25417. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  25418. * bbSize : optional bounding box size data, required for facetPartitioning computation
  25419. * bInfo : optional bounding info, required for facetPartitioning computation
  25420. */
  25421. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  25422. // temporary scalar variables
  25423. var index = 0; // facet index
  25424. var p1p2x = 0.0; // p1p2 vector x coordinate
  25425. var p1p2y = 0.0; // p1p2 vector y coordinate
  25426. var p1p2z = 0.0; // p1p2 vector z coordinate
  25427. var p3p2x = 0.0; // p3p2 vector x coordinate
  25428. var p3p2y = 0.0; // p3p2 vector y coordinate
  25429. var p3p2z = 0.0; // p3p2 vector z coordinate
  25430. var faceNormalx = 0.0; // facet normal x coordinate
  25431. var faceNormaly = 0.0; // facet normal y coordinate
  25432. var faceNormalz = 0.0; // facet normal z coordinate
  25433. var length = 0.0; // facet normal length before normalization
  25434. var v1x = 0; // vector1 x index in the positions array
  25435. var v1y = 0; // vector1 y index in the positions array
  25436. var v1z = 0; // vector1 z index in the positions array
  25437. var v2x = 0; // vector2 x index in the positions array
  25438. var v2y = 0; // vector2 y index in the positions array
  25439. var v2z = 0; // vector2 z index in the positions array
  25440. var v3x = 0; // vector3 x index in the positions array
  25441. var v3y = 0; // vector3 y index in the positions array
  25442. var v3z = 0; // vector3 z index in the positions array
  25443. var computeFacetNormals = false;
  25444. var computeFacetPositions = false;
  25445. var computeFacetPartitioning = false;
  25446. if (options) {
  25447. computeFacetNormals = (options.facetNormals) ? true : false;
  25448. computeFacetPositions = (options.facetPositions) ? true : false;
  25449. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  25450. }
  25451. // facetPartitioning reinit if needed
  25452. if (computeFacetPartitioning) {
  25453. var ox = 0; // X partitioning index for facet position
  25454. var oy = 0; // Y partinioning index for facet position
  25455. var oz = 0; // Z partinioning index for facet position
  25456. var b1x = 0; // X partitioning index for facet v1 vertex
  25457. var b1y = 0; // Y partitioning index for facet v1 vertex
  25458. var b1z = 0; // z partitioning index for facet v1 vertex
  25459. var b2x = 0; // X partitioning index for facet v2 vertex
  25460. var b2y = 0; // Y partitioning index for facet v2 vertex
  25461. var b2z = 0; // Z partitioning index for facet v2 vertex
  25462. var b3x = 0; // X partitioning index for facet v3 vertex
  25463. var b3y = 0; // Y partitioning index for facet v3 vertex
  25464. var b3z = 0; // Z partitioning index for facet v3 vertex
  25465. var block_idx_o = 0; // facet barycenter block index
  25466. var block_idx_v1 = 0; // v1 vertex block index
  25467. var block_idx_v2 = 0; // v2 vertex block index
  25468. var block_idx_v3 = 0; // v3 vertex block index
  25469. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  25470. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  25471. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  25472. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  25473. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  25474. var subSq = options.subDiv.max * options.subDiv.max;
  25475. options.facetPartitioning.length = 0;
  25476. }
  25477. // reset the normals
  25478. for (index = 0; index < positions.length; index++) {
  25479. normals[index] = 0.0;
  25480. }
  25481. // Loop : 1 indice triplet = 1 facet
  25482. var nbFaces = indices.length / 3;
  25483. for (index = 0; index < nbFaces; index++) {
  25484. // get the indexes of the coordinates of each vertex of the facet
  25485. v1x = indices[index * 3] * 3;
  25486. v1y = v1x + 1;
  25487. v1z = v1x + 2;
  25488. v2x = indices[index * 3 + 1] * 3;
  25489. v2y = v2x + 1;
  25490. v2z = v2x + 2;
  25491. v3x = indices[index * 3 + 2] * 3;
  25492. v3y = v3x + 1;
  25493. v3z = v3x + 2;
  25494. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  25495. p1p2y = positions[v1y] - positions[v2y];
  25496. p1p2z = positions[v1z] - positions[v2z];
  25497. p3p2x = positions[v3x] - positions[v2x];
  25498. p3p2y = positions[v3y] - positions[v2y];
  25499. p3p2z = positions[v3z] - positions[v2z];
  25500. // compute the face normal with the cross product
  25501. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  25502. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  25503. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  25504. // normalize this normal and store it in the array facetData
  25505. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25506. length = (length === 0) ? 1.0 : length;
  25507. faceNormalx /= length;
  25508. faceNormaly /= length;
  25509. faceNormalz /= length;
  25510. if (computeFacetNormals) {
  25511. options.facetNormals[index].x = faceNormalx;
  25512. options.facetNormals[index].y = faceNormaly;
  25513. options.facetNormals[index].z = faceNormalz;
  25514. }
  25515. if (computeFacetPositions) {
  25516. // compute and the facet barycenter coordinates in the array facetPositions
  25517. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  25518. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  25519. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  25520. }
  25521. if (computeFacetPartitioning) {
  25522. // store the facet indexes in arrays in the main facetPartitioning array :
  25523. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  25524. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25525. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25526. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25527. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25528. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25529. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25530. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25531. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25532. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25533. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  25534. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  25535. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  25536. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  25537. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  25538. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  25539. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  25540. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  25541. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  25542. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  25543. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  25544. // push each facet index in each block containing the vertex
  25545. options.facetPartitioning[block_idx_v1].push(index);
  25546. if (block_idx_v2 != block_idx_v1) {
  25547. options.facetPartitioning[block_idx_v2].push(index);
  25548. }
  25549. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  25550. options.facetPartitioning[block_idx_v3].push(index);
  25551. }
  25552. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  25553. options.facetPartitioning[block_idx_o].push(index);
  25554. }
  25555. }
  25556. // compute the normals anyway
  25557. normals[v1x] += faceNormalx; // accumulate all the normals per face
  25558. normals[v1y] += faceNormaly;
  25559. normals[v1z] += faceNormalz;
  25560. normals[v2x] += faceNormalx;
  25561. normals[v2y] += faceNormaly;
  25562. normals[v2z] += faceNormalz;
  25563. normals[v3x] += faceNormalx;
  25564. normals[v3y] += faceNormaly;
  25565. normals[v3z] += faceNormalz;
  25566. }
  25567. // last normalization of each normal
  25568. for (index = 0; index < normals.length / 3; index++) {
  25569. faceNormalx = normals[index * 3];
  25570. faceNormaly = normals[index * 3 + 1];
  25571. faceNormalz = normals[index * 3 + 2];
  25572. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  25573. length = (length === 0) ? 1.0 : length;
  25574. faceNormalx /= length;
  25575. faceNormaly /= length;
  25576. faceNormalz /= length;
  25577. normals[index * 3] = faceNormalx;
  25578. normals[index * 3 + 1] = faceNormaly;
  25579. normals[index * 3 + 2] = faceNormalz;
  25580. }
  25581. };
  25582. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25583. var li = indices.length;
  25584. var ln = normals.length;
  25585. var i;
  25586. var n;
  25587. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25588. switch (sideOrientation) {
  25589. case BABYLON.Mesh.FRONTSIDE:
  25590. // nothing changed
  25591. break;
  25592. case BABYLON.Mesh.BACKSIDE:
  25593. var tmp;
  25594. // indices
  25595. for (i = 0; i < li; i += 3) {
  25596. tmp = indices[i];
  25597. indices[i] = indices[i + 2];
  25598. indices[i + 2] = tmp;
  25599. }
  25600. // normals
  25601. for (n = 0; n < ln; n++) {
  25602. normals[n] = -normals[n];
  25603. }
  25604. break;
  25605. case BABYLON.Mesh.DOUBLESIDE:
  25606. // positions
  25607. var lp = positions.length;
  25608. var l = lp / 3;
  25609. for (var p = 0; p < lp; p++) {
  25610. positions[lp + p] = positions[p];
  25611. }
  25612. // indices
  25613. for (i = 0; i < li; i += 3) {
  25614. indices[i + li] = indices[i + 2] + l;
  25615. indices[i + 1 + li] = indices[i + 1] + l;
  25616. indices[i + 2 + li] = indices[i] + l;
  25617. }
  25618. // normals
  25619. for (n = 0; n < ln; n++) {
  25620. normals[ln + n] = -normals[n];
  25621. }
  25622. // uvs
  25623. var lu = uvs.length;
  25624. for (var u = 0; u < lu; u++) {
  25625. uvs[u + lu] = uvs[u];
  25626. }
  25627. break;
  25628. }
  25629. };
  25630. /**
  25631. * Creates a new VertexData from the imported parameters.
  25632. */
  25633. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  25634. var vertexData = new VertexData();
  25635. // positions
  25636. var positions = parsedVertexData.positions;
  25637. if (positions) {
  25638. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  25639. }
  25640. // normals
  25641. var normals = parsedVertexData.normals;
  25642. if (normals) {
  25643. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  25644. }
  25645. // tangents
  25646. var tangents = parsedVertexData.tangents;
  25647. if (tangents) {
  25648. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  25649. }
  25650. // uvs
  25651. var uvs = parsedVertexData.uvs;
  25652. if (uvs) {
  25653. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  25654. }
  25655. // uv2s
  25656. var uv2s = parsedVertexData.uv2s;
  25657. if (uv2s) {
  25658. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  25659. }
  25660. // uv3s
  25661. var uv3s = parsedVertexData.uv3s;
  25662. if (uv3s) {
  25663. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  25664. }
  25665. // uv4s
  25666. var uv4s = parsedVertexData.uv4s;
  25667. if (uv4s) {
  25668. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  25669. }
  25670. // uv5s
  25671. var uv5s = parsedVertexData.uv5s;
  25672. if (uv5s) {
  25673. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  25674. }
  25675. // uv6s
  25676. var uv6s = parsedVertexData.uv6s;
  25677. if (uv6s) {
  25678. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  25679. }
  25680. // colors
  25681. var colors = parsedVertexData.colors;
  25682. if (colors) {
  25683. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  25684. }
  25685. // matricesIndices
  25686. var matricesIndices = parsedVertexData.matricesIndices;
  25687. if (matricesIndices) {
  25688. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  25689. }
  25690. // matricesWeights
  25691. var matricesWeights = parsedVertexData.matricesWeights;
  25692. if (matricesWeights) {
  25693. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  25694. }
  25695. // indices
  25696. var indices = parsedVertexData.indices;
  25697. if (indices) {
  25698. vertexData.indices = indices;
  25699. }
  25700. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  25701. };
  25702. return VertexData;
  25703. }());
  25704. BABYLON.VertexData = VertexData;
  25705. })(BABYLON || (BABYLON = {}));
  25706. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  25707. var BABYLON;
  25708. (function (BABYLON) {
  25709. var Geometry = (function () {
  25710. function Geometry(id, scene, vertexData, updatable, mesh) {
  25711. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25712. this._totalVertices = 0;
  25713. this._isDisposed = false;
  25714. this.id = id;
  25715. this._engine = scene.getEngine();
  25716. this._meshes = [];
  25717. this._scene = scene;
  25718. //Init vertex buffer cache
  25719. this._vertexBuffers = {};
  25720. this._indices = [];
  25721. // vertexData
  25722. if (vertexData) {
  25723. this.setAllVerticesData(vertexData, updatable);
  25724. }
  25725. else {
  25726. this._totalVertices = 0;
  25727. this._indices = [];
  25728. }
  25729. if (this._engine.getCaps().vertexArrayObject) {
  25730. this._vertexArrayObjects = {};
  25731. }
  25732. // applyToMesh
  25733. if (mesh) {
  25734. if (mesh.getClassName() === "LinesMesh") {
  25735. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  25736. this.updateExtend();
  25737. }
  25738. this.applyToMesh(mesh);
  25739. mesh.computeWorldMatrix(true);
  25740. }
  25741. }
  25742. Object.defineProperty(Geometry.prototype, "boundingBias", {
  25743. /**
  25744. * 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
  25745. * @returns The Bias Vector
  25746. */
  25747. get: function () {
  25748. return this._boundingBias;
  25749. },
  25750. set: function (value) {
  25751. if (this._boundingBias && this._boundingBias.equals(value)) {
  25752. return;
  25753. }
  25754. this._boundingBias = value.clone();
  25755. this.updateBoundingInfo(true, null);
  25756. },
  25757. enumerable: true,
  25758. configurable: true
  25759. });
  25760. Object.defineProperty(Geometry.prototype, "extend", {
  25761. get: function () {
  25762. return this._extend;
  25763. },
  25764. enumerable: true,
  25765. configurable: true
  25766. });
  25767. Geometry.prototype.getScene = function () {
  25768. return this._scene;
  25769. };
  25770. Geometry.prototype.getEngine = function () {
  25771. return this._engine;
  25772. };
  25773. Geometry.prototype.isReady = function () {
  25774. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25775. };
  25776. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  25777. get: function () {
  25778. for (var index = 0; index < this._meshes.length; index++) {
  25779. if (!this._meshes[index].doNotSerialize) {
  25780. return false;
  25781. }
  25782. }
  25783. return true;
  25784. },
  25785. enumerable: true,
  25786. configurable: true
  25787. });
  25788. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25789. vertexData.applyToGeometry(this, updatable);
  25790. this.notifyUpdate();
  25791. };
  25792. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25793. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25794. this.setVerticesBuffer(buffer);
  25795. };
  25796. Geometry.prototype.removeVerticesData = function (kind) {
  25797. if (this._vertexBuffers[kind]) {
  25798. this._vertexBuffers[kind].dispose();
  25799. delete this._vertexBuffers[kind];
  25800. }
  25801. };
  25802. Geometry.prototype.setVerticesBuffer = function (buffer) {
  25803. var kind = buffer.getKind();
  25804. if (this._vertexBuffers[kind]) {
  25805. this._vertexBuffers[kind].dispose();
  25806. }
  25807. this._vertexBuffers[kind] = buffer;
  25808. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25809. var data = buffer.getData();
  25810. var stride = buffer.getStrideSize();
  25811. this._totalVertices = data.length / stride;
  25812. this.updateExtend(data, stride);
  25813. var meshes = this._meshes;
  25814. var numOfMeshes = meshes.length;
  25815. for (var index = 0; index < numOfMeshes; index++) {
  25816. var mesh = meshes[index];
  25817. mesh._resetPointsArrayCache();
  25818. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25819. mesh._createGlobalSubMesh();
  25820. mesh.computeWorldMatrix(true);
  25821. }
  25822. }
  25823. this.notifyUpdate(kind);
  25824. if (this._vertexArrayObjects) {
  25825. this._disposeVertexArrayObjects();
  25826. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  25827. }
  25828. };
  25829. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25830. var vertexBuffer = this.getVertexBuffer(kind);
  25831. if (!vertexBuffer) {
  25832. return;
  25833. }
  25834. vertexBuffer.updateDirectly(data, offset);
  25835. this.notifyUpdate(kind);
  25836. };
  25837. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25838. var vertexBuffer = this.getVertexBuffer(kind);
  25839. if (!vertexBuffer) {
  25840. return;
  25841. }
  25842. vertexBuffer.update(data);
  25843. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25844. var stride = vertexBuffer.getStrideSize();
  25845. this._totalVertices = data.length / stride;
  25846. this.updateBoundingInfo(updateExtends, data);
  25847. }
  25848. this.notifyUpdate(kind);
  25849. };
  25850. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  25851. if (updateExtends) {
  25852. this.updateExtend(data);
  25853. }
  25854. var meshes = this._meshes;
  25855. var numOfMeshes = meshes.length;
  25856. for (var index = 0; index < numOfMeshes; index++) {
  25857. var mesh = meshes[index];
  25858. mesh._resetPointsArrayCache();
  25859. if (updateExtends) {
  25860. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  25861. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25862. var subMesh = mesh.subMeshes[subIndex];
  25863. subMesh.refreshBoundingInfo();
  25864. }
  25865. }
  25866. }
  25867. };
  25868. Geometry.prototype._bind = function (effect, indexToBind) {
  25869. if (indexToBind === void 0) { indexToBind = undefined; }
  25870. if (indexToBind === undefined) {
  25871. indexToBind = this._indexBuffer;
  25872. }
  25873. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  25874. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  25875. return;
  25876. }
  25877. // Using VAO
  25878. if (!this._vertexArrayObjects[effect.key]) {
  25879. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  25880. }
  25881. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  25882. };
  25883. Geometry.prototype.getTotalVertices = function () {
  25884. if (!this.isReady()) {
  25885. return 0;
  25886. }
  25887. return this._totalVertices;
  25888. };
  25889. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  25890. var vertexBuffer = this.getVertexBuffer(kind);
  25891. if (!vertexBuffer) {
  25892. return null;
  25893. }
  25894. var orig = vertexBuffer.getData();
  25895. if (!copyWhenShared || this._meshes.length === 1) {
  25896. return orig;
  25897. }
  25898. else {
  25899. var len = orig.length;
  25900. var copy = [];
  25901. for (var i = 0; i < len; i++) {
  25902. copy.push(orig[i]);
  25903. }
  25904. return copy;
  25905. }
  25906. };
  25907. Geometry.prototype.getVertexBuffer = function (kind) {
  25908. if (!this.isReady()) {
  25909. return null;
  25910. }
  25911. return this._vertexBuffers[kind];
  25912. };
  25913. Geometry.prototype.getVertexBuffers = function () {
  25914. if (!this.isReady()) {
  25915. return null;
  25916. }
  25917. return this._vertexBuffers;
  25918. };
  25919. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25920. if (!this._vertexBuffers) {
  25921. if (this._delayInfo) {
  25922. return this._delayInfo.indexOf(kind) !== -1;
  25923. }
  25924. return false;
  25925. }
  25926. return this._vertexBuffers[kind] !== undefined;
  25927. };
  25928. Geometry.prototype.getVerticesDataKinds = function () {
  25929. var result = [];
  25930. var kind;
  25931. if (!this._vertexBuffers && this._delayInfo) {
  25932. for (kind in this._delayInfo) {
  25933. result.push(kind);
  25934. }
  25935. }
  25936. else {
  25937. for (kind in this._vertexBuffers) {
  25938. result.push(kind);
  25939. }
  25940. }
  25941. return result;
  25942. };
  25943. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25944. if (this._indexBuffer) {
  25945. this._engine._releaseBuffer(this._indexBuffer);
  25946. }
  25947. this._disposeVertexArrayObjects();
  25948. this._indices = indices;
  25949. if (this._meshes.length !== 0 && this._indices) {
  25950. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25951. }
  25952. if (totalVertices !== undefined) {
  25953. this._totalVertices = totalVertices;
  25954. }
  25955. var meshes = this._meshes;
  25956. var numOfMeshes = meshes.length;
  25957. for (var index = 0; index < numOfMeshes; index++) {
  25958. meshes[index]._createGlobalSubMesh();
  25959. }
  25960. this.notifyUpdate();
  25961. };
  25962. Geometry.prototype.getTotalIndices = function () {
  25963. if (!this.isReady()) {
  25964. return 0;
  25965. }
  25966. return this._indices.length;
  25967. };
  25968. Geometry.prototype.getIndices = function (copyWhenShared) {
  25969. if (!this.isReady()) {
  25970. return null;
  25971. }
  25972. var orig = this._indices;
  25973. if (!copyWhenShared || this._meshes.length === 1) {
  25974. return orig;
  25975. }
  25976. else {
  25977. var len = orig.length;
  25978. var copy = [];
  25979. for (var i = 0; i < len; i++) {
  25980. copy.push(orig[i]);
  25981. }
  25982. return copy;
  25983. }
  25984. };
  25985. Geometry.prototype.getIndexBuffer = function () {
  25986. if (!this.isReady()) {
  25987. return null;
  25988. }
  25989. return this._indexBuffer;
  25990. };
  25991. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  25992. if (!effect || !this._vertexArrayObjects) {
  25993. return;
  25994. }
  25995. if (this._vertexArrayObjects[effect.key]) {
  25996. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  25997. delete this._vertexArrayObjects[effect.key];
  25998. }
  25999. };
  26000. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  26001. var meshes = this._meshes;
  26002. var index = meshes.indexOf(mesh);
  26003. if (index === -1) {
  26004. return;
  26005. }
  26006. meshes.splice(index, 1);
  26007. mesh._geometry = null;
  26008. if (meshes.length === 0 && shouldDispose) {
  26009. this.dispose();
  26010. }
  26011. };
  26012. Geometry.prototype.applyToMesh = function (mesh) {
  26013. if (mesh._geometry === this) {
  26014. return;
  26015. }
  26016. var previousGeometry = mesh._geometry;
  26017. if (previousGeometry) {
  26018. previousGeometry.releaseForMesh(mesh);
  26019. }
  26020. var meshes = this._meshes;
  26021. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  26022. mesh._geometry = this;
  26023. this._scene.pushGeometry(this);
  26024. meshes.push(mesh);
  26025. if (this.isReady()) {
  26026. this._applyToMesh(mesh);
  26027. }
  26028. else {
  26029. mesh._boundingInfo = this._boundingInfo;
  26030. }
  26031. };
  26032. Geometry.prototype.updateExtend = function (data, stride) {
  26033. if (data === void 0) { data = null; }
  26034. if (!data) {
  26035. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  26036. }
  26037. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  26038. };
  26039. Geometry.prototype._applyToMesh = function (mesh) {
  26040. var numOfMeshes = this._meshes.length;
  26041. // vertexBuffers
  26042. for (var kind in this._vertexBuffers) {
  26043. if (numOfMeshes === 1) {
  26044. this._vertexBuffers[kind].create();
  26045. }
  26046. var buffer = this._vertexBuffers[kind].getBuffer();
  26047. if (buffer)
  26048. buffer.references = numOfMeshes;
  26049. if (kind === BABYLON.VertexBuffer.PositionKind) {
  26050. mesh._resetPointsArrayCache();
  26051. if (!this._extend) {
  26052. this.updateExtend(this._vertexBuffers[kind].getData());
  26053. }
  26054. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26055. mesh._createGlobalSubMesh();
  26056. //bounding info was just created again, world matrix should be applied again.
  26057. mesh._updateBoundingInfo();
  26058. }
  26059. }
  26060. // indexBuffer
  26061. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  26062. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  26063. }
  26064. if (this._indexBuffer) {
  26065. this._indexBuffer.references = numOfMeshes;
  26066. }
  26067. };
  26068. Geometry.prototype.notifyUpdate = function (kind) {
  26069. if (this.onGeometryUpdated) {
  26070. this.onGeometryUpdated(this, kind);
  26071. }
  26072. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  26073. var mesh = _a[_i];
  26074. mesh._markSubMeshesAsAttributesDirty();
  26075. }
  26076. };
  26077. Geometry.prototype.load = function (scene, onLoaded) {
  26078. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26079. return;
  26080. }
  26081. if (this.isReady()) {
  26082. if (onLoaded) {
  26083. onLoaded();
  26084. }
  26085. return;
  26086. }
  26087. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26088. this._queueLoad(scene, onLoaded);
  26089. };
  26090. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  26091. var _this = this;
  26092. scene._addPendingData(this);
  26093. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26094. _this._delayLoadingFunction(JSON.parse(data), _this);
  26095. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26096. _this._delayInfo = [];
  26097. scene._removePendingData(_this);
  26098. var meshes = _this._meshes;
  26099. var numOfMeshes = meshes.length;
  26100. for (var index = 0; index < numOfMeshes; index++) {
  26101. _this._applyToMesh(meshes[index]);
  26102. }
  26103. if (onLoaded) {
  26104. onLoaded();
  26105. }
  26106. }, function () { }, scene.database);
  26107. };
  26108. /**
  26109. * Invert the geometry to move from a right handed system to a left handed one.
  26110. */
  26111. Geometry.prototype.toLeftHanded = function () {
  26112. // Flip faces
  26113. var tIndices = this.getIndices(false);
  26114. if (tIndices != null && tIndices.length > 0) {
  26115. for (var i = 0; i < tIndices.length; i += 3) {
  26116. var tTemp = tIndices[i + 0];
  26117. tIndices[i + 0] = tIndices[i + 2];
  26118. tIndices[i + 2] = tTemp;
  26119. }
  26120. this.setIndices(tIndices);
  26121. }
  26122. // Negate position.z
  26123. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  26124. if (tPositions != null && tPositions.length > 0) {
  26125. for (var i = 0; i < tPositions.length; i += 3) {
  26126. tPositions[i + 2] = -tPositions[i + 2];
  26127. }
  26128. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  26129. }
  26130. // Negate normal.z
  26131. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  26132. if (tNormals != null && tNormals.length > 0) {
  26133. for (var i = 0; i < tNormals.length; i += 3) {
  26134. tNormals[i + 2] = -tNormals[i + 2];
  26135. }
  26136. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  26137. }
  26138. };
  26139. Geometry.prototype.isDisposed = function () {
  26140. return this._isDisposed;
  26141. };
  26142. Geometry.prototype._disposeVertexArrayObjects = function () {
  26143. if (this._vertexArrayObjects) {
  26144. for (var kind in this._vertexArrayObjects) {
  26145. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  26146. }
  26147. this._vertexArrayObjects = {};
  26148. }
  26149. };
  26150. Geometry.prototype.dispose = function () {
  26151. var meshes = this._meshes;
  26152. var numOfMeshes = meshes.length;
  26153. var index;
  26154. for (index = 0; index < numOfMeshes; index++) {
  26155. this.releaseForMesh(meshes[index]);
  26156. }
  26157. this._meshes = [];
  26158. this._disposeVertexArrayObjects();
  26159. for (var kind in this._vertexBuffers) {
  26160. this._vertexBuffers[kind].dispose();
  26161. }
  26162. this._vertexBuffers = {};
  26163. this._totalVertices = 0;
  26164. if (this._indexBuffer) {
  26165. this._engine._releaseBuffer(this._indexBuffer);
  26166. }
  26167. this._indexBuffer = null;
  26168. this._indices = [];
  26169. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26170. this.delayLoadingFile = null;
  26171. this._delayLoadingFunction = null;
  26172. this._delayInfo = [];
  26173. this._boundingInfo = null;
  26174. this._scene.removeGeometry(this);
  26175. this._isDisposed = true;
  26176. };
  26177. Geometry.prototype.copy = function (id) {
  26178. var vertexData = new BABYLON.VertexData();
  26179. vertexData.indices = [];
  26180. var indices = this.getIndices();
  26181. for (var index = 0; index < indices.length; index++) {
  26182. vertexData.indices.push(indices[index]);
  26183. }
  26184. var updatable = false;
  26185. var stopChecking = false;
  26186. var kind;
  26187. for (kind in this._vertexBuffers) {
  26188. // using slice() to make a copy of the array and not just reference it
  26189. var data = this.getVerticesData(kind);
  26190. if (data instanceof Float32Array) {
  26191. vertexData.set(new Float32Array(data), kind);
  26192. }
  26193. else {
  26194. vertexData.set(data.slice(0), kind);
  26195. }
  26196. if (!stopChecking) {
  26197. updatable = this.getVertexBuffer(kind).isUpdatable();
  26198. stopChecking = !updatable;
  26199. }
  26200. }
  26201. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  26202. geometry.delayLoadState = this.delayLoadState;
  26203. geometry.delayLoadingFile = this.delayLoadingFile;
  26204. geometry._delayLoadingFunction = this._delayLoadingFunction;
  26205. for (kind in this._delayInfo) {
  26206. geometry._delayInfo = geometry._delayInfo || [];
  26207. geometry._delayInfo.push(kind);
  26208. }
  26209. // Bounding info
  26210. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  26211. return geometry;
  26212. };
  26213. Geometry.prototype.serialize = function () {
  26214. var serializationObject = {};
  26215. serializationObject.id = this.id;
  26216. if (BABYLON.Tags.HasTags(this)) {
  26217. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26218. }
  26219. return serializationObject;
  26220. };
  26221. Geometry.prototype.serializeVerticeData = function () {
  26222. var serializationObject = this.serialize();
  26223. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26224. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26225. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  26226. serializationObject.positions._updatable = true;
  26227. }
  26228. }
  26229. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26230. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26231. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  26232. serializationObject.normals._updatable = true;
  26233. }
  26234. }
  26235. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26236. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26237. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  26238. serializationObject.uvs._updatable = true;
  26239. }
  26240. }
  26241. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26242. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  26243. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  26244. serializationObject.uv2s._updatable = true;
  26245. }
  26246. }
  26247. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26248. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  26249. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  26250. serializationObject.uv3s._updatable = true;
  26251. }
  26252. }
  26253. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26254. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  26255. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  26256. serializationObject.uv4s._updatable = true;
  26257. }
  26258. }
  26259. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26260. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  26261. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  26262. serializationObject.uv5s._updatable = true;
  26263. }
  26264. }
  26265. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26266. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  26267. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  26268. serializationObject.uv6s._updatable = true;
  26269. }
  26270. }
  26271. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26272. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26273. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  26274. serializationObject.colors._updatable = true;
  26275. }
  26276. }
  26277. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26278. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26279. serializationObject.matricesIndices._isExpanded = true;
  26280. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  26281. serializationObject.matricesIndices._updatable = true;
  26282. }
  26283. }
  26284. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26285. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26286. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  26287. serializationObject.matricesWeights._updatable = true;
  26288. }
  26289. }
  26290. serializationObject.indices = this.getIndices();
  26291. return serializationObject;
  26292. };
  26293. // Statics
  26294. Geometry.ExtractFromMesh = function (mesh, id) {
  26295. var geometry = mesh._geometry;
  26296. if (!geometry) {
  26297. return null;
  26298. }
  26299. return geometry.copy(id);
  26300. };
  26301. /**
  26302. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  26303. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  26304. * Be aware Math.random() could cause collisions, but:
  26305. * "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"
  26306. */
  26307. Geometry.RandomId = function () {
  26308. return BABYLON.Tools.RandomId();
  26309. };
  26310. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  26311. var scene = mesh.getScene();
  26312. // Geometry
  26313. var geometryId = parsedGeometry.geometryId;
  26314. if (geometryId) {
  26315. var geometry = scene.getGeometryByID(geometryId);
  26316. if (geometry) {
  26317. geometry.applyToMesh(mesh);
  26318. }
  26319. }
  26320. else if (parsedGeometry instanceof ArrayBuffer) {
  26321. var binaryInfo = mesh._binaryInfo;
  26322. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  26323. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  26324. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  26325. }
  26326. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  26327. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  26328. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  26329. }
  26330. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  26331. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  26332. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  26333. }
  26334. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  26335. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  26336. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  26337. }
  26338. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  26339. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  26340. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  26341. }
  26342. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  26343. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  26344. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  26345. }
  26346. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  26347. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  26348. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  26349. }
  26350. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  26351. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  26352. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  26353. }
  26354. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  26355. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  26356. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  26357. }
  26358. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  26359. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  26360. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  26361. }
  26362. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  26363. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  26364. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  26365. }
  26366. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  26367. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  26368. mesh.setIndices(indicesData);
  26369. }
  26370. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  26371. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  26372. mesh.subMeshes = [];
  26373. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  26374. var materialIndex = subMeshesData[(i * 5) + 0];
  26375. var verticesStart = subMeshesData[(i * 5) + 1];
  26376. var verticesCount = subMeshesData[(i * 5) + 2];
  26377. var indexStart = subMeshesData[(i * 5) + 3];
  26378. var indexCount = subMeshesData[(i * 5) + 4];
  26379. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  26380. }
  26381. }
  26382. }
  26383. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  26384. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  26385. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  26386. if (parsedGeometry.uvs) {
  26387. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  26388. }
  26389. if (parsedGeometry.uvs2) {
  26390. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  26391. }
  26392. if (parsedGeometry.uvs3) {
  26393. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  26394. }
  26395. if (parsedGeometry.uvs4) {
  26396. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  26397. }
  26398. if (parsedGeometry.uvs5) {
  26399. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  26400. }
  26401. if (parsedGeometry.uvs6) {
  26402. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  26403. }
  26404. if (parsedGeometry.colors) {
  26405. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  26406. }
  26407. if (parsedGeometry.matricesIndices) {
  26408. if (!parsedGeometry.matricesIndices._isExpanded) {
  26409. var floatIndices = [];
  26410. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  26411. var matricesIndex = parsedGeometry.matricesIndices[i];
  26412. floatIndices.push(matricesIndex & 0x000000FF);
  26413. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26414. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26415. floatIndices.push(matricesIndex >> 24);
  26416. }
  26417. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  26418. }
  26419. else {
  26420. delete parsedGeometry.matricesIndices._isExpanded;
  26421. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  26422. }
  26423. }
  26424. if (parsedGeometry.matricesIndicesExtra) {
  26425. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  26426. var floatIndices = [];
  26427. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  26428. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  26429. floatIndices.push(matricesIndex & 0x000000FF);
  26430. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  26431. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  26432. floatIndices.push(matricesIndex >> 24);
  26433. }
  26434. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  26435. }
  26436. else {
  26437. delete parsedGeometry.matricesIndices._isExpanded;
  26438. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  26439. }
  26440. }
  26441. if (parsedGeometry.matricesWeights) {
  26442. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  26443. }
  26444. if (parsedGeometry.matricesWeightsExtra) {
  26445. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  26446. }
  26447. mesh.setIndices(parsedGeometry.indices);
  26448. }
  26449. // SubMeshes
  26450. if (parsedGeometry.subMeshes) {
  26451. mesh.subMeshes = [];
  26452. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  26453. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  26454. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  26455. }
  26456. }
  26457. // Flat shading
  26458. if (mesh._shouldGenerateFlatShading) {
  26459. mesh.convertToFlatShadedMesh();
  26460. delete mesh._shouldGenerateFlatShading;
  26461. }
  26462. // Update
  26463. mesh.computeWorldMatrix(true);
  26464. // Octree
  26465. if (scene['_selectionOctree']) {
  26466. scene['_selectionOctree'].addMesh(mesh);
  26467. }
  26468. };
  26469. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  26470. if (scene.getGeometryByID(parsedVertexData.id)) {
  26471. return null; // null since geometry could be something else than a box...
  26472. }
  26473. var geometry = new Geometry(parsedVertexData.id, scene);
  26474. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  26475. if (parsedVertexData.delayLoadingFile) {
  26476. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26477. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  26478. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  26479. geometry._delayInfo = [];
  26480. if (parsedVertexData.hasUVs) {
  26481. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26482. }
  26483. if (parsedVertexData.hasUVs2) {
  26484. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26485. }
  26486. if (parsedVertexData.hasUVs3) {
  26487. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26488. }
  26489. if (parsedVertexData.hasUVs4) {
  26490. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26491. }
  26492. if (parsedVertexData.hasUVs5) {
  26493. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26494. }
  26495. if (parsedVertexData.hasUVs6) {
  26496. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26497. }
  26498. if (parsedVertexData.hasColors) {
  26499. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26500. }
  26501. if (parsedVertexData.hasMatricesIndices) {
  26502. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26503. }
  26504. if (parsedVertexData.hasMatricesWeights) {
  26505. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26506. }
  26507. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  26508. }
  26509. else {
  26510. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  26511. }
  26512. scene.pushGeometry(geometry, true);
  26513. return geometry;
  26514. };
  26515. return Geometry;
  26516. }());
  26517. BABYLON.Geometry = Geometry;
  26518. /////// Primitives //////////////////////////////////////////////
  26519. (function (Geometry) {
  26520. var Primitives;
  26521. (function (Primitives) {
  26522. /// Abstract class
  26523. var _Primitive = (function (_super) {
  26524. __extends(_Primitive, _super);
  26525. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  26526. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  26527. _this._canBeRegenerated = _canBeRegenerated;
  26528. _this._beingRegenerated = true;
  26529. _this.regenerate();
  26530. _this._beingRegenerated = false;
  26531. return _this;
  26532. }
  26533. _Primitive.prototype.canBeRegenerated = function () {
  26534. return this._canBeRegenerated;
  26535. };
  26536. _Primitive.prototype.regenerate = function () {
  26537. if (!this._canBeRegenerated) {
  26538. return;
  26539. }
  26540. this._beingRegenerated = true;
  26541. this.setAllVerticesData(this._regenerateVertexData(), false);
  26542. this._beingRegenerated = false;
  26543. };
  26544. _Primitive.prototype.asNewGeometry = function (id) {
  26545. return _super.prototype.copy.call(this, id);
  26546. };
  26547. // overrides
  26548. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  26549. if (!this._beingRegenerated) {
  26550. return;
  26551. }
  26552. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  26553. };
  26554. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  26555. if (!this._beingRegenerated) {
  26556. return;
  26557. }
  26558. _super.prototype.setVerticesData.call(this, kind, data, false);
  26559. };
  26560. // to override
  26561. // protected
  26562. _Primitive.prototype._regenerateVertexData = function () {
  26563. throw new Error("Abstract method");
  26564. };
  26565. _Primitive.prototype.copy = function (id) {
  26566. throw new Error("Must be overriden in sub-classes.");
  26567. };
  26568. _Primitive.prototype.serialize = function () {
  26569. var serializationObject = _super.prototype.serialize.call(this);
  26570. serializationObject.canBeRegenerated = this.canBeRegenerated();
  26571. return serializationObject;
  26572. };
  26573. return _Primitive;
  26574. }(Geometry));
  26575. Primitives._Primitive = _Primitive;
  26576. var Ribbon = (function (_super) {
  26577. __extends(Ribbon, _super);
  26578. // Members
  26579. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  26580. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26581. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26582. _this.pathArray = pathArray;
  26583. _this.closeArray = closeArray;
  26584. _this.closePath = closePath;
  26585. _this.offset = offset;
  26586. _this.side = side;
  26587. return _this;
  26588. }
  26589. Ribbon.prototype._regenerateVertexData = function () {
  26590. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  26591. };
  26592. Ribbon.prototype.copy = function (id) {
  26593. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  26594. };
  26595. return Ribbon;
  26596. }(_Primitive));
  26597. Primitives.Ribbon = Ribbon;
  26598. var Box = (function (_super) {
  26599. __extends(Box, _super);
  26600. // Members
  26601. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  26602. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26603. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26604. _this.size = size;
  26605. _this.side = side;
  26606. return _this;
  26607. }
  26608. Box.prototype._regenerateVertexData = function () {
  26609. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  26610. };
  26611. Box.prototype.copy = function (id) {
  26612. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26613. };
  26614. Box.prototype.serialize = function () {
  26615. var serializationObject = _super.prototype.serialize.call(this);
  26616. serializationObject.size = this.size;
  26617. return serializationObject;
  26618. };
  26619. Box.Parse = function (parsedBox, scene) {
  26620. if (scene.getGeometryByID(parsedBox.id)) {
  26621. return null; // null since geometry could be something else than a box...
  26622. }
  26623. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  26624. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  26625. scene.pushGeometry(box, true);
  26626. return box;
  26627. };
  26628. return Box;
  26629. }(_Primitive));
  26630. Primitives.Box = Box;
  26631. var Sphere = (function (_super) {
  26632. __extends(Sphere, _super);
  26633. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  26634. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26635. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26636. _this.segments = segments;
  26637. _this.diameter = diameter;
  26638. _this.side = side;
  26639. return _this;
  26640. }
  26641. Sphere.prototype._regenerateVertexData = function () {
  26642. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  26643. };
  26644. Sphere.prototype.copy = function (id) {
  26645. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  26646. };
  26647. Sphere.prototype.serialize = function () {
  26648. var serializationObject = _super.prototype.serialize.call(this);
  26649. serializationObject.segments = this.segments;
  26650. serializationObject.diameter = this.diameter;
  26651. return serializationObject;
  26652. };
  26653. Sphere.Parse = function (parsedSphere, scene) {
  26654. if (scene.getGeometryByID(parsedSphere.id)) {
  26655. return null; // null since geometry could be something else than a sphere...
  26656. }
  26657. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  26658. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  26659. scene.pushGeometry(sphere, true);
  26660. return sphere;
  26661. };
  26662. return Sphere;
  26663. }(_Primitive));
  26664. Primitives.Sphere = Sphere;
  26665. var Disc = (function (_super) {
  26666. __extends(Disc, _super);
  26667. // Members
  26668. function Disc(id, scene, radius, tessellation, 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.radius = radius;
  26672. _this.tessellation = tessellation;
  26673. _this.side = side;
  26674. return _this;
  26675. }
  26676. Disc.prototype._regenerateVertexData = function () {
  26677. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  26678. };
  26679. Disc.prototype.copy = function (id) {
  26680. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  26681. };
  26682. return Disc;
  26683. }(_Primitive));
  26684. Primitives.Disc = Disc;
  26685. var Cylinder = (function (_super) {
  26686. __extends(Cylinder, _super);
  26687. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  26688. if (subdivisions === void 0) { subdivisions = 1; }
  26689. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26690. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26691. _this.height = height;
  26692. _this.diameterTop = diameterTop;
  26693. _this.diameterBottom = diameterBottom;
  26694. _this.tessellation = tessellation;
  26695. _this.subdivisions = subdivisions;
  26696. _this.side = side;
  26697. return _this;
  26698. }
  26699. Cylinder.prototype._regenerateVertexData = function () {
  26700. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  26701. };
  26702. Cylinder.prototype.copy = function (id) {
  26703. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  26704. };
  26705. Cylinder.prototype.serialize = function () {
  26706. var serializationObject = _super.prototype.serialize.call(this);
  26707. serializationObject.height = this.height;
  26708. serializationObject.diameterTop = this.diameterTop;
  26709. serializationObject.diameterBottom = this.diameterBottom;
  26710. serializationObject.tessellation = this.tessellation;
  26711. return serializationObject;
  26712. };
  26713. Cylinder.Parse = function (parsedCylinder, scene) {
  26714. if (scene.getGeometryByID(parsedCylinder.id)) {
  26715. return null; // null since geometry could be something else than a cylinder...
  26716. }
  26717. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  26718. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  26719. scene.pushGeometry(cylinder, true);
  26720. return cylinder;
  26721. };
  26722. return Cylinder;
  26723. }(_Primitive));
  26724. Primitives.Cylinder = Cylinder;
  26725. var Torus = (function (_super) {
  26726. __extends(Torus, _super);
  26727. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  26728. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26729. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26730. _this.diameter = diameter;
  26731. _this.thickness = thickness;
  26732. _this.tessellation = tessellation;
  26733. _this.side = side;
  26734. return _this;
  26735. }
  26736. Torus.prototype._regenerateVertexData = function () {
  26737. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  26738. };
  26739. Torus.prototype.copy = function (id) {
  26740. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  26741. };
  26742. Torus.prototype.serialize = function () {
  26743. var serializationObject = _super.prototype.serialize.call(this);
  26744. serializationObject.diameter = this.diameter;
  26745. serializationObject.thickness = this.thickness;
  26746. serializationObject.tessellation = this.tessellation;
  26747. return serializationObject;
  26748. };
  26749. Torus.Parse = function (parsedTorus, scene) {
  26750. if (scene.getGeometryByID(parsedTorus.id)) {
  26751. return null; // null since geometry could be something else than a torus...
  26752. }
  26753. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  26754. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  26755. scene.pushGeometry(torus, true);
  26756. return torus;
  26757. };
  26758. return Torus;
  26759. }(_Primitive));
  26760. Primitives.Torus = Torus;
  26761. var Ground = (function (_super) {
  26762. __extends(Ground, _super);
  26763. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  26764. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26765. _this.width = width;
  26766. _this.height = height;
  26767. _this.subdivisions = subdivisions;
  26768. return _this;
  26769. }
  26770. Ground.prototype._regenerateVertexData = function () {
  26771. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  26772. };
  26773. Ground.prototype.copy = function (id) {
  26774. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  26775. };
  26776. Ground.prototype.serialize = function () {
  26777. var serializationObject = _super.prototype.serialize.call(this);
  26778. serializationObject.width = this.width;
  26779. serializationObject.height = this.height;
  26780. serializationObject.subdivisions = this.subdivisions;
  26781. return serializationObject;
  26782. };
  26783. Ground.Parse = function (parsedGround, scene) {
  26784. if (scene.getGeometryByID(parsedGround.id)) {
  26785. return null; // null since geometry could be something else than a ground...
  26786. }
  26787. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  26788. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  26789. scene.pushGeometry(ground, true);
  26790. return ground;
  26791. };
  26792. return Ground;
  26793. }(_Primitive));
  26794. Primitives.Ground = Ground;
  26795. var TiledGround = (function (_super) {
  26796. __extends(TiledGround, _super);
  26797. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  26798. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26799. _this.xmin = xmin;
  26800. _this.zmin = zmin;
  26801. _this.xmax = xmax;
  26802. _this.zmax = zmax;
  26803. _this.subdivisions = subdivisions;
  26804. _this.precision = precision;
  26805. return _this;
  26806. }
  26807. TiledGround.prototype._regenerateVertexData = function () {
  26808. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  26809. };
  26810. TiledGround.prototype.copy = function (id) {
  26811. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  26812. };
  26813. return TiledGround;
  26814. }(_Primitive));
  26815. Primitives.TiledGround = TiledGround;
  26816. var Plane = (function (_super) {
  26817. __extends(Plane, _super);
  26818. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  26819. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26820. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26821. _this.size = size;
  26822. _this.side = side;
  26823. return _this;
  26824. }
  26825. Plane.prototype._regenerateVertexData = function () {
  26826. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  26827. };
  26828. Plane.prototype.copy = function (id) {
  26829. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  26830. };
  26831. Plane.prototype.serialize = function () {
  26832. var serializationObject = _super.prototype.serialize.call(this);
  26833. serializationObject.size = this.size;
  26834. return serializationObject;
  26835. };
  26836. Plane.Parse = function (parsedPlane, scene) {
  26837. if (scene.getGeometryByID(parsedPlane.id)) {
  26838. return null; // null since geometry could be something else than a ground...
  26839. }
  26840. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  26841. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  26842. scene.pushGeometry(plane, true);
  26843. return plane;
  26844. };
  26845. return Plane;
  26846. }(_Primitive));
  26847. Primitives.Plane = Plane;
  26848. var TorusKnot = (function (_super) {
  26849. __extends(TorusKnot, _super);
  26850. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  26851. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  26852. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  26853. _this.radius = radius;
  26854. _this.tube = tube;
  26855. _this.radialSegments = radialSegments;
  26856. _this.tubularSegments = tubularSegments;
  26857. _this.p = p;
  26858. _this.q = q;
  26859. _this.side = side;
  26860. return _this;
  26861. }
  26862. TorusKnot.prototype._regenerateVertexData = function () {
  26863. 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 });
  26864. };
  26865. TorusKnot.prototype.copy = function (id) {
  26866. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  26867. };
  26868. TorusKnot.prototype.serialize = function () {
  26869. var serializationObject = _super.prototype.serialize.call(this);
  26870. serializationObject.radius = this.radius;
  26871. serializationObject.tube = this.tube;
  26872. serializationObject.radialSegments = this.radialSegments;
  26873. serializationObject.tubularSegments = this.tubularSegments;
  26874. serializationObject.p = this.p;
  26875. serializationObject.q = this.q;
  26876. return serializationObject;
  26877. };
  26878. ;
  26879. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  26880. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  26881. return null; // null since geometry could be something else than a ground...
  26882. }
  26883. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  26884. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  26885. scene.pushGeometry(torusKnot, true);
  26886. return torusKnot;
  26887. };
  26888. return TorusKnot;
  26889. }(_Primitive));
  26890. Primitives.TorusKnot = TorusKnot;
  26891. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  26892. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  26893. })(BABYLON || (BABYLON = {}));
  26894. //# sourceMappingURL=babylon.geometry.js.map
  26895. var BABYLON;
  26896. (function (BABYLON) {
  26897. var PostProcessManager = (function () {
  26898. function PostProcessManager(scene) {
  26899. this._vertexBuffers = {};
  26900. this._scene = scene;
  26901. }
  26902. PostProcessManager.prototype._prepareBuffers = function () {
  26903. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  26904. return;
  26905. }
  26906. // VBO
  26907. var vertices = [];
  26908. vertices.push(1, 1);
  26909. vertices.push(-1, 1);
  26910. vertices.push(-1, -1);
  26911. vertices.push(1, -1);
  26912. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  26913. // Indices
  26914. var indices = [];
  26915. indices.push(0);
  26916. indices.push(1);
  26917. indices.push(2);
  26918. indices.push(0);
  26919. indices.push(2);
  26920. indices.push(3);
  26921. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  26922. };
  26923. // Methods
  26924. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  26925. var postProcesses = this._scene.activeCamera._postProcesses;
  26926. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  26927. return false;
  26928. }
  26929. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  26930. return true;
  26931. };
  26932. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  26933. var engine = this._scene.getEngine();
  26934. for (var index = 0; index < postProcesses.length; index++) {
  26935. if (index < postProcesses.length - 1) {
  26936. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26937. }
  26938. else {
  26939. if (targetTexture) {
  26940. engine.bindFramebuffer(targetTexture);
  26941. }
  26942. else {
  26943. engine.restoreDefaultFramebuffer();
  26944. }
  26945. }
  26946. var pp = postProcesses[index];
  26947. var effect = pp.apply();
  26948. if (effect) {
  26949. pp.onBeforeRenderObservable.notifyObservers(effect);
  26950. // VBOs
  26951. this._prepareBuffers();
  26952. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26953. // Draw order
  26954. engine.draw(true, 0, 6);
  26955. pp.onAfterRenderObservable.notifyObservers(effect);
  26956. }
  26957. }
  26958. // Restore depth buffer
  26959. engine.setDepthBuffer(true);
  26960. engine.setDepthWrite(true);
  26961. };
  26962. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  26963. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  26964. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  26965. return;
  26966. }
  26967. var engine = this._scene.getEngine();
  26968. for (var index = 0, len = postProcesses.length; index < len; index++) {
  26969. if (index < len - 1) {
  26970. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  26971. }
  26972. else {
  26973. if (targetTexture) {
  26974. engine.bindFramebuffer(targetTexture, faceIndex);
  26975. }
  26976. else {
  26977. engine.restoreDefaultFramebuffer();
  26978. }
  26979. }
  26980. if (doNotPresent) {
  26981. break;
  26982. }
  26983. var pp = postProcesses[index];
  26984. var effect = pp.apply();
  26985. if (effect) {
  26986. pp.onBeforeRenderObservable.notifyObservers(effect);
  26987. // VBOs
  26988. this._prepareBuffers();
  26989. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26990. // Draw order
  26991. engine.draw(true, 0, 6);
  26992. pp.onAfterRenderObservable.notifyObservers(effect);
  26993. }
  26994. }
  26995. // Restore depth buffer
  26996. engine.setDepthBuffer(true);
  26997. engine.setDepthWrite(true);
  26998. };
  26999. PostProcessManager.prototype.dispose = function () {
  27000. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27001. if (buffer) {
  27002. buffer.dispose();
  27003. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27004. }
  27005. if (this._indexBuffer) {
  27006. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27007. this._indexBuffer = null;
  27008. }
  27009. };
  27010. return PostProcessManager;
  27011. }());
  27012. BABYLON.PostProcessManager = PostProcessManager;
  27013. })(BABYLON || (BABYLON = {}));
  27014. //# sourceMappingURL=babylon.postProcessManager.js.map
  27015. var BABYLON;
  27016. (function (BABYLON) {
  27017. var StandardMaterialDefines = (function (_super) {
  27018. __extends(StandardMaterialDefines, _super);
  27019. function StandardMaterialDefines() {
  27020. var _this = _super.call(this) || this;
  27021. _this.DIFFUSE = false;
  27022. _this.AMBIENT = false;
  27023. _this.OPACITY = false;
  27024. _this.OPACITYRGB = false;
  27025. _this.REFLECTION = false;
  27026. _this.EMISSIVE = false;
  27027. _this.SPECULAR = false;
  27028. _this.BUMP = false;
  27029. _this.PARALLAX = false;
  27030. _this.PARALLAXOCCLUSION = false;
  27031. _this.SPECULAROVERALPHA = false;
  27032. _this.CLIPPLANE = false;
  27033. _this.ALPHATEST = false;
  27034. _this.ALPHAFROMDIFFUSE = false;
  27035. _this.POINTSIZE = false;
  27036. _this.FOG = false;
  27037. _this.SPECULARTERM = false;
  27038. _this.DIFFUSEFRESNEL = false;
  27039. _this.OPACITYFRESNEL = false;
  27040. _this.REFLECTIONFRESNEL = false;
  27041. _this.REFRACTIONFRESNEL = false;
  27042. _this.EMISSIVEFRESNEL = false;
  27043. _this.FRESNEL = false;
  27044. _this.NORMAL = false;
  27045. _this.UV1 = false;
  27046. _this.UV2 = false;
  27047. _this.VERTEXCOLOR = false;
  27048. _this.VERTEXALPHA = false;
  27049. _this.NUM_BONE_INFLUENCERS = 0;
  27050. _this.BonesPerMesh = 0;
  27051. _this.INSTANCES = false;
  27052. _this.GLOSSINESS = false;
  27053. _this.ROUGHNESS = false;
  27054. _this.EMISSIVEASILLUMINATION = false;
  27055. _this.LINKEMISSIVEWITHDIFFUSE = false;
  27056. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  27057. _this.LIGHTMAP = false;
  27058. _this.USELIGHTMAPASSHADOWMAP = false;
  27059. _this.REFLECTIONMAP_3D = false;
  27060. _this.REFLECTIONMAP_SPHERICAL = false;
  27061. _this.REFLECTIONMAP_PLANAR = false;
  27062. _this.REFLECTIONMAP_CUBIC = false;
  27063. _this.REFLECTIONMAP_PROJECTION = false;
  27064. _this.REFLECTIONMAP_SKYBOX = false;
  27065. _this.REFLECTIONMAP_EXPLICIT = false;
  27066. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  27067. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  27068. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  27069. _this.INVERTCUBICMAP = false;
  27070. _this.LOGARITHMICDEPTH = false;
  27071. _this.REFRACTION = false;
  27072. _this.REFRACTIONMAP_3D = false;
  27073. _this.REFLECTIONOVERALPHA = false;
  27074. _this.INVERTNORMALMAPX = false;
  27075. _this.INVERTNORMALMAPY = false;
  27076. _this.TWOSIDEDLIGHTING = false;
  27077. _this.SHADOWFULLFLOAT = false;
  27078. _this.CAMERACOLORGRADING = false;
  27079. _this.CAMERACOLORCURVES = false;
  27080. _this.MORPHTARGETS = false;
  27081. _this.MORPHTARGETS_NORMAL = false;
  27082. _this.MORPHTARGETS_TANGENT = false;
  27083. _this.NUM_MORPH_INFLUENCERS = 0;
  27084. _this.rebuild();
  27085. return _this;
  27086. }
  27087. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  27088. var modes = [
  27089. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  27090. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  27091. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  27092. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  27093. ];
  27094. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  27095. var mode = modes_1[_i];
  27096. this[mode] = (mode === modeToEnable);
  27097. }
  27098. };
  27099. return StandardMaterialDefines;
  27100. }(BABYLON.MaterialDefines));
  27101. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  27102. var StandardMaterial = (function (_super) {
  27103. __extends(StandardMaterial, _super);
  27104. function StandardMaterial(name, scene) {
  27105. var _this = _super.call(this, name, scene) || this;
  27106. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  27107. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  27108. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  27109. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  27110. _this.specularPower = 64;
  27111. _this._useAlphaFromDiffuseTexture = false;
  27112. _this._useEmissiveAsIllumination = false;
  27113. _this._linkEmissiveWithDiffuse = false;
  27114. _this._useSpecularOverAlpha = false;
  27115. _this._useReflectionOverAlpha = false;
  27116. _this._disableLighting = false;
  27117. _this._useParallax = false;
  27118. _this._useParallaxOcclusion = false;
  27119. _this.parallaxScaleBias = 0.05;
  27120. _this._roughness = 0;
  27121. _this.indexOfRefraction = 0.98;
  27122. _this.invertRefractionY = true;
  27123. _this._useLightmapAsShadowmap = false;
  27124. _this._useReflectionFresnelFromSpecular = false;
  27125. _this._useGlossinessFromSpecularMapAlpha = false;
  27126. _this._maxSimultaneousLights = 4;
  27127. /**
  27128. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  27129. */
  27130. _this._invertNormalMapX = false;
  27131. /**
  27132. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  27133. */
  27134. _this._invertNormalMapY = false;
  27135. /**
  27136. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  27137. */
  27138. _this._twoSidedLighting = false;
  27139. /**
  27140. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  27141. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  27142. * 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;
  27143. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  27144. */
  27145. _this._cameraColorCurves = null;
  27146. _this._renderTargets = new BABYLON.SmartArray(16);
  27147. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  27148. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  27149. _this.getRenderTargetTextures = function () {
  27150. _this._renderTargets.reset();
  27151. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  27152. _this._renderTargets.push(_this._reflectionTexture);
  27153. }
  27154. if (_this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  27155. _this._renderTargets.push(_this._refractionTexture);
  27156. }
  27157. return _this._renderTargets;
  27158. };
  27159. return _this;
  27160. }
  27161. StandardMaterial.prototype.getClassName = function () {
  27162. return "StandardMaterial";
  27163. };
  27164. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  27165. get: function () {
  27166. return this._useLogarithmicDepth;
  27167. },
  27168. set: function (value) {
  27169. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  27170. this._markAllSubMeshesAsMiscDirty();
  27171. },
  27172. enumerable: true,
  27173. configurable: true
  27174. });
  27175. StandardMaterial.prototype.needAlphaBlending = function () {
  27176. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  27177. };
  27178. StandardMaterial.prototype.needAlphaTesting = function () {
  27179. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  27180. };
  27181. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  27182. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  27183. };
  27184. StandardMaterial.prototype.getAlphaTestTexture = function () {
  27185. return this._diffuseTexture;
  27186. };
  27187. /**
  27188. * Child classes can use it to update shaders
  27189. */
  27190. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  27191. if (this.isFrozen) {
  27192. if (this._wasPreviouslyReady && subMesh.effect) {
  27193. return true;
  27194. }
  27195. }
  27196. if (!subMesh._materialDefines) {
  27197. subMesh._materialDefines = new StandardMaterialDefines();
  27198. }
  27199. var scene = this.getScene();
  27200. var defines = subMesh._materialDefines;
  27201. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  27202. if (defines._renderId === scene.getRenderId()) {
  27203. return true;
  27204. }
  27205. }
  27206. var engine = scene.getEngine();
  27207. // Lights
  27208. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  27209. // Textures
  27210. if (defines._areTexturesDirty) {
  27211. defines._needUVs = false;
  27212. if (scene.texturesEnabled) {
  27213. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27214. if (!this._diffuseTexture.isReady()) {
  27215. return false;
  27216. }
  27217. else {
  27218. defines._needUVs = true;
  27219. defines.DIFFUSE = true;
  27220. }
  27221. }
  27222. else {
  27223. defines.DIFFUSE = false;
  27224. }
  27225. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27226. if (!this._ambientTexture.isReady()) {
  27227. return false;
  27228. }
  27229. else {
  27230. defines._needUVs = true;
  27231. defines.AMBIENT = true;
  27232. }
  27233. }
  27234. else {
  27235. defines.AMBIENT = false;
  27236. }
  27237. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27238. if (!this._opacityTexture.isReady()) {
  27239. return false;
  27240. }
  27241. else {
  27242. defines._needUVs = true;
  27243. defines.OPACITY = true;
  27244. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  27245. }
  27246. }
  27247. else {
  27248. defines.OPACITY = false;
  27249. }
  27250. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27251. if (!this._reflectionTexture.isReady()) {
  27252. return false;
  27253. }
  27254. else {
  27255. defines._needNormals = true;
  27256. defines.REFLECTION = true;
  27257. defines.ROUGHNESS = (this._roughness > 0);
  27258. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  27259. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  27260. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  27261. switch (this._reflectionTexture.coordinatesMode) {
  27262. case BABYLON.Texture.CUBIC_MODE:
  27263. case BABYLON.Texture.INVCUBIC_MODE:
  27264. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  27265. break;
  27266. case BABYLON.Texture.EXPLICIT_MODE:
  27267. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  27268. break;
  27269. case BABYLON.Texture.PLANAR_MODE:
  27270. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  27271. break;
  27272. case BABYLON.Texture.PROJECTION_MODE:
  27273. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  27274. break;
  27275. case BABYLON.Texture.SKYBOX_MODE:
  27276. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  27277. break;
  27278. case BABYLON.Texture.SPHERICAL_MODE:
  27279. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  27280. break;
  27281. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  27282. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  27283. break;
  27284. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  27285. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  27286. break;
  27287. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  27288. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  27289. break;
  27290. }
  27291. }
  27292. }
  27293. else {
  27294. defines.REFLECTION = false;
  27295. }
  27296. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27297. if (!this._emissiveTexture.isReady()) {
  27298. return false;
  27299. }
  27300. else {
  27301. defines._needUVs = true;
  27302. defines.EMISSIVE = true;
  27303. }
  27304. }
  27305. else {
  27306. defines.EMISSIVE = false;
  27307. }
  27308. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27309. if (!this._lightmapTexture.isReady()) {
  27310. return false;
  27311. }
  27312. else {
  27313. defines._needUVs = true;
  27314. defines.LIGHTMAP = true;
  27315. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  27316. }
  27317. }
  27318. else {
  27319. defines.LIGHTMAP = false;
  27320. }
  27321. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27322. if (!this._specularTexture.isReady()) {
  27323. return false;
  27324. }
  27325. else {
  27326. defines._needUVs = true;
  27327. defines.SPECULAR = true;
  27328. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  27329. }
  27330. }
  27331. else {
  27332. defines.SPECULAR = false;
  27333. }
  27334. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  27335. if (!this._bumpTexture.isReady()) {
  27336. return false;
  27337. }
  27338. else {
  27339. defines._needUVs = true;
  27340. defines.BUMP = true;
  27341. defines.INVERTNORMALMAPX = this.invertNormalMapX;
  27342. defines.INVERTNORMALMAPY = this.invertNormalMapY;
  27343. defines.PARALLAX = this._useParallax;
  27344. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  27345. }
  27346. }
  27347. else {
  27348. defines.BUMP = false;
  27349. }
  27350. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27351. if (!this._refractionTexture.isReady()) {
  27352. return false;
  27353. }
  27354. else {
  27355. defines._needUVs = true;
  27356. defines.REFRACTION = true;
  27357. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  27358. }
  27359. }
  27360. else {
  27361. defines.REFRACTION = false;
  27362. }
  27363. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27364. if (!this._cameraColorGradingTexture.isReady()) {
  27365. return false;
  27366. }
  27367. else {
  27368. defines.CAMERACOLORGRADING = true;
  27369. }
  27370. }
  27371. else {
  27372. defines.CAMERACOLORGRADING = false;
  27373. }
  27374. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  27375. }
  27376. else {
  27377. defines.DIFFUSE = false;
  27378. defines.AMBIENT = false;
  27379. defines.OPACITY = false;
  27380. defines.REFLECTION = false;
  27381. defines.EMISSIVE = false;
  27382. defines.LIGHTMAP = false;
  27383. defines.BUMP = false;
  27384. defines.REFRACTION = false;
  27385. defines.CAMERACOLORGRADING = false;
  27386. }
  27387. defines.CAMERACOLORCURVES = (this._cameraColorCurves !== undefined && this._cameraColorCurves !== null);
  27388. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  27389. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  27390. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  27391. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  27392. }
  27393. if (defines._areFresnelDirty) {
  27394. if (StandardMaterial.FresnelEnabled) {
  27395. // Fresnel
  27396. if (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled ||
  27397. this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled ||
  27398. this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled ||
  27399. this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled ||
  27400. this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled) {
  27401. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  27402. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  27403. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  27404. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  27405. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  27406. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  27407. defines._needNormals = true;
  27408. defines.FRESNEL = true;
  27409. }
  27410. }
  27411. else {
  27412. defines.FRESNEL = false;
  27413. }
  27414. }
  27415. // Misc.
  27416. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  27417. // Attribs
  27418. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  27419. // Values that need to be evaluated on every frame
  27420. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  27421. if (scene._mirroredCameraPosition && defines.BUMP) {
  27422. defines.INVERTNORMALMAPX = !this.invertNormalMapX;
  27423. defines.INVERTNORMALMAPY = !this.invertNormalMapY;
  27424. defines.markAsUnprocessed();
  27425. }
  27426. // Get correct effect
  27427. if (defines.isDirty) {
  27428. defines.markAsProcessed();
  27429. scene.resetCachedMaterial();
  27430. // Fallbacks
  27431. var fallbacks = new BABYLON.EffectFallbacks();
  27432. if (defines.REFLECTION) {
  27433. fallbacks.addFallback(0, "REFLECTION");
  27434. }
  27435. if (defines.SPECULAR) {
  27436. fallbacks.addFallback(0, "SPECULAR");
  27437. }
  27438. if (defines.BUMP) {
  27439. fallbacks.addFallback(0, "BUMP");
  27440. }
  27441. if (defines.PARALLAX) {
  27442. fallbacks.addFallback(1, "PARALLAX");
  27443. }
  27444. if (defines.PARALLAXOCCLUSION) {
  27445. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  27446. }
  27447. if (defines.SPECULAROVERALPHA) {
  27448. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  27449. }
  27450. if (defines.FOG) {
  27451. fallbacks.addFallback(1, "FOG");
  27452. }
  27453. if (defines.POINTSIZE) {
  27454. fallbacks.addFallback(0, "POINTSIZE");
  27455. }
  27456. if (defines.LOGARITHMICDEPTH) {
  27457. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  27458. }
  27459. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  27460. if (defines.SPECULARTERM) {
  27461. fallbacks.addFallback(0, "SPECULARTERM");
  27462. }
  27463. if (defines.DIFFUSEFRESNEL) {
  27464. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  27465. }
  27466. if (defines.OPACITYFRESNEL) {
  27467. fallbacks.addFallback(2, "OPACITYFRESNEL");
  27468. }
  27469. if (defines.REFLECTIONFRESNEL) {
  27470. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  27471. }
  27472. if (defines.EMISSIVEFRESNEL) {
  27473. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  27474. }
  27475. if (defines.FRESNEL) {
  27476. fallbacks.addFallback(4, "FRESNEL");
  27477. }
  27478. //Attributes
  27479. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27480. if (defines.NORMAL) {
  27481. attribs.push(BABYLON.VertexBuffer.NormalKind);
  27482. }
  27483. if (defines.UV1) {
  27484. attribs.push(BABYLON.VertexBuffer.UVKind);
  27485. }
  27486. if (defines.UV2) {
  27487. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27488. }
  27489. if (defines.VERTEXCOLOR) {
  27490. attribs.push(BABYLON.VertexBuffer.ColorKind);
  27491. }
  27492. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  27493. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  27494. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  27495. var shaderName = "default";
  27496. if (this.customShaderNameResolve) {
  27497. shaderName = this.customShaderNameResolve(shaderName);
  27498. }
  27499. var join = defines.toString();
  27500. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  27501. "vFogInfos", "vFogColor", "pointSize",
  27502. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  27503. "mBones",
  27504. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  27505. "depthValues",
  27506. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  27507. "logarithmicDepthConstant"
  27508. ];
  27509. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  27510. var uniformBuffers = ["Material", "Scene"];
  27511. if (defines.CAMERACOLORCURVES) {
  27512. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  27513. }
  27514. if (defines.CAMERACOLORGRADING) {
  27515. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  27516. }
  27517. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  27518. uniformsNames: uniforms,
  27519. uniformBuffersNames: uniformBuffers,
  27520. samplers: samplers,
  27521. defines: defines,
  27522. maxSimultaneousLights: this._maxSimultaneousLights
  27523. });
  27524. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  27525. attributes: attribs,
  27526. uniformsNames: uniforms,
  27527. uniformBuffersNames: uniformBuffers,
  27528. samplers: samplers,
  27529. defines: join,
  27530. fallbacks: fallbacks,
  27531. onCompiled: this.onCompiled,
  27532. onError: this.onError,
  27533. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  27534. }, engine), defines);
  27535. this.buildUniformLayout();
  27536. }
  27537. if (!subMesh.effect.isReady()) {
  27538. return false;
  27539. }
  27540. defines._renderId = scene.getRenderId();
  27541. this._wasPreviouslyReady = true;
  27542. return true;
  27543. };
  27544. StandardMaterial.prototype.buildUniformLayout = function () {
  27545. // Order is important !
  27546. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  27547. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  27548. this._uniformBuffer.addUniform("opacityParts", 4);
  27549. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  27550. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  27551. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  27552. this._uniformBuffer.addUniform("refractionRightColor", 4);
  27553. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  27554. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  27555. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  27556. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  27557. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  27558. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  27559. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  27560. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  27561. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  27562. this._uniformBuffer.addUniform("vBumpInfos", 3);
  27563. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  27564. this._uniformBuffer.addUniform("ambientMatrix", 16);
  27565. this._uniformBuffer.addUniform("opacityMatrix", 16);
  27566. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  27567. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  27568. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  27569. this._uniformBuffer.addUniform("specularMatrix", 16);
  27570. this._uniformBuffer.addUniform("bumpMatrix", 16);
  27571. this._uniformBuffer.addUniform("refractionMatrix", 16);
  27572. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  27573. this._uniformBuffer.addUniform("vSpecularColor", 4);
  27574. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  27575. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  27576. this._uniformBuffer.addUniform("pointSize", 1);
  27577. this._uniformBuffer.create();
  27578. };
  27579. StandardMaterial.prototype.unbind = function () {
  27580. if (this._activeEffect) {
  27581. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  27582. this._activeEffect.setTexture("reflection2DSampler", null);
  27583. }
  27584. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  27585. this._activeEffect.setTexture("refraction2DSampler", null);
  27586. }
  27587. }
  27588. _super.prototype.unbind.call(this);
  27589. };
  27590. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  27591. var scene = this.getScene();
  27592. var defines = subMesh._materialDefines;
  27593. if (!defines) {
  27594. return;
  27595. }
  27596. var effect = subMesh.effect;
  27597. this._activeEffect = effect;
  27598. // Matrices
  27599. this.bindOnlyWorldMatrix(world);
  27600. // Bones
  27601. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  27602. if (this._mustRebind(scene, effect)) {
  27603. this._uniformBuffer.bindToEffect(effect, "Material");
  27604. this.bindViewProjection(effect);
  27605. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  27606. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  27607. // Fresnel
  27608. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  27609. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  27610. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  27611. }
  27612. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  27613. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  27614. }
  27615. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27616. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  27617. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  27618. }
  27619. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  27620. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  27621. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  27622. }
  27623. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  27624. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  27625. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  27626. }
  27627. }
  27628. // Textures
  27629. if (scene.texturesEnabled) {
  27630. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27631. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  27632. this._uniformBuffer.updateMatrix("diffuseMatrix", this._diffuseTexture.getTextureMatrix());
  27633. }
  27634. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27635. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  27636. this._uniformBuffer.updateMatrix("ambientMatrix", this._ambientTexture.getTextureMatrix());
  27637. }
  27638. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27639. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  27640. this._uniformBuffer.updateMatrix("opacityMatrix", this._opacityTexture.getTextureMatrix());
  27641. }
  27642. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27643. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  27644. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  27645. }
  27646. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27647. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  27648. this._uniformBuffer.updateMatrix("emissiveMatrix", this._emissiveTexture.getTextureMatrix());
  27649. }
  27650. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27651. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  27652. this._uniformBuffer.updateMatrix("lightmapMatrix", this._lightmapTexture.getTextureMatrix());
  27653. }
  27654. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27655. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  27656. this._uniformBuffer.updateMatrix("specularMatrix", this._specularTexture.getTextureMatrix());
  27657. }
  27658. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  27659. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  27660. this._uniformBuffer.updateMatrix("bumpMatrix", this._bumpTexture.getTextureMatrix());
  27661. }
  27662. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27663. var depth = 1.0;
  27664. if (!this._refractionTexture.isCube) {
  27665. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  27666. if (this._refractionTexture.depth) {
  27667. depth = this._refractionTexture.depth;
  27668. }
  27669. }
  27670. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  27671. }
  27672. }
  27673. // Point size
  27674. if (this.pointsCloud) {
  27675. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  27676. }
  27677. if (defines.SPECULARTERM) {
  27678. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  27679. }
  27680. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  27681. // Diffuse
  27682. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  27683. }
  27684. // Textures
  27685. if (scene.texturesEnabled) {
  27686. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27687. effect.setTexture("diffuseSampler", this._diffuseTexture);
  27688. }
  27689. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27690. effect.setTexture("ambientSampler", this._ambientTexture);
  27691. }
  27692. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27693. effect.setTexture("opacitySampler", this._opacityTexture);
  27694. }
  27695. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27696. if (this._reflectionTexture.isCube) {
  27697. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  27698. }
  27699. else {
  27700. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  27701. }
  27702. }
  27703. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27704. effect.setTexture("emissiveSampler", this._emissiveTexture);
  27705. }
  27706. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27707. effect.setTexture("lightmapSampler", this._lightmapTexture);
  27708. }
  27709. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27710. effect.setTexture("specularSampler", this._specularTexture);
  27711. }
  27712. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  27713. effect.setTexture("bumpSampler", this._bumpTexture);
  27714. }
  27715. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27716. var depth = 1.0;
  27717. if (this._refractionTexture.isCube) {
  27718. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  27719. }
  27720. else {
  27721. effect.setTexture("refraction2DSampler", this._refractionTexture);
  27722. }
  27723. }
  27724. if (this._cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27725. BABYLON.ColorGradingTexture.Bind(this._cameraColorGradingTexture, effect);
  27726. }
  27727. }
  27728. // Clip plane
  27729. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  27730. // Colors
  27731. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  27732. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  27733. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  27734. }
  27735. if (this._mustRebind(scene, effect) || !this.isFrozen) {
  27736. // Lights
  27737. if (scene.lightsEnabled && !this._disableLighting) {
  27738. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  27739. }
  27740. // View
  27741. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  27742. this.bindView(effect);
  27743. }
  27744. // Fog
  27745. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  27746. // Morph targets
  27747. if (defines.NUM_MORPH_INFLUENCERS) {
  27748. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  27749. }
  27750. // Log. depth
  27751. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  27752. // Color Curves
  27753. if (this._cameraColorCurves) {
  27754. BABYLON.ColorCurves.Bind(this._cameraColorCurves, effect);
  27755. }
  27756. }
  27757. this._uniformBuffer.update();
  27758. this._afterBind(mesh, this._activeEffect);
  27759. };
  27760. StandardMaterial.prototype.getAnimatables = function () {
  27761. var results = [];
  27762. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  27763. results.push(this._diffuseTexture);
  27764. }
  27765. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  27766. results.push(this._ambientTexture);
  27767. }
  27768. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  27769. results.push(this._opacityTexture);
  27770. }
  27771. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  27772. results.push(this._reflectionTexture);
  27773. }
  27774. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  27775. results.push(this._emissiveTexture);
  27776. }
  27777. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  27778. results.push(this._specularTexture);
  27779. }
  27780. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  27781. results.push(this._bumpTexture);
  27782. }
  27783. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  27784. results.push(this._lightmapTexture);
  27785. }
  27786. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  27787. results.push(this._refractionTexture);
  27788. }
  27789. if (this._cameraColorGradingTexture && this._cameraColorGradingTexture.animations && this._cameraColorGradingTexture.animations.length > 0) {
  27790. results.push(this._cameraColorGradingTexture);
  27791. }
  27792. return results;
  27793. };
  27794. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27795. if (forceDisposeTextures) {
  27796. if (this._diffuseTexture) {
  27797. this._diffuseTexture.dispose();
  27798. }
  27799. if (this._ambientTexture) {
  27800. this._ambientTexture.dispose();
  27801. }
  27802. if (this._opacityTexture) {
  27803. this._opacityTexture.dispose();
  27804. }
  27805. if (this._reflectionTexture) {
  27806. this._reflectionTexture.dispose();
  27807. }
  27808. if (this._emissiveTexture) {
  27809. this._emissiveTexture.dispose();
  27810. }
  27811. if (this._specularTexture) {
  27812. this._specularTexture.dispose();
  27813. }
  27814. if (this._bumpTexture) {
  27815. this._bumpTexture.dispose();
  27816. }
  27817. if (this._lightmapTexture) {
  27818. this._lightmapTexture.dispose();
  27819. }
  27820. if (this._refractionTexture) {
  27821. this._refractionTexture.dispose();
  27822. }
  27823. if (this._cameraColorGradingTexture) {
  27824. this._cameraColorGradingTexture.dispose();
  27825. }
  27826. }
  27827. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  27828. };
  27829. StandardMaterial.prototype.clone = function (name) {
  27830. var _this = this;
  27831. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  27832. result.name = name;
  27833. result.id = name;
  27834. return result;
  27835. };
  27836. StandardMaterial.prototype.serialize = function () {
  27837. return BABYLON.SerializationHelper.Serialize(this);
  27838. };
  27839. // Statics
  27840. StandardMaterial.Parse = function (source, scene, rootUrl) {
  27841. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  27842. };
  27843. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  27844. get: function () {
  27845. return StandardMaterial._DiffuseTextureEnabled;
  27846. },
  27847. set: function (value) {
  27848. if (StandardMaterial._DiffuseTextureEnabled === value) {
  27849. return;
  27850. }
  27851. StandardMaterial._DiffuseTextureEnabled = value;
  27852. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27853. },
  27854. enumerable: true,
  27855. configurable: true
  27856. });
  27857. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  27858. get: function () {
  27859. return StandardMaterial._AmbientTextureEnabled;
  27860. },
  27861. set: function (value) {
  27862. if (StandardMaterial._AmbientTextureEnabled === value) {
  27863. return;
  27864. }
  27865. StandardMaterial._AmbientTextureEnabled = value;
  27866. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27867. },
  27868. enumerable: true,
  27869. configurable: true
  27870. });
  27871. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  27872. get: function () {
  27873. return StandardMaterial._OpacityTextureEnabled;
  27874. },
  27875. set: function (value) {
  27876. if (StandardMaterial._OpacityTextureEnabled === value) {
  27877. return;
  27878. }
  27879. StandardMaterial._OpacityTextureEnabled = value;
  27880. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27881. },
  27882. enumerable: true,
  27883. configurable: true
  27884. });
  27885. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  27886. get: function () {
  27887. return StandardMaterial._ReflectionTextureEnabled;
  27888. },
  27889. set: function (value) {
  27890. if (StandardMaterial._ReflectionTextureEnabled === value) {
  27891. return;
  27892. }
  27893. StandardMaterial._ReflectionTextureEnabled = value;
  27894. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27895. },
  27896. enumerable: true,
  27897. configurable: true
  27898. });
  27899. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  27900. get: function () {
  27901. return StandardMaterial._EmissiveTextureEnabled;
  27902. },
  27903. set: function (value) {
  27904. if (StandardMaterial._EmissiveTextureEnabled === value) {
  27905. return;
  27906. }
  27907. StandardMaterial._EmissiveTextureEnabled = value;
  27908. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27909. },
  27910. enumerable: true,
  27911. configurable: true
  27912. });
  27913. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  27914. get: function () {
  27915. return StandardMaterial._SpecularTextureEnabled;
  27916. },
  27917. set: function (value) {
  27918. if (StandardMaterial._SpecularTextureEnabled === value) {
  27919. return;
  27920. }
  27921. StandardMaterial._SpecularTextureEnabled = value;
  27922. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27923. },
  27924. enumerable: true,
  27925. configurable: true
  27926. });
  27927. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  27928. get: function () {
  27929. return StandardMaterial._BumpTextureEnabled;
  27930. },
  27931. set: function (value) {
  27932. if (StandardMaterial._BumpTextureEnabled === value) {
  27933. return;
  27934. }
  27935. StandardMaterial._BumpTextureEnabled = value;
  27936. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27937. },
  27938. enumerable: true,
  27939. configurable: true
  27940. });
  27941. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  27942. get: function () {
  27943. return StandardMaterial._LightmapTextureEnabled;
  27944. },
  27945. set: function (value) {
  27946. if (StandardMaterial._LightmapTextureEnabled === value) {
  27947. return;
  27948. }
  27949. StandardMaterial._LightmapTextureEnabled = value;
  27950. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27951. },
  27952. enumerable: true,
  27953. configurable: true
  27954. });
  27955. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  27956. get: function () {
  27957. return StandardMaterial._RefractionTextureEnabled;
  27958. },
  27959. set: function (value) {
  27960. if (StandardMaterial._RefractionTextureEnabled === value) {
  27961. return;
  27962. }
  27963. StandardMaterial._RefractionTextureEnabled = value;
  27964. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27965. },
  27966. enumerable: true,
  27967. configurable: true
  27968. });
  27969. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  27970. get: function () {
  27971. return StandardMaterial._ColorGradingTextureEnabled;
  27972. },
  27973. set: function (value) {
  27974. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  27975. return;
  27976. }
  27977. StandardMaterial._ColorGradingTextureEnabled = value;
  27978. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27979. },
  27980. enumerable: true,
  27981. configurable: true
  27982. });
  27983. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  27984. get: function () {
  27985. return StandardMaterial._FresnelEnabled;
  27986. },
  27987. set: function (value) {
  27988. if (StandardMaterial._FresnelEnabled === value) {
  27989. return;
  27990. }
  27991. StandardMaterial._FresnelEnabled = value;
  27992. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  27993. },
  27994. enumerable: true,
  27995. configurable: true
  27996. });
  27997. return StandardMaterial;
  27998. }(BABYLON.PushMaterial));
  27999. // Flags used to enable or disable a type of texture for all Standard Materials
  28000. StandardMaterial._DiffuseTextureEnabled = true;
  28001. StandardMaterial._AmbientTextureEnabled = true;
  28002. StandardMaterial._OpacityTextureEnabled = true;
  28003. StandardMaterial._ReflectionTextureEnabled = true;
  28004. StandardMaterial._EmissiveTextureEnabled = true;
  28005. StandardMaterial._SpecularTextureEnabled = true;
  28006. StandardMaterial._BumpTextureEnabled = true;
  28007. StandardMaterial._LightmapTextureEnabled = true;
  28008. StandardMaterial._RefractionTextureEnabled = true;
  28009. StandardMaterial._ColorGradingTextureEnabled = true;
  28010. StandardMaterial._FresnelEnabled = true;
  28011. __decorate([
  28012. BABYLON.serializeAsTexture("diffuseTexture")
  28013. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  28014. __decorate([
  28015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28016. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  28017. __decorate([
  28018. BABYLON.serializeAsTexture("ambientTexture")
  28019. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  28020. __decorate([
  28021. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28022. ], StandardMaterial.prototype, "ambientTexture", void 0);
  28023. __decorate([
  28024. BABYLON.serializeAsTexture("opacityTexture")
  28025. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  28026. __decorate([
  28027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28028. ], StandardMaterial.prototype, "opacityTexture", void 0);
  28029. __decorate([
  28030. BABYLON.serializeAsTexture("reflectionTexture")
  28031. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  28032. __decorate([
  28033. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28034. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  28035. __decorate([
  28036. BABYLON.serializeAsTexture("emissiveTexture")
  28037. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  28038. __decorate([
  28039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28040. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  28041. __decorate([
  28042. BABYLON.serializeAsTexture("specularTexture")
  28043. ], StandardMaterial.prototype, "_specularTexture", void 0);
  28044. __decorate([
  28045. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28046. ], StandardMaterial.prototype, "specularTexture", void 0);
  28047. __decorate([
  28048. BABYLON.serializeAsTexture("bumpTexture")
  28049. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  28050. __decorate([
  28051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28052. ], StandardMaterial.prototype, "bumpTexture", void 0);
  28053. __decorate([
  28054. BABYLON.serializeAsTexture("lightmapTexture")
  28055. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  28056. __decorate([
  28057. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28058. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  28059. __decorate([
  28060. BABYLON.serializeAsTexture("refractionTexture")
  28061. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  28062. __decorate([
  28063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28064. ], StandardMaterial.prototype, "refractionTexture", void 0);
  28065. __decorate([
  28066. BABYLON.serializeAsColor3("ambient")
  28067. ], StandardMaterial.prototype, "ambientColor", void 0);
  28068. __decorate([
  28069. BABYLON.serializeAsColor3("diffuse")
  28070. ], StandardMaterial.prototype, "diffuseColor", void 0);
  28071. __decorate([
  28072. BABYLON.serializeAsColor3("specular")
  28073. ], StandardMaterial.prototype, "specularColor", void 0);
  28074. __decorate([
  28075. BABYLON.serializeAsColor3("emissive")
  28076. ], StandardMaterial.prototype, "emissiveColor", void 0);
  28077. __decorate([
  28078. BABYLON.serialize()
  28079. ], StandardMaterial.prototype, "specularPower", void 0);
  28080. __decorate([
  28081. BABYLON.serialize("useAlphaFromDiffuseTexture")
  28082. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  28083. __decorate([
  28084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28085. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  28086. __decorate([
  28087. BABYLON.serialize("useEmissiveAsIllumination")
  28088. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  28089. __decorate([
  28090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28091. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  28092. __decorate([
  28093. BABYLON.serialize("linkEmissiveWithDiffuse")
  28094. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  28095. __decorate([
  28096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28097. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  28098. __decorate([
  28099. BABYLON.serialize("useSpecularOverAlpha")
  28100. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  28101. __decorate([
  28102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28103. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  28104. __decorate([
  28105. BABYLON.serialize("useReflectionOverAlpha")
  28106. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  28107. __decorate([
  28108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28109. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  28110. __decorate([
  28111. BABYLON.serialize("disableLighting")
  28112. ], StandardMaterial.prototype, "_disableLighting", void 0);
  28113. __decorate([
  28114. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  28115. ], StandardMaterial.prototype, "disableLighting", void 0);
  28116. __decorate([
  28117. BABYLON.serialize("useParallax")
  28118. ], StandardMaterial.prototype, "_useParallax", void 0);
  28119. __decorate([
  28120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28121. ], StandardMaterial.prototype, "useParallax", void 0);
  28122. __decorate([
  28123. BABYLON.serialize("useParallaxOcclusion")
  28124. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  28125. __decorate([
  28126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28127. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  28128. __decorate([
  28129. BABYLON.serialize()
  28130. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  28131. __decorate([
  28132. BABYLON.serialize("roughness")
  28133. ], StandardMaterial.prototype, "_roughness", void 0);
  28134. __decorate([
  28135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28136. ], StandardMaterial.prototype, "roughness", void 0);
  28137. __decorate([
  28138. BABYLON.serialize()
  28139. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  28140. __decorate([
  28141. BABYLON.serialize()
  28142. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  28143. __decorate([
  28144. BABYLON.serialize("useLightmapAsShadowmap")
  28145. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  28146. __decorate([
  28147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28148. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  28149. __decorate([
  28150. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  28151. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  28152. __decorate([
  28153. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28154. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  28155. __decorate([
  28156. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  28157. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  28158. __decorate([
  28159. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28160. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  28161. __decorate([
  28162. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  28163. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  28164. __decorate([
  28165. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28166. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  28167. __decorate([
  28168. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  28169. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  28170. __decorate([
  28171. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28172. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  28173. __decorate([
  28174. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  28175. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  28176. __decorate([
  28177. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28178. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  28179. __decorate([
  28180. BABYLON.serialize("useReflectionFresnelFromSpecular")
  28181. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  28182. __decorate([
  28183. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  28184. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  28185. __decorate([
  28186. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  28187. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  28188. __decorate([
  28189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28190. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  28191. __decorate([
  28192. BABYLON.serialize("maxSimultaneousLights")
  28193. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  28194. __decorate([
  28195. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  28196. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  28197. __decorate([
  28198. BABYLON.serialize("invertNormalMapX")
  28199. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  28200. __decorate([
  28201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28202. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  28203. __decorate([
  28204. BABYLON.serialize("invertNormalMapY")
  28205. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  28206. __decorate([
  28207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28208. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  28209. __decorate([
  28210. BABYLON.serialize("twoSidedLighting")
  28211. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  28212. __decorate([
  28213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28214. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  28215. __decorate([
  28216. BABYLON.serializeAsTexture("cameraColorGradingTexture")
  28217. ], StandardMaterial.prototype, "_cameraColorGradingTexture", void 0);
  28218. __decorate([
  28219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28220. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  28221. __decorate([
  28222. BABYLON.serializeAsColorCurves("cameraColorCurves")
  28223. ], StandardMaterial.prototype, "_cameraColorCurves", void 0);
  28224. __decorate([
  28225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  28226. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  28227. __decorate([
  28228. BABYLON.serialize()
  28229. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  28230. BABYLON.StandardMaterial = StandardMaterial;
  28231. })(BABYLON || (BABYLON = {}));
  28232. //# sourceMappingURL=babylon.standardMaterial.js.map
  28233. var BABYLON;
  28234. (function (BABYLON) {
  28235. var PBRMaterialDefines = (function (_super) {
  28236. __extends(PBRMaterialDefines, _super);
  28237. function PBRMaterialDefines() {
  28238. var _this = _super.call(this) || this;
  28239. _this.ALBEDO = false;
  28240. _this.AMBIENT = false;
  28241. _this.AMBIENTINGRAYSCALE = false;
  28242. _this.OPACITY = false;
  28243. _this.OPACITYRGB = false;
  28244. _this.REFLECTION = false;
  28245. _this.EMISSIVE = false;
  28246. _this.REFLECTIVITY = false;
  28247. _this.BUMP = false;
  28248. _this.PARALLAX = false;
  28249. _this.PARALLAXOCCLUSION = false;
  28250. _this.SPECULAROVERALPHA = false;
  28251. _this.CLIPPLANE = false;
  28252. _this.ALPHATEST = false;
  28253. _this.ALPHAFROMALBEDO = false;
  28254. _this.POINTSIZE = false;
  28255. _this.FOG = false;
  28256. _this.SPECULARTERM = false;
  28257. _this.OPACITYFRESNEL = false;
  28258. _this.EMISSIVEFRESNEL = false;
  28259. _this.FRESNEL = false;
  28260. _this.NORMAL = false;
  28261. _this.TANGENT = false;
  28262. _this.UV1 = false;
  28263. _this.UV2 = false;
  28264. _this.VERTEXCOLOR = false;
  28265. _this.VERTEXALPHA = false;
  28266. _this.NUM_BONE_INFLUENCERS = 0;
  28267. _this.BonesPerMesh = 0;
  28268. _this.INSTANCES = false;
  28269. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  28270. _this.MICROSURFACEAUTOMATIC = false;
  28271. _this.EMISSIVEASILLUMINATION = false;
  28272. _this.LINKEMISSIVEWITHALBEDO = false;
  28273. _this.LIGHTMAP = false;
  28274. _this.USELIGHTMAPASSHADOWMAP = false;
  28275. _this.REFLECTIONMAP_3D = false;
  28276. _this.REFLECTIONMAP_SPHERICAL = false;
  28277. _this.REFLECTIONMAP_PLANAR = false;
  28278. _this.REFLECTIONMAP_CUBIC = false;
  28279. _this.REFLECTIONMAP_PROJECTION = false;
  28280. _this.REFLECTIONMAP_SKYBOX = false;
  28281. _this.REFLECTIONMAP_EXPLICIT = false;
  28282. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  28283. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  28284. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  28285. _this.INVERTCUBICMAP = false;
  28286. _this.LOGARITHMICDEPTH = false;
  28287. _this.CAMERATONEMAP = false;
  28288. _this.CAMERACONTRAST = false;
  28289. _this.CAMERACOLORGRADING = false;
  28290. _this.CAMERACOLORCURVES = false;
  28291. _this.OVERLOADEDVALUES = false;
  28292. _this.OVERLOADEDSHADOWVALUES = false;
  28293. _this.USESPHERICALFROMREFLECTIONMAP = false;
  28294. _this.REFRACTION = false;
  28295. _this.REFRACTIONMAP_3D = false;
  28296. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  28297. _this.REFRACTIONMAPINLINEARSPACE = false;
  28298. _this.LODBASEDMICROSFURACE = false;
  28299. _this.USEPHYSICALLIGHTFALLOFF = false;
  28300. _this.RADIANCEOVERALPHA = false;
  28301. _this.USEPMREMREFLECTION = false;
  28302. _this.USEPMREMREFRACTION = false;
  28303. _this.INVERTNORMALMAPX = false;
  28304. _this.INVERTNORMALMAPY = false;
  28305. _this.TWOSIDEDLIGHTING = false;
  28306. _this.SHADOWFULLFLOAT = false;
  28307. _this.METALLICWORKFLOW = false;
  28308. _this.METALLICMAP = false;
  28309. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  28310. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  28311. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  28312. _this.AOSTOREINMETALMAPRED = false;
  28313. _this.MICROSURFACEMAP = false;
  28314. _this.MORPHTARGETS = false;
  28315. _this.MORPHTARGETS_NORMAL = false;
  28316. _this.MORPHTARGETS_TANGENT = false;
  28317. _this.NUM_MORPH_INFLUENCERS = 0;
  28318. _this.rebuild();
  28319. return _this;
  28320. }
  28321. return PBRMaterialDefines;
  28322. }(BABYLON.MaterialDefines));
  28323. /**
  28324. * The Physically based material of BJS.
  28325. *
  28326. * This offers the main features of a standard PBR material.
  28327. * For more information, please refer to the documentation :
  28328. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  28329. */
  28330. var PBRMaterial = (function (_super) {
  28331. __extends(PBRMaterial, _super);
  28332. /**
  28333. * Instantiates a new PBRMaterial instance.
  28334. *
  28335. * @param name The material name
  28336. * @param scene The scene the material will be use in.
  28337. */
  28338. function PBRMaterial(name, scene) {
  28339. var _this = _super.call(this, name, scene) || this;
  28340. /**
  28341. * Intensity of the direct lights e.g. the four lights available in your scene.
  28342. * This impacts both the direct diffuse and specular highlights.
  28343. */
  28344. _this.directIntensity = 1.0;
  28345. /**
  28346. * Intensity of the emissive part of the material.
  28347. * This helps controlling the emissive effect without modifying the emissive color.
  28348. */
  28349. _this.emissiveIntensity = 1.0;
  28350. /**
  28351. * Intensity of the environment e.g. how much the environment will light the object
  28352. * either through harmonics for rough material or through the refelction for shiny ones.
  28353. */
  28354. _this.environmentIntensity = 1.0;
  28355. /**
  28356. * This is a special control allowing the reduction of the specular highlights coming from the
  28357. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  28358. */
  28359. _this.specularIntensity = 1.0;
  28360. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  28361. /**
  28362. * Debug Control allowing disabling the bump map on this material.
  28363. */
  28364. _this.disableBumpMap = false;
  28365. /**
  28366. * Debug Control helping enforcing or dropping the darkness of shadows.
  28367. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  28368. */
  28369. _this.overloadedShadowIntensity = 1.0;
  28370. /**
  28371. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  28372. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  28373. */
  28374. _this.overloadedShadeIntensity = 1.0;
  28375. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  28376. /**
  28377. * The camera exposure used on this material.
  28378. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  28379. * This corresponds to a photographic exposure.
  28380. */
  28381. _this.cameraExposure = 1.0;
  28382. /**
  28383. * The camera contrast used on this material.
  28384. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  28385. */
  28386. _this.cameraContrast = 1.0;
  28387. /**
  28388. * Color Grading 2D Lookup Texture.
  28389. * This allows special effects like sepia, black and white to sixties rendering style.
  28390. */
  28391. _this.cameraColorGradingTexture = null;
  28392. /**
  28393. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  28394. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  28395. * 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;
  28396. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  28397. */
  28398. _this.cameraColorCurves = null;
  28399. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  28400. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  28401. /**
  28402. * Debug Control allowing to overload the ambient color.
  28403. * This as to be use with the overloadedAmbientIntensity parameter.
  28404. */
  28405. _this.overloadedAmbient = BABYLON.Color3.White();
  28406. /**
  28407. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  28408. */
  28409. _this.overloadedAmbientIntensity = 0.0;
  28410. /**
  28411. * Debug Control allowing to overload the albedo color.
  28412. * This as to be use with the overloadedAlbedoIntensity parameter.
  28413. */
  28414. _this.overloadedAlbedo = BABYLON.Color3.White();
  28415. /**
  28416. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  28417. */
  28418. _this.overloadedAlbedoIntensity = 0.0;
  28419. /**
  28420. * Debug Control allowing to overload the reflectivity color.
  28421. * This as to be use with the overloadedReflectivityIntensity parameter.
  28422. */
  28423. _this.overloadedReflectivity = new BABYLON.Color3(0.0, 0.0, 0.0);
  28424. /**
  28425. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  28426. */
  28427. _this.overloadedReflectivityIntensity = 0.0;
  28428. /**
  28429. * Debug Control allowing to overload the emissive color.
  28430. * This as to be use with the overloadedEmissiveIntensity parameter.
  28431. */
  28432. _this.overloadedEmissive = BABYLON.Color3.White();
  28433. /**
  28434. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  28435. */
  28436. _this.overloadedEmissiveIntensity = 0.0;
  28437. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  28438. /**
  28439. * Debug Control allowing to overload the reflection color.
  28440. * This as to be use with the overloadedReflectionIntensity parameter.
  28441. */
  28442. _this.overloadedReflection = BABYLON.Color3.White();
  28443. /**
  28444. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  28445. */
  28446. _this.overloadedReflectionIntensity = 0.0;
  28447. /**
  28448. * Debug Control allowing to overload the microsurface.
  28449. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  28450. */
  28451. _this.overloadedMicroSurface = 0.0;
  28452. /**
  28453. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  28454. */
  28455. _this.overloadedMicroSurfaceIntensity = 0.0;
  28456. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  28457. /**
  28458. * AKA Occlusion Texture Intensity in other nomenclature.
  28459. */
  28460. _this.ambientTextureStrength = 1.0;
  28461. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  28462. /**
  28463. * AKA Diffuse Color in other nomenclature.
  28464. */
  28465. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  28466. /**
  28467. * AKA Specular Color in other nomenclature.
  28468. */
  28469. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  28470. _this.reflectionColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  28471. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  28472. /**
  28473. * AKA Glossiness in other nomenclature.
  28474. */
  28475. _this.microSurface = 0.9;
  28476. /**
  28477. * source material index of refraction (IOR)' / 'destination material IOR.
  28478. */
  28479. _this.indexOfRefraction = 0.66;
  28480. /**
  28481. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  28482. */
  28483. _this.invertRefractionY = false;
  28484. /**
  28485. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  28486. * Materials half opaque for instance using refraction could benefit from this control.
  28487. */
  28488. _this.linkRefractionWithTransparency = false;
  28489. /**
  28490. * The emissive and albedo are linked to never be more than one (Energy conservation).
  28491. */
  28492. _this.linkEmissiveWithAlbedo = false;
  28493. _this.useLightmapAsShadowmap = false;
  28494. /**
  28495. * In this mode, the emissive informtaion will always be added to the lighting once.
  28496. * A light for instance can be thought as emissive.
  28497. */
  28498. _this.useEmissiveAsIllumination = false;
  28499. /**
  28500. * Secifies that the alpha is coming form the albedo channel alpha channel.
  28501. */
  28502. _this.useAlphaFromAlbedoTexture = false;
  28503. /**
  28504. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  28505. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  28506. */
  28507. _this.useSpecularOverAlpha = true;
  28508. /**
  28509. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  28510. */
  28511. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  28512. /**
  28513. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  28514. */
  28515. _this.useRoughnessFromMetallicTextureAlpha = true;
  28516. /**
  28517. * Specifies if the metallic texture contains the roughness information in its green channel.
  28518. */
  28519. _this.useRoughnessFromMetallicTextureGreen = false;
  28520. /**
  28521. * Specifies if the metallic texture contains the metallness information in its blue channel.
  28522. */
  28523. _this.useMetallnessFromMetallicTextureBlue = false;
  28524. /**
  28525. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  28526. */
  28527. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  28528. /**
  28529. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  28530. */
  28531. _this.useAmbientInGrayScale = false;
  28532. /**
  28533. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  28534. * The material will try to infer what glossiness each pixel should be.
  28535. */
  28536. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  28537. /**
  28538. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  28539. * the creation of the material.
  28540. */
  28541. _this.useScalarInLinearSpace = false;
  28542. /**
  28543. * BJS is using an harcoded light falloff based on a manually sets up range.
  28544. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  28545. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  28546. */
  28547. _this.usePhysicalLightFalloff = true;
  28548. /**
  28549. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  28550. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  28551. */
  28552. _this.useRadianceOverAlpha = true;
  28553. /**
  28554. * Allows using the bump map in parallax mode.
  28555. */
  28556. _this.useParallax = false;
  28557. /**
  28558. * Allows using the bump map in parallax occlusion mode.
  28559. */
  28560. _this.useParallaxOcclusion = false;
  28561. /**
  28562. * Controls the scale bias of the parallax mode.
  28563. */
  28564. _this.parallaxScaleBias = 0.05;
  28565. /**
  28566. * If sets to true, disables all the lights affecting the material.
  28567. */
  28568. _this.disableLighting = false;
  28569. /**
  28570. * Number of Simultaneous lights allowed on the material.
  28571. */
  28572. _this.maxSimultaneousLights = 4;
  28573. /**
  28574. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  28575. */
  28576. _this.invertNormalMapX = false;
  28577. /**
  28578. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  28579. */
  28580. _this.invertNormalMapY = false;
  28581. /**
  28582. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  28583. */
  28584. _this.twoSidedLighting = false;
  28585. _this._renderTargets = new BABYLON.SmartArray(16);
  28586. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  28587. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  28588. _this._tempColor = new BABYLON.Color3();
  28589. _this._defines = new PBRMaterialDefines();
  28590. _this._cachedDefines = new PBRMaterialDefines();
  28591. _this._myScene = null;
  28592. _this._myShadowGenerator = null;
  28593. _this._cachedDefines.BonesPerMesh = -1;
  28594. _this.getRenderTargetTextures = function () {
  28595. _this._renderTargets.reset();
  28596. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  28597. _this._renderTargets.push(_this.reflectionTexture);
  28598. }
  28599. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  28600. _this._renderTargets.push(_this.refractionTexture);
  28601. }
  28602. return _this._renderTargets;
  28603. };
  28604. return _this;
  28605. }
  28606. PBRMaterial.prototype.getClassName = function () {
  28607. return "PBRMaterial";
  28608. };
  28609. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  28610. get: function () {
  28611. return this._useLogarithmicDepth;
  28612. },
  28613. set: function (value) {
  28614. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  28615. },
  28616. enumerable: true,
  28617. configurable: true
  28618. });
  28619. PBRMaterial.prototype.needAlphaBlending = function () {
  28620. if (this.linkRefractionWithTransparency) {
  28621. return false;
  28622. }
  28623. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  28624. };
  28625. PBRMaterial.prototype.needAlphaTesting = function () {
  28626. if (this.linkRefractionWithTransparency) {
  28627. return false;
  28628. }
  28629. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  28630. };
  28631. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  28632. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  28633. };
  28634. PBRMaterial.prototype.getAlphaTestTexture = function () {
  28635. return this.albedoTexture;
  28636. };
  28637. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  28638. if (!mesh) {
  28639. return true;
  28640. }
  28641. if (this._defines.INSTANCES !== useInstances) {
  28642. return false;
  28643. }
  28644. return false;
  28645. };
  28646. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  28647. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  28648. };
  28649. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  28650. if (!useScalarInLinear) {
  28651. color.toLinearSpaceToRef(ref);
  28652. }
  28653. else {
  28654. ref.r = color.r;
  28655. ref.g = color.g;
  28656. ref.b = color.b;
  28657. }
  28658. };
  28659. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  28660. var lightIndex = 0;
  28661. var depthValuesAlreadySet = false;
  28662. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  28663. var light = _a[_i];
  28664. var useUbo = light._uniformBuffer.useUbo;
  28665. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  28666. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  28667. // GAMMA CORRECTION.
  28668. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  28669. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  28670. light._uniformBuffer.updateColor4(useUbo ? "vLightDiffuse" : "vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  28671. if (defines["SPECULARTERM"]) {
  28672. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  28673. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  28674. light._uniformBuffer.updateColor3(useUbo ? "vLightSpecular" : "vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  28675. }
  28676. // Shadows
  28677. if (scene.shadowsEnabled) {
  28678. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex + "", effect, depthValuesAlreadySet);
  28679. }
  28680. light._uniformBuffer.update();
  28681. lightIndex++;
  28682. if (lightIndex === maxSimultaneousLights)
  28683. break;
  28684. }
  28685. };
  28686. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  28687. if (this.isFrozen) {
  28688. if (this._wasPreviouslyReady) {
  28689. return true;
  28690. }
  28691. }
  28692. var scene = this.getScene();
  28693. var engine = scene.getEngine();
  28694. var needUVs = false;
  28695. this._defines.reset();
  28696. if (scene.lightsEnabled && !this.disableLighting) {
  28697. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, true, this.maxSimultaneousLights);
  28698. }
  28699. if (!this.checkReadyOnEveryCall) {
  28700. if (this._renderId === scene.getRenderId()) {
  28701. if (this._checkCache(scene, mesh, useInstances)) {
  28702. return true;
  28703. }
  28704. }
  28705. }
  28706. if (scene.texturesEnabled) {
  28707. if (scene.getEngine().getCaps().textureLOD) {
  28708. this._defines.LODBASEDMICROSFURACE = true;
  28709. }
  28710. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  28711. if (!this.albedoTexture.isReady()) {
  28712. return false;
  28713. }
  28714. needUVs = true;
  28715. this._defines.ALBEDO = true;
  28716. }
  28717. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  28718. if (!this.ambientTexture.isReady()) {
  28719. return false;
  28720. }
  28721. needUVs = true;
  28722. this._defines.AMBIENT = true;
  28723. this._defines.AMBIENTINGRAYSCALE = this.useAmbientInGrayScale;
  28724. }
  28725. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  28726. if (!this.opacityTexture.isReady()) {
  28727. return false;
  28728. }
  28729. needUVs = true;
  28730. this._defines.OPACITY = true;
  28731. if (this.opacityTexture.getAlphaFromRGB) {
  28732. this._defines.OPACITYRGB = true;
  28733. }
  28734. }
  28735. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  28736. if (!this.reflectionTexture.isReady()) {
  28737. return false;
  28738. }
  28739. this._defines.REFLECTION = true;
  28740. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  28741. this._defines.INVERTCUBICMAP = true;
  28742. }
  28743. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  28744. switch (this.reflectionTexture.coordinatesMode) {
  28745. case BABYLON.Texture.CUBIC_MODE:
  28746. case BABYLON.Texture.INVCUBIC_MODE:
  28747. this._defines.REFLECTIONMAP_CUBIC = true;
  28748. break;
  28749. case BABYLON.Texture.EXPLICIT_MODE:
  28750. this._defines.REFLECTIONMAP_EXPLICIT = true;
  28751. break;
  28752. case BABYLON.Texture.PLANAR_MODE:
  28753. this._defines.REFLECTIONMAP_PLANAR = true;
  28754. break;
  28755. case BABYLON.Texture.PROJECTION_MODE:
  28756. this._defines.REFLECTIONMAP_PROJECTION = true;
  28757. break;
  28758. case BABYLON.Texture.SKYBOX_MODE:
  28759. this._defines.REFLECTIONMAP_SKYBOX = true;
  28760. break;
  28761. case BABYLON.Texture.SPHERICAL_MODE:
  28762. this._defines.REFLECTIONMAP_SPHERICAL = true;
  28763. break;
  28764. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  28765. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  28766. break;
  28767. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  28768. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  28769. break;
  28770. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  28771. this._defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  28772. break;
  28773. }
  28774. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  28775. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  28776. if (this.reflectionTexture.isPMREM) {
  28777. this._defines.USEPMREMREFLECTION = true;
  28778. }
  28779. }
  28780. }
  28781. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  28782. if (!this.lightmapTexture.isReady()) {
  28783. return false;
  28784. }
  28785. needUVs = true;
  28786. this._defines.LIGHTMAP = true;
  28787. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  28788. }
  28789. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  28790. if (!this.emissiveTexture.isReady()) {
  28791. return false;
  28792. }
  28793. needUVs = true;
  28794. this._defines.EMISSIVE = true;
  28795. }
  28796. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  28797. if (this.metallicTexture) {
  28798. if (!this.metallicTexture.isReady()) {
  28799. return false;
  28800. }
  28801. needUVs = true;
  28802. this._defines.METALLICWORKFLOW = true;
  28803. this._defines.METALLICMAP = true;
  28804. this._defines.ROUGHNESSSTOREINMETALMAPALPHA = this.useRoughnessFromMetallicTextureAlpha;
  28805. this._defines.ROUGHNESSSTOREINMETALMAPGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  28806. this._defines.METALLNESSSTOREINMETALMAPBLUE = this.useMetallnessFromMetallicTextureBlue;
  28807. this._defines.AOSTOREINMETALMAPRED = this.useAmbientOcclusionFromMetallicTextureRed;
  28808. }
  28809. else if (this.reflectivityTexture) {
  28810. if (!this.reflectivityTexture.isReady()) {
  28811. return false;
  28812. }
  28813. needUVs = true;
  28814. this._defines.REFLECTIVITY = true;
  28815. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  28816. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  28817. }
  28818. if (this.microSurfaceTexture) {
  28819. if (!this.microSurfaceTexture.isReady()) {
  28820. return false;
  28821. }
  28822. needUVs = true;
  28823. this._defines.MICROSURFACEMAP = true;
  28824. }
  28825. }
  28826. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  28827. if (!this.bumpTexture.isReady()) {
  28828. return false;
  28829. }
  28830. needUVs = true;
  28831. this._defines.BUMP = true;
  28832. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  28833. this._defines.PARALLAX = true;
  28834. if (this.useParallaxOcclusion) {
  28835. this._defines.PARALLAXOCCLUSION = true;
  28836. }
  28837. }
  28838. if (this.invertNormalMapX) {
  28839. this._defines.INVERTNORMALMAPX = true;
  28840. }
  28841. if (this.invertNormalMapY) {
  28842. this._defines.INVERTNORMALMAPY = true;
  28843. }
  28844. if (scene._mirroredCameraPosition) {
  28845. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  28846. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  28847. }
  28848. }
  28849. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  28850. if (!this.refractionTexture.isReady()) {
  28851. return false;
  28852. }
  28853. needUVs = true;
  28854. this._defines.REFRACTION = true;
  28855. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  28856. if (this.linkRefractionWithTransparency) {
  28857. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  28858. }
  28859. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  28860. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  28861. if (this.refractionTexture.isPMREM) {
  28862. this._defines.USEPMREMREFRACTION = true;
  28863. }
  28864. }
  28865. }
  28866. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  28867. if (!this.cameraColorGradingTexture.isReady()) {
  28868. return false;
  28869. }
  28870. this._defines.CAMERACOLORGRADING = true;
  28871. }
  28872. if (!this.backFaceCulling && this.twoSidedLighting) {
  28873. this._defines.TWOSIDEDLIGHTING = true;
  28874. }
  28875. }
  28876. // Effect
  28877. if (scene.clipPlane) {
  28878. this._defines.CLIPPLANE = true;
  28879. }
  28880. if (engine.getAlphaTesting()) {
  28881. this._defines.ALPHATEST = true;
  28882. }
  28883. if (this._shouldUseAlphaFromAlbedoTexture()) {
  28884. this._defines.ALPHAFROMALBEDO = true;
  28885. }
  28886. if (this.useEmissiveAsIllumination) {
  28887. this._defines.EMISSIVEASILLUMINATION = true;
  28888. }
  28889. if (this.linkEmissiveWithAlbedo) {
  28890. this._defines.LINKEMISSIVEWITHALBEDO = true;
  28891. }
  28892. if (this.useLogarithmicDepth) {
  28893. this._defines.LOGARITHMICDEPTH = true;
  28894. }
  28895. if (this.cameraContrast != 1) {
  28896. this._defines.CAMERACONTRAST = true;
  28897. }
  28898. if (this.cameraExposure != 1) {
  28899. this._defines.CAMERATONEMAP = true;
  28900. }
  28901. if (this.cameraColorCurves) {
  28902. this._defines.CAMERACOLORCURVES = true;
  28903. }
  28904. if (this.overloadedShadeIntensity != 1 ||
  28905. this.overloadedShadowIntensity != 1) {
  28906. this._defines.OVERLOADEDSHADOWVALUES = true;
  28907. }
  28908. if (this.overloadedMicroSurfaceIntensity > 0 ||
  28909. this.overloadedEmissiveIntensity > 0 ||
  28910. this.overloadedReflectivityIntensity > 0 ||
  28911. this.overloadedAlbedoIntensity > 0 ||
  28912. this.overloadedAmbientIntensity > 0 ||
  28913. this.overloadedReflectionIntensity > 0) {
  28914. this._defines.OVERLOADEDVALUES = true;
  28915. }
  28916. // Point size
  28917. if (this.pointsCloud || scene.forcePointsCloud) {
  28918. this._defines.POINTSIZE = true;
  28919. }
  28920. // Fog
  28921. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28922. this._defines.FOG = true;
  28923. }
  28924. if (BABYLON.StandardMaterial.FresnelEnabled) {
  28925. // Fresnel
  28926. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  28927. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  28928. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  28929. this._defines.OPACITYFRESNEL = true;
  28930. }
  28931. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  28932. this._defines.EMISSIVEFRESNEL = true;
  28933. }
  28934. this._defines.FRESNEL = true;
  28935. }
  28936. }
  28937. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  28938. this._defines.SPECULAROVERALPHA = true;
  28939. }
  28940. if (this.usePhysicalLightFalloff) {
  28941. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  28942. }
  28943. if (this.useRadianceOverAlpha) {
  28944. this._defines.RADIANCEOVERALPHA = true;
  28945. }
  28946. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  28947. this._defines.METALLICWORKFLOW = true;
  28948. }
  28949. // Attribs
  28950. if (mesh) {
  28951. if (!mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28952. mesh.createNormals(true);
  28953. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  28954. }
  28955. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28956. this._defines.NORMAL = true;
  28957. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  28958. this._defines.TANGENT = true;
  28959. }
  28960. }
  28961. if (needUVs) {
  28962. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28963. this._defines.UV1 = true;
  28964. }
  28965. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28966. this._defines.UV2 = true;
  28967. }
  28968. }
  28969. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28970. this._defines.VERTEXCOLOR = true;
  28971. if (mesh.hasVertexAlpha) {
  28972. this._defines.VERTEXALPHA = true;
  28973. }
  28974. }
  28975. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  28976. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  28977. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  28978. }
  28979. // Instances
  28980. if (useInstances) {
  28981. this._defines.INSTANCES = true;
  28982. }
  28983. if (mesh.morphTargetManager) {
  28984. var manager = mesh.morphTargetManager;
  28985. this._defines.MORPHTARGETS_TANGENT = manager.supportsTangents && this._defines.TANGENT;
  28986. this._defines.MORPHTARGETS_NORMAL = manager.supportsNormals && this._defines.NORMAL;
  28987. this._defines.MORPHTARGETS = (manager.numInfluencers > 0);
  28988. this._defines.NUM_MORPH_INFLUENCERS = manager.numInfluencers;
  28989. }
  28990. }
  28991. // Get correct effect
  28992. if (!this._defines.isEqual(this._cachedDefines)) {
  28993. this._defines.cloneTo(this._cachedDefines);
  28994. scene.resetCachedMaterial();
  28995. // Fallbacks
  28996. var fallbacks = new BABYLON.EffectFallbacks();
  28997. if (this._defines.REFLECTION) {
  28998. fallbacks.addFallback(0, "REFLECTION");
  28999. }
  29000. if (this._defines.REFRACTION) {
  29001. fallbacks.addFallback(0, "REFRACTION");
  29002. }
  29003. if (this._defines.REFLECTIVITY) {
  29004. fallbacks.addFallback(0, "REFLECTIVITY");
  29005. }
  29006. if (this._defines.BUMP) {
  29007. fallbacks.addFallback(0, "BUMP");
  29008. }
  29009. if (this._defines.PARALLAX) {
  29010. fallbacks.addFallback(1, "PARALLAX");
  29011. }
  29012. if (this._defines.PARALLAXOCCLUSION) {
  29013. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  29014. }
  29015. if (this._defines.SPECULAROVERALPHA) {
  29016. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  29017. }
  29018. if (this._defines.FOG) {
  29019. fallbacks.addFallback(1, "FOG");
  29020. }
  29021. if (this._defines.POINTSIZE) {
  29022. fallbacks.addFallback(0, "POINTSIZE");
  29023. }
  29024. if (this._defines.LOGARITHMICDEPTH) {
  29025. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  29026. }
  29027. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  29028. if (this._defines.SPECULARTERM) {
  29029. fallbacks.addFallback(0, "SPECULARTERM");
  29030. }
  29031. if (this._defines.OPACITYFRESNEL) {
  29032. fallbacks.addFallback(1, "OPACITYFRESNEL");
  29033. }
  29034. if (this._defines.EMISSIVEFRESNEL) {
  29035. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  29036. }
  29037. if (this._defines.FRESNEL) {
  29038. fallbacks.addFallback(3, "FRESNEL");
  29039. }
  29040. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  29041. fallbacks.addCPUSkinningFallback(0, mesh);
  29042. }
  29043. //Attributes
  29044. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29045. if (this._defines.NORMAL) {
  29046. attribs.push(BABYLON.VertexBuffer.NormalKind);
  29047. }
  29048. if (this._defines.TANGENT) {
  29049. attribs.push(BABYLON.VertexBuffer.TangentKind);
  29050. }
  29051. if (this._defines.UV1) {
  29052. attribs.push(BABYLON.VertexBuffer.UVKind);
  29053. }
  29054. if (this._defines.UV2) {
  29055. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29056. }
  29057. if (this._defines.VERTEXCOLOR) {
  29058. attribs.push(BABYLON.VertexBuffer.ColorKind);
  29059. }
  29060. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  29061. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  29062. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, this._defines);
  29063. // Legacy browser patch
  29064. var join = this._defines.toString();
  29065. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  29066. "vFogInfos", "vFogColor", "pointSize",
  29067. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  29068. "mBones",
  29069. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  29070. "depthValues",
  29071. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  29072. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  29073. "logarithmicDepthConstant",
  29074. "vSphericalX", "vSphericalY", "vSphericalZ",
  29075. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  29076. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  29077. "vMicrosurfaceTextureLods",
  29078. "vCameraInfos"
  29079. ];
  29080. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "microSurfaceSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  29081. var uniformBuffers = ["Material", "Scene"];
  29082. if (this._defines.CAMERACOLORCURVES) {
  29083. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  29084. }
  29085. if (this._defines.CAMERACOLORGRADING) {
  29086. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  29087. }
  29088. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  29089. uniformsNames: uniforms,
  29090. uniformBuffersNames: uniformBuffers,
  29091. samplers: samplers,
  29092. defines: this._defines,
  29093. maxSimultaneousLights: this.maxSimultaneousLights
  29094. });
  29095. var onCompiled = function (effect) {
  29096. if (this.onCompiled) {
  29097. this.onCompiled(effect);
  29098. }
  29099. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  29100. }.bind(this);
  29101. this._effect = scene.getEngine().createEffect("pbr", {
  29102. attributes: attribs,
  29103. uniformsNames: uniforms,
  29104. uniformBuffersNames: uniformBuffers,
  29105. samplers: samplers,
  29106. defines: join,
  29107. fallbacks: fallbacks,
  29108. onCompiled: onCompiled,
  29109. onError: this.onError,
  29110. indexParameters: { maxSimultaneousLights: this.maxSimultaneousLights, maxSimultaneousMorphTargets: this._defines.NUM_MORPH_INFLUENCERS }
  29111. }, engine);
  29112. this.buildUniformLayout();
  29113. }
  29114. if (!this._effect.isReady()) {
  29115. return false;
  29116. }
  29117. this._renderId = scene.getRenderId();
  29118. this._wasPreviouslyReady = true;
  29119. return true;
  29120. };
  29121. PBRMaterial.prototype.buildUniformLayout = function () {
  29122. // Order is important !
  29123. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  29124. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  29125. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  29126. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  29127. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  29128. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  29129. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  29130. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  29131. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  29132. this._uniformBuffer.addUniform("vBumpInfos", 3);
  29133. this._uniformBuffer.addUniform("albedoMatrix", 16);
  29134. this._uniformBuffer.addUniform("ambientMatrix", 16);
  29135. this._uniformBuffer.addUniform("opacityMatrix", 16);
  29136. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  29137. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  29138. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  29139. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  29140. this._uniformBuffer.addUniform("bumpMatrix", 16);
  29141. this._uniformBuffer.addUniform("refractionMatrix", 16);
  29142. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  29143. this._uniformBuffer.addUniform("vReflectionColor", 3);
  29144. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  29145. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  29146. this._uniformBuffer.addUniform("vMicrosurfaceTextureLods", 2);
  29147. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  29148. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  29149. this._uniformBuffer.addUniform("opacityParts", 4);
  29150. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  29151. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  29152. this._uniformBuffer.addUniform("vOverloadedIntensity", 4);
  29153. this._uniformBuffer.addUniform("vOverloadedAmbient", 3);
  29154. this._uniformBuffer.addUniform("vOverloadedAlbedo", 3);
  29155. this._uniformBuffer.addUniform("vOverloadedReflectivity", 3);
  29156. this._uniformBuffer.addUniform("vOverloadedEmissive", 3);
  29157. this._uniformBuffer.addUniform("vOverloadedReflection", 3);
  29158. this._uniformBuffer.addUniform("vOverloadedMicroSurface", 3);
  29159. this._uniformBuffer.addUniform("vOverloadedShadowIntensity", 4);
  29160. this._uniformBuffer.addUniform("pointSize", 1);
  29161. this._uniformBuffer.create();
  29162. };
  29163. PBRMaterial.prototype.unbind = function () {
  29164. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  29165. this._uniformBuffer.setTexture("reflection2DSampler", null);
  29166. }
  29167. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  29168. this._uniformBuffer.setTexture("refraction2DSampler", null);
  29169. }
  29170. _super.prototype.unbind.call(this);
  29171. };
  29172. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  29173. this._effect.setMatrix("world", world);
  29174. };
  29175. PBRMaterial.prototype.bind = function (world, mesh) {
  29176. this._myScene = this.getScene();
  29177. var effect = this._effect;
  29178. // Matrices
  29179. this.bindOnlyWorldMatrix(world);
  29180. // Bones
  29181. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  29182. if (this._myScene.getCachedMaterial() !== this) {
  29183. this._uniformBuffer.bindToEffect(effect, "Material");
  29184. this.bindViewProjection(effect);
  29185. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  29186. // Fresnel
  29187. if (BABYLON.StandardMaterial.FresnelEnabled) {
  29188. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  29189. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  29190. }
  29191. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  29192. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  29193. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  29194. }
  29195. }
  29196. // Texture uniforms
  29197. if (this._myScene.texturesEnabled) {
  29198. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29199. this._uniformBuffer.updateFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  29200. this._uniformBuffer.updateMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  29201. }
  29202. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  29203. this._uniformBuffer.updateFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  29204. this._uniformBuffer.updateMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  29205. }
  29206. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  29207. this._uniformBuffer.updateFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  29208. this._uniformBuffer.updateMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  29209. }
  29210. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  29211. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  29212. this._uniformBuffer.updateMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  29213. this._uniformBuffer.updateFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  29214. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  29215. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  29216. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  29217. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  29218. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  29219. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  29220. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  29221. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  29222. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  29223. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  29224. }
  29225. }
  29226. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  29227. this._uniformBuffer.updateFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  29228. this._uniformBuffer.updateMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  29229. }
  29230. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  29231. this._uniformBuffer.updateFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  29232. this._uniformBuffer.updateMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  29233. }
  29234. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  29235. if (this.metallicTexture) {
  29236. this._uniformBuffer.updateFloat3("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level, this.ambientTextureStrength);
  29237. this._uniformBuffer.updateMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  29238. }
  29239. else if (this.reflectivityTexture) {
  29240. this._uniformBuffer.updateFloat3("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level, 1.0);
  29241. this._uniformBuffer.updateMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  29242. }
  29243. if (this.microSurfaceTexture) {
  29244. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this.microSurfaceTexture.coordinatesIndex, this.microSurfaceTexture.level);
  29245. this._uniformBuffer.updateMatrix("microSurfaceSamplerMatrix", this.microSurfaceTexture.getTextureMatrix());
  29246. }
  29247. }
  29248. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  29249. this._uniformBuffer.updateFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  29250. this._uniformBuffer.updateMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  29251. }
  29252. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  29253. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  29254. var depth = 1.0;
  29255. if (!this.refractionTexture.isCube) {
  29256. this._uniformBuffer.updateMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  29257. if (this.refractionTexture.depth) {
  29258. depth = this.refractionTexture.depth;
  29259. }
  29260. }
  29261. this._uniformBuffer.updateFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  29262. }
  29263. if ((this.reflectionTexture || this.refractionTexture)) {
  29264. this._uniformBuffer.updateFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  29265. }
  29266. }
  29267. // Point size
  29268. if (this.pointsCloud) {
  29269. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  29270. }
  29271. // Colors
  29272. if (this._defines.METALLICWORKFLOW) {
  29273. PBRMaterial._scaledReflectivity.r = (this.metallic === undefined || this.metallic === null) ? 1 : this.metallic;
  29274. PBRMaterial._scaledReflectivity.g = (this.roughness === undefined || this.roughness === null) ? 1 : this.roughness;
  29275. this._uniformBuffer.updateColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  29276. }
  29277. else {
  29278. // GAMMA CORRECTION.
  29279. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  29280. this._uniformBuffer.updateColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  29281. }
  29282. // GAMMA CORRECTION.
  29283. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  29284. this._uniformBuffer.updateColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  29285. // GAMMA CORRECTION.
  29286. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  29287. this._uniformBuffer.updateColor3("vReflectionColor", PBRMaterial._scaledReflection);
  29288. // GAMMA CORRECTION.
  29289. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  29290. this._uniformBuffer.updateColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  29291. // Misc
  29292. this._lightingInfos.x = this.directIntensity;
  29293. this._lightingInfos.y = this.emissiveIntensity;
  29294. this._lightingInfos.z = this.environmentIntensity;
  29295. this._lightingInfos.w = this.specularIntensity;
  29296. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  29297. // Overloaded params
  29298. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  29299. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  29300. this._uniformBuffer.updateVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  29301. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  29302. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  29303. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  29304. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  29305. this._uniformBuffer.updateVector4("vOverloadedIntensity", this._overloadedIntensity);
  29306. this._uniformBuffer.updateColor3("vOverloadedAmbient", this.overloadedAmbient);
  29307. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  29308. this._uniformBuffer.updateColor3("vOverloadedAlbedo", this._tempColor);
  29309. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  29310. this._uniformBuffer.updateColor3("vOverloadedReflectivity", this._tempColor);
  29311. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  29312. this._uniformBuffer.updateColor3("vOverloadedEmissive", this._tempColor);
  29313. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  29314. this._uniformBuffer.updateColor3("vOverloadedReflection", this._tempColor);
  29315. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  29316. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  29317. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  29318. this._uniformBuffer.updateVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  29319. }
  29320. // Textures
  29321. if (this._myScene.texturesEnabled) {
  29322. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  29323. this._uniformBuffer.setTexture("albedoSampler", this.albedoTexture);
  29324. }
  29325. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  29326. this._uniformBuffer.setTexture("ambientSampler", this.ambientTexture);
  29327. }
  29328. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  29329. this._uniformBuffer.setTexture("opacitySampler", this.opacityTexture);
  29330. }
  29331. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  29332. if (this.reflectionTexture.isCube) {
  29333. this._uniformBuffer.setTexture("reflectionCubeSampler", this.reflectionTexture);
  29334. }
  29335. else {
  29336. this._uniformBuffer.setTexture("reflection2DSampler", this.reflectionTexture);
  29337. }
  29338. }
  29339. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  29340. this._uniformBuffer.setTexture("emissiveSampler", this.emissiveTexture);
  29341. }
  29342. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  29343. this._uniformBuffer.setTexture("lightmapSampler", this.lightmapTexture);
  29344. }
  29345. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  29346. if (this.metallicTexture) {
  29347. this._uniformBuffer.setTexture("reflectivitySampler", this.metallicTexture);
  29348. }
  29349. else if (this.reflectivityTexture) {
  29350. this._uniformBuffer.setTexture("reflectivitySampler", this.reflectivityTexture);
  29351. }
  29352. if (this.microSurfaceTexture) {
  29353. this._uniformBuffer.setTexture("microSurfaceSampler", this.microSurfaceTexture);
  29354. }
  29355. }
  29356. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  29357. this._uniformBuffer.setTexture("bumpSampler", this.bumpTexture);
  29358. }
  29359. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  29360. if (this.refractionTexture.isCube) {
  29361. this._uniformBuffer.setTexture("refractionCubeSampler", this.refractionTexture);
  29362. }
  29363. else {
  29364. this._uniformBuffer.setTexture("refraction2DSampler", this.refractionTexture);
  29365. }
  29366. }
  29367. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  29368. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  29369. }
  29370. }
  29371. // Clip plane
  29372. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  29373. // Colors
  29374. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  29375. effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  29376. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  29377. }
  29378. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  29379. // Lights
  29380. if (this._myScene.lightsEnabled && !this.disableLighting) {
  29381. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  29382. }
  29383. // View
  29384. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  29385. this.bindView(effect);
  29386. }
  29387. // Fog
  29388. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  29389. // Morph targets
  29390. if (this._defines.NUM_MORPH_INFLUENCERS) {
  29391. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  29392. }
  29393. this._cameraInfos.x = this.cameraExposure;
  29394. this._cameraInfos.y = this.cameraContrast;
  29395. effect.setVector4("vCameraInfos", this._cameraInfos);
  29396. if (this.cameraColorCurves) {
  29397. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  29398. }
  29399. // Log. depth
  29400. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  29401. }
  29402. this._uniformBuffer.update();
  29403. this._afterBind(mesh);
  29404. this._myScene = null;
  29405. };
  29406. PBRMaterial.prototype.getAnimatables = function () {
  29407. var results = [];
  29408. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  29409. results.push(this.albedoTexture);
  29410. }
  29411. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  29412. results.push(this.ambientTexture);
  29413. }
  29414. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  29415. results.push(this.opacityTexture);
  29416. }
  29417. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  29418. results.push(this.reflectionTexture);
  29419. }
  29420. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  29421. results.push(this.emissiveTexture);
  29422. }
  29423. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  29424. results.push(this.metallicTexture);
  29425. }
  29426. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  29427. results.push(this.reflectivityTexture);
  29428. }
  29429. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  29430. results.push(this.bumpTexture);
  29431. }
  29432. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  29433. results.push(this.lightmapTexture);
  29434. }
  29435. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  29436. results.push(this.refractionTexture);
  29437. }
  29438. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  29439. results.push(this.cameraColorGradingTexture);
  29440. }
  29441. return results;
  29442. };
  29443. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  29444. if (forceDisposeTextures) {
  29445. if (this.albedoTexture) {
  29446. this.albedoTexture.dispose();
  29447. }
  29448. if (this.ambientTexture) {
  29449. this.ambientTexture.dispose();
  29450. }
  29451. if (this.opacityTexture) {
  29452. this.opacityTexture.dispose();
  29453. }
  29454. if (this.reflectionTexture) {
  29455. this.reflectionTexture.dispose();
  29456. }
  29457. if (this.emissiveTexture) {
  29458. this.emissiveTexture.dispose();
  29459. }
  29460. if (this.metallicTexture) {
  29461. this.metallicTexture.dispose();
  29462. }
  29463. if (this.reflectivityTexture) {
  29464. this.reflectivityTexture.dispose();
  29465. }
  29466. if (this.bumpTexture) {
  29467. this.bumpTexture.dispose();
  29468. }
  29469. if (this.lightmapTexture) {
  29470. this.lightmapTexture.dispose();
  29471. }
  29472. if (this.refractionTexture) {
  29473. this.refractionTexture.dispose();
  29474. }
  29475. if (this.cameraColorGradingTexture) {
  29476. this.cameraColorGradingTexture.dispose();
  29477. }
  29478. }
  29479. this._renderTargets.dispose();
  29480. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  29481. };
  29482. PBRMaterial.prototype.clone = function (name) {
  29483. var _this = this;
  29484. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  29485. };
  29486. PBRMaterial.prototype.serialize = function () {
  29487. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29488. serializationObject.customType = "BABYLON.PBRMaterial";
  29489. return serializationObject;
  29490. };
  29491. // Statics
  29492. PBRMaterial.Parse = function (source, scene, rootUrl) {
  29493. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  29494. };
  29495. return PBRMaterial;
  29496. }(BABYLON.Material));
  29497. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  29498. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  29499. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  29500. PBRMaterial._scaledReflection = new BABYLON.Color3();
  29501. __decorate([
  29502. BABYLON.serialize()
  29503. ], PBRMaterial.prototype, "directIntensity", void 0);
  29504. __decorate([
  29505. BABYLON.serialize()
  29506. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  29507. __decorate([
  29508. BABYLON.serialize()
  29509. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  29510. __decorate([
  29511. BABYLON.serialize()
  29512. ], PBRMaterial.prototype, "specularIntensity", void 0);
  29513. __decorate([
  29514. BABYLON.serialize()
  29515. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  29516. __decorate([
  29517. BABYLON.serialize()
  29518. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  29519. __decorate([
  29520. BABYLON.serialize()
  29521. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  29522. __decorate([
  29523. BABYLON.serialize()
  29524. ], PBRMaterial.prototype, "cameraExposure", void 0);
  29525. __decorate([
  29526. BABYLON.serialize()
  29527. ], PBRMaterial.prototype, "cameraContrast", void 0);
  29528. __decorate([
  29529. BABYLON.serializeAsTexture()
  29530. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  29531. __decorate([
  29532. BABYLON.serializeAsColorCurves()
  29533. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  29534. __decorate([
  29535. BABYLON.serializeAsColor3()
  29536. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  29537. __decorate([
  29538. BABYLON.serialize()
  29539. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  29540. __decorate([
  29541. BABYLON.serializeAsColor3()
  29542. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  29543. __decorate([
  29544. BABYLON.serialize()
  29545. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  29546. __decorate([
  29547. BABYLON.serializeAsColor3()
  29548. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  29549. __decorate([
  29550. BABYLON.serialize()
  29551. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  29552. __decorate([
  29553. BABYLON.serializeAsColor3()
  29554. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  29555. __decorate([
  29556. BABYLON.serialize()
  29557. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  29558. __decorate([
  29559. BABYLON.serializeAsColor3()
  29560. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  29561. __decorate([
  29562. BABYLON.serialize()
  29563. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  29564. __decorate([
  29565. BABYLON.serialize()
  29566. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  29567. __decorate([
  29568. BABYLON.serialize()
  29569. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  29570. __decorate([
  29571. BABYLON.serializeAsTexture()
  29572. ], PBRMaterial.prototype, "albedoTexture", void 0);
  29573. __decorate([
  29574. BABYLON.serializeAsTexture()
  29575. ], PBRMaterial.prototype, "ambientTexture", void 0);
  29576. __decorate([
  29577. BABYLON.serialize()
  29578. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  29579. __decorate([
  29580. BABYLON.serializeAsTexture()
  29581. ], PBRMaterial.prototype, "opacityTexture", void 0);
  29582. __decorate([
  29583. BABYLON.serializeAsTexture()
  29584. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  29585. __decorate([
  29586. BABYLON.serializeAsTexture()
  29587. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  29588. __decorate([
  29589. BABYLON.serializeAsTexture()
  29590. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  29591. __decorate([
  29592. BABYLON.serializeAsTexture()
  29593. ], PBRMaterial.prototype, "metallicTexture", void 0);
  29594. __decorate([
  29595. BABYLON.serialize()
  29596. ], PBRMaterial.prototype, "metallic", void 0);
  29597. __decorate([
  29598. BABYLON.serialize()
  29599. ], PBRMaterial.prototype, "roughness", void 0);
  29600. __decorate([
  29601. BABYLON.serializeAsTexture()
  29602. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  29603. __decorate([
  29604. BABYLON.serializeAsTexture()
  29605. ], PBRMaterial.prototype, "bumpTexture", void 0);
  29606. __decorate([
  29607. BABYLON.serializeAsTexture()
  29608. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  29609. __decorate([
  29610. BABYLON.serializeAsTexture()
  29611. ], PBRMaterial.prototype, "refractionTexture", void 0);
  29612. __decorate([
  29613. BABYLON.serializeAsColor3("ambient")
  29614. ], PBRMaterial.prototype, "ambientColor", void 0);
  29615. __decorate([
  29616. BABYLON.serializeAsColor3("albedo")
  29617. ], PBRMaterial.prototype, "albedoColor", void 0);
  29618. __decorate([
  29619. BABYLON.serializeAsColor3("reflectivity")
  29620. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  29621. __decorate([
  29622. BABYLON.serializeAsColor3("reflection")
  29623. ], PBRMaterial.prototype, "reflectionColor", void 0);
  29624. __decorate([
  29625. BABYLON.serializeAsColor3("emissive")
  29626. ], PBRMaterial.prototype, "emissiveColor", void 0);
  29627. __decorate([
  29628. BABYLON.serialize()
  29629. ], PBRMaterial.prototype, "microSurface", void 0);
  29630. __decorate([
  29631. BABYLON.serialize()
  29632. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  29633. __decorate([
  29634. BABYLON.serialize()
  29635. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  29636. __decorate([
  29637. BABYLON.serializeAsFresnelParameters()
  29638. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  29639. __decorate([
  29640. BABYLON.serializeAsFresnelParameters()
  29641. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  29642. __decorate([
  29643. BABYLON.serialize()
  29644. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  29645. __decorate([
  29646. BABYLON.serialize()
  29647. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  29648. __decorate([
  29649. BABYLON.serialize()
  29650. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  29651. __decorate([
  29652. BABYLON.serialize()
  29653. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  29654. __decorate([
  29655. BABYLON.serialize()
  29656. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  29657. __decorate([
  29658. BABYLON.serialize()
  29659. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  29660. __decorate([
  29661. BABYLON.serialize()
  29662. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  29663. __decorate([
  29664. BABYLON.serialize()
  29665. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  29666. __decorate([
  29667. BABYLON.serialize()
  29668. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  29669. __decorate([
  29670. BABYLON.serialize()
  29671. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  29672. __decorate([
  29673. BABYLON.serialize()
  29674. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  29675. __decorate([
  29676. BABYLON.serialize()
  29677. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  29678. __decorate([
  29679. BABYLON.serialize()
  29680. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  29681. __decorate([
  29682. BABYLON.serialize()
  29683. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  29684. __decorate([
  29685. BABYLON.serialize()
  29686. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  29687. __decorate([
  29688. BABYLON.serialize()
  29689. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  29690. __decorate([
  29691. BABYLON.serialize()
  29692. ], PBRMaterial.prototype, "useParallax", void 0);
  29693. __decorate([
  29694. BABYLON.serialize()
  29695. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  29696. __decorate([
  29697. BABYLON.serialize()
  29698. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  29699. __decorate([
  29700. BABYLON.serialize()
  29701. ], PBRMaterial.prototype, "disableLighting", void 0);
  29702. __decorate([
  29703. BABYLON.serialize()
  29704. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  29705. __decorate([
  29706. BABYLON.serialize()
  29707. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  29708. __decorate([
  29709. BABYLON.serialize()
  29710. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  29711. __decorate([
  29712. BABYLON.serialize()
  29713. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  29714. __decorate([
  29715. BABYLON.serialize()
  29716. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  29717. BABYLON.PBRMaterial = PBRMaterial;
  29718. })(BABYLON || (BABYLON = {}));
  29719. //# sourceMappingURL=babylon.pbrMaterial.js.map
  29720. var BABYLON;
  29721. (function (BABYLON) {
  29722. BABYLON.CameraInputTypes = {};
  29723. var CameraInputsManager = (function () {
  29724. function CameraInputsManager(camera) {
  29725. this.attached = {};
  29726. this.camera = camera;
  29727. this.checkInputs = function () { };
  29728. }
  29729. CameraInputsManager.prototype.add = function (input) {
  29730. var type = input.getSimpleName();
  29731. if (this.attached[type]) {
  29732. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  29733. return;
  29734. }
  29735. this.attached[type] = input;
  29736. input.camera = this.camera;
  29737. //for checkInputs, we are dynamically creating a function
  29738. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  29739. if (input.checkInputs) {
  29740. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29741. }
  29742. if (this.attachedElement) {
  29743. input.attachControl(this.attachedElement);
  29744. }
  29745. };
  29746. CameraInputsManager.prototype.remove = function (inputToRemove) {
  29747. for (var cam in this.attached) {
  29748. var input = this.attached[cam];
  29749. if (input === inputToRemove) {
  29750. input.detachControl(this.attachedElement);
  29751. delete this.attached[cam];
  29752. this.rebuildInputCheck();
  29753. }
  29754. }
  29755. };
  29756. CameraInputsManager.prototype.removeByType = function (inputType) {
  29757. for (var cam in this.attached) {
  29758. var input = this.attached[cam];
  29759. if (input.getTypeName() === inputType) {
  29760. input.detachControl(this.attachedElement);
  29761. delete this.attached[cam];
  29762. this.rebuildInputCheck();
  29763. }
  29764. }
  29765. };
  29766. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  29767. var current = this.checkInputs;
  29768. return function () {
  29769. current();
  29770. fn();
  29771. };
  29772. };
  29773. CameraInputsManager.prototype.attachInput = function (input) {
  29774. input.attachControl(this.attachedElement, this.noPreventDefault);
  29775. };
  29776. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  29777. if (this.attachedElement) {
  29778. return;
  29779. }
  29780. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  29781. this.attachedElement = element;
  29782. this.noPreventDefault = noPreventDefault;
  29783. for (var cam in this.attached) {
  29784. var input = this.attached[cam];
  29785. this.attached[cam].attachControl(element, noPreventDefault);
  29786. }
  29787. };
  29788. CameraInputsManager.prototype.detachElement = function (element) {
  29789. if (this.attachedElement !== element) {
  29790. return;
  29791. }
  29792. for (var cam in this.attached) {
  29793. var input = this.attached[cam];
  29794. this.attached[cam].detachControl(element);
  29795. }
  29796. this.attachedElement = null;
  29797. };
  29798. CameraInputsManager.prototype.rebuildInputCheck = function () {
  29799. this.checkInputs = function () { };
  29800. for (var cam in this.attached) {
  29801. var input = this.attached[cam];
  29802. if (input.checkInputs) {
  29803. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  29804. }
  29805. }
  29806. };
  29807. CameraInputsManager.prototype.clear = function () {
  29808. if (this.attachedElement) {
  29809. this.detachElement(this.attachedElement);
  29810. }
  29811. this.attached = {};
  29812. this.attachedElement = null;
  29813. this.checkInputs = function () { };
  29814. };
  29815. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  29816. var inputs = {};
  29817. for (var cam in this.attached) {
  29818. var input = this.attached[cam];
  29819. var res = BABYLON.SerializationHelper.Serialize(input);
  29820. inputs[input.getTypeName()] = res;
  29821. }
  29822. serializedCamera.inputsmgr = inputs;
  29823. };
  29824. CameraInputsManager.prototype.parse = function (parsedCamera) {
  29825. var parsedInputs = parsedCamera.inputsmgr;
  29826. if (parsedInputs) {
  29827. this.clear();
  29828. for (var n in parsedInputs) {
  29829. var construct = BABYLON.CameraInputTypes[n];
  29830. if (construct) {
  29831. var parsedinput = parsedInputs[n];
  29832. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  29833. this.add(input);
  29834. }
  29835. }
  29836. }
  29837. else {
  29838. //2016-03-08 this part is for managing backward compatibility
  29839. for (var n in this.attached) {
  29840. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  29841. if (construct) {
  29842. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  29843. this.remove(this.attached[n]);
  29844. this.add(input);
  29845. }
  29846. }
  29847. }
  29848. };
  29849. return CameraInputsManager;
  29850. }());
  29851. BABYLON.CameraInputsManager = CameraInputsManager;
  29852. })(BABYLON || (BABYLON = {}));
  29853. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  29854. var BABYLON;
  29855. (function (BABYLON) {
  29856. var FreeCameraMouseInput = (function () {
  29857. function FreeCameraMouseInput(touchEnabled) {
  29858. if (touchEnabled === void 0) { touchEnabled = true; }
  29859. this.touchEnabled = touchEnabled;
  29860. this.buttons = [0, 1, 2];
  29861. this.angularSensibility = 2000.0;
  29862. }
  29863. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  29864. var _this = this;
  29865. var engine = this.camera.getEngine();
  29866. if (!this._pointerInput) {
  29867. this._pointerInput = function (p, s) {
  29868. var evt = p.event;
  29869. if (!_this.touchEnabled && evt.pointerType === "touch") {
  29870. return;
  29871. }
  29872. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  29873. return;
  29874. }
  29875. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  29876. try {
  29877. evt.srcElement.setPointerCapture(evt.pointerId);
  29878. }
  29879. catch (e) {
  29880. //Nothing to do with the error. Execution will continue.
  29881. }
  29882. _this.previousPosition = {
  29883. x: evt.clientX,
  29884. y: evt.clientY
  29885. };
  29886. if (!noPreventDefault) {
  29887. evt.preventDefault();
  29888. element.focus();
  29889. }
  29890. }
  29891. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  29892. try {
  29893. evt.srcElement.releasePointerCapture(evt.pointerId);
  29894. }
  29895. catch (e) {
  29896. //Nothing to do with the error.
  29897. }
  29898. _this.previousPosition = null;
  29899. if (!noPreventDefault) {
  29900. evt.preventDefault();
  29901. }
  29902. }
  29903. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  29904. if (!_this.previousPosition || engine.isPointerLock) {
  29905. return;
  29906. }
  29907. var offsetX = evt.clientX - _this.previousPosition.x;
  29908. var offsetY = evt.clientY - _this.previousPosition.y;
  29909. if (_this.camera.getScene().useRightHandedSystem) {
  29910. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  29911. }
  29912. else {
  29913. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  29914. }
  29915. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  29916. _this.previousPosition = {
  29917. x: evt.clientX,
  29918. y: evt.clientY
  29919. };
  29920. if (!noPreventDefault) {
  29921. evt.preventDefault();
  29922. }
  29923. }
  29924. };
  29925. }
  29926. this._onMouseMove = function (evt) {
  29927. if (!engine.isPointerLock) {
  29928. return;
  29929. }
  29930. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  29931. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  29932. if (_this.camera.getScene().useRightHandedSystem) {
  29933. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  29934. }
  29935. else {
  29936. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  29937. }
  29938. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  29939. _this.previousPosition = null;
  29940. if (!noPreventDefault) {
  29941. evt.preventDefault();
  29942. }
  29943. };
  29944. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  29945. element.addEventListener("mousemove", this._onMouseMove, false);
  29946. };
  29947. FreeCameraMouseInput.prototype.detachControl = function (element) {
  29948. if (this._observer && element) {
  29949. this.camera.getScene().onPointerObservable.remove(this._observer);
  29950. element.removeEventListener("mousemove", this._onMouseMove);
  29951. this._observer = null;
  29952. this._onMouseMove = null;
  29953. this.previousPosition = null;
  29954. }
  29955. };
  29956. FreeCameraMouseInput.prototype.getTypeName = function () {
  29957. return "FreeCameraMouseInput";
  29958. };
  29959. FreeCameraMouseInput.prototype.getSimpleName = function () {
  29960. return "mouse";
  29961. };
  29962. return FreeCameraMouseInput;
  29963. }());
  29964. __decorate([
  29965. BABYLON.serialize()
  29966. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  29967. __decorate([
  29968. BABYLON.serialize()
  29969. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  29970. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  29971. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  29972. })(BABYLON || (BABYLON = {}));
  29973. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  29974. var BABYLON;
  29975. (function (BABYLON) {
  29976. var FreeCameraKeyboardMoveInput = (function () {
  29977. function FreeCameraKeyboardMoveInput() {
  29978. this._keys = [];
  29979. this.keysUp = [38];
  29980. this.keysDown = [40];
  29981. this.keysLeft = [37];
  29982. this.keysRight = [39];
  29983. }
  29984. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  29985. var _this = this;
  29986. if (!this._onKeyDown) {
  29987. element.tabIndex = 1;
  29988. this._onKeyDown = function (evt) {
  29989. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  29990. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  29991. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  29992. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  29993. var index = _this._keys.indexOf(evt.keyCode);
  29994. if (index === -1) {
  29995. _this._keys.push(evt.keyCode);
  29996. }
  29997. if (!noPreventDefault) {
  29998. evt.preventDefault();
  29999. }
  30000. }
  30001. };
  30002. this._onKeyUp = function (evt) {
  30003. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30004. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30005. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30006. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30007. var index = _this._keys.indexOf(evt.keyCode);
  30008. if (index >= 0) {
  30009. _this._keys.splice(index, 1);
  30010. }
  30011. if (!noPreventDefault) {
  30012. evt.preventDefault();
  30013. }
  30014. }
  30015. };
  30016. element.addEventListener("keydown", this._onKeyDown, false);
  30017. element.addEventListener("keyup", this._onKeyUp, false);
  30018. BABYLON.Tools.RegisterTopRootEvents([
  30019. { name: "blur", handler: this._onLostFocus }
  30020. ]);
  30021. }
  30022. };
  30023. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  30024. if (this._onKeyDown) {
  30025. element.removeEventListener("keydown", this._onKeyDown);
  30026. element.removeEventListener("keyup", this._onKeyUp);
  30027. BABYLON.Tools.UnregisterTopRootEvents([
  30028. { name: "blur", handler: this._onLostFocus }
  30029. ]);
  30030. this._keys = [];
  30031. this._onKeyDown = null;
  30032. this._onKeyUp = null;
  30033. }
  30034. };
  30035. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  30036. if (this._onKeyDown) {
  30037. var camera = this.camera;
  30038. // Keyboard
  30039. for (var index = 0; index < this._keys.length; index++) {
  30040. var keyCode = this._keys[index];
  30041. var speed = camera._computeLocalCameraSpeed();
  30042. if (this.keysLeft.indexOf(keyCode) !== -1) {
  30043. camera._localDirection.copyFromFloats(-speed, 0, 0);
  30044. }
  30045. else if (this.keysUp.indexOf(keyCode) !== -1) {
  30046. camera._localDirection.copyFromFloats(0, 0, speed);
  30047. }
  30048. else if (this.keysRight.indexOf(keyCode) !== -1) {
  30049. camera._localDirection.copyFromFloats(speed, 0, 0);
  30050. }
  30051. else if (this.keysDown.indexOf(keyCode) !== -1) {
  30052. camera._localDirection.copyFromFloats(0, 0, -speed);
  30053. }
  30054. if (camera.getScene().useRightHandedSystem) {
  30055. camera._localDirection.z *= -1;
  30056. }
  30057. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  30058. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  30059. camera.cameraDirection.addInPlace(camera._transformedDirection);
  30060. }
  30061. }
  30062. };
  30063. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  30064. return "FreeCameraKeyboardMoveInput";
  30065. };
  30066. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  30067. this._keys = [];
  30068. };
  30069. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  30070. return "keyboard";
  30071. };
  30072. return FreeCameraKeyboardMoveInput;
  30073. }());
  30074. __decorate([
  30075. BABYLON.serialize()
  30076. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  30077. __decorate([
  30078. BABYLON.serialize()
  30079. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  30080. __decorate([
  30081. BABYLON.serialize()
  30082. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  30083. __decorate([
  30084. BABYLON.serialize()
  30085. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  30086. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  30087. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  30088. })(BABYLON || (BABYLON = {}));
  30089. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  30090. var BABYLON;
  30091. (function (BABYLON) {
  30092. var FreeCameraInputsManager = (function (_super) {
  30093. __extends(FreeCameraInputsManager, _super);
  30094. function FreeCameraInputsManager(camera) {
  30095. return _super.call(this, camera) || this;
  30096. }
  30097. FreeCameraInputsManager.prototype.addKeyboard = function () {
  30098. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  30099. return this;
  30100. };
  30101. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  30102. if (touchEnabled === void 0) { touchEnabled = true; }
  30103. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  30104. return this;
  30105. };
  30106. FreeCameraInputsManager.prototype.addGamepad = function () {
  30107. this.add(new BABYLON.FreeCameraGamepadInput());
  30108. return this;
  30109. };
  30110. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  30111. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  30112. return this;
  30113. };
  30114. FreeCameraInputsManager.prototype.addTouch = function () {
  30115. this.add(new BABYLON.FreeCameraTouchInput());
  30116. return this;
  30117. };
  30118. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  30119. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  30120. return this;
  30121. };
  30122. return FreeCameraInputsManager;
  30123. }(BABYLON.CameraInputsManager));
  30124. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  30125. })(BABYLON || (BABYLON = {}));
  30126. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  30127. /// <reference path="babylon.camera.ts" />
  30128. var BABYLON;
  30129. (function (BABYLON) {
  30130. var TargetCamera = (function (_super) {
  30131. __extends(TargetCamera, _super);
  30132. function TargetCamera(name, position, scene) {
  30133. var _this = _super.call(this, name, position, scene) || this;
  30134. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  30135. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  30136. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  30137. _this.speed = 2.0;
  30138. _this.noRotationConstraint = false;
  30139. _this.lockedTarget = null;
  30140. _this._currentTarget = BABYLON.Vector3.Zero();
  30141. _this._viewMatrix = BABYLON.Matrix.Zero();
  30142. _this._camMatrix = BABYLON.Matrix.Zero();
  30143. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  30144. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  30145. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  30146. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  30147. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  30148. _this._lookAtTemp = BABYLON.Matrix.Zero();
  30149. _this._tempMatrix = BABYLON.Matrix.Zero();
  30150. return _this;
  30151. }
  30152. TargetCamera.prototype.getFrontPosition = function (distance) {
  30153. var direction = this.getTarget().subtract(this.position);
  30154. direction.normalize();
  30155. direction.scaleInPlace(distance);
  30156. return this.globalPosition.add(direction);
  30157. };
  30158. TargetCamera.prototype._getLockedTargetPosition = function () {
  30159. if (!this.lockedTarget) {
  30160. return null;
  30161. }
  30162. if (this.lockedTarget.absolutePosition) {
  30163. this.lockedTarget.computeWorldMatrix();
  30164. }
  30165. return this.lockedTarget.absolutePosition || this.lockedTarget;
  30166. };
  30167. // Cache
  30168. TargetCamera.prototype._initCache = function () {
  30169. _super.prototype._initCache.call(this);
  30170. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30171. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30172. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  30173. };
  30174. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  30175. if (!ignoreParentClass) {
  30176. _super.prototype._updateCache.call(this);
  30177. }
  30178. var lockedTargetPosition = this._getLockedTargetPosition();
  30179. if (!lockedTargetPosition) {
  30180. this._cache.lockedTarget = null;
  30181. }
  30182. else {
  30183. if (!this._cache.lockedTarget) {
  30184. this._cache.lockedTarget = lockedTargetPosition.clone();
  30185. }
  30186. else {
  30187. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  30188. }
  30189. }
  30190. this._cache.rotation.copyFrom(this.rotation);
  30191. if (this.rotationQuaternion)
  30192. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30193. };
  30194. // Synchronized
  30195. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  30196. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  30197. return false;
  30198. }
  30199. var lockedTargetPosition = this._getLockedTargetPosition();
  30200. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  30201. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  30202. };
  30203. // Methods
  30204. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  30205. var engine = this.getEngine();
  30206. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  30207. };
  30208. // Target
  30209. TargetCamera.prototype.setTarget = function (target) {
  30210. this.upVector.normalize();
  30211. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  30212. this._camMatrix.invert();
  30213. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  30214. var vDir = target.subtract(this.position);
  30215. if (vDir.x >= 0.0) {
  30216. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  30217. }
  30218. else {
  30219. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  30220. }
  30221. this.rotation.z = 0;
  30222. if (isNaN(this.rotation.x)) {
  30223. this.rotation.x = 0;
  30224. }
  30225. if (isNaN(this.rotation.y)) {
  30226. this.rotation.y = 0;
  30227. }
  30228. if (isNaN(this.rotation.z)) {
  30229. this.rotation.z = 0;
  30230. }
  30231. if (this.rotationQuaternion) {
  30232. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  30233. }
  30234. };
  30235. /**
  30236. * Return the current target position of the camera. This value is expressed in local space.
  30237. */
  30238. TargetCamera.prototype.getTarget = function () {
  30239. return this._currentTarget;
  30240. };
  30241. TargetCamera.prototype._decideIfNeedsToMove = function () {
  30242. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  30243. };
  30244. TargetCamera.prototype._updatePosition = function () {
  30245. if (this.parent) {
  30246. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  30247. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  30248. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  30249. return;
  30250. }
  30251. this.position.addInPlace(this.cameraDirection);
  30252. };
  30253. TargetCamera.prototype._checkInputs = function () {
  30254. var needToMove = this._decideIfNeedsToMove();
  30255. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  30256. // Move
  30257. if (needToMove) {
  30258. this._updatePosition();
  30259. }
  30260. // Rotate
  30261. if (needToRotate) {
  30262. this.rotation.x += this.cameraRotation.x;
  30263. this.rotation.y += this.cameraRotation.y;
  30264. //rotate, if quaternion is set and rotation was used
  30265. if (this.rotationQuaternion) {
  30266. var len = this.rotation.lengthSquared();
  30267. if (len) {
  30268. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  30269. }
  30270. }
  30271. if (!this.noRotationConstraint) {
  30272. var limit = (Math.PI / 2) * 0.95;
  30273. if (this.rotation.x > limit)
  30274. this.rotation.x = limit;
  30275. if (this.rotation.x < -limit)
  30276. this.rotation.x = -limit;
  30277. }
  30278. }
  30279. // Inertia
  30280. if (needToMove) {
  30281. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  30282. this.cameraDirection.x = 0;
  30283. }
  30284. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  30285. this.cameraDirection.y = 0;
  30286. }
  30287. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  30288. this.cameraDirection.z = 0;
  30289. }
  30290. this.cameraDirection.scaleInPlace(this.inertia);
  30291. }
  30292. if (needToRotate) {
  30293. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  30294. this.cameraRotation.x = 0;
  30295. }
  30296. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  30297. this.cameraRotation.y = 0;
  30298. }
  30299. this.cameraRotation.scaleInPlace(this.inertia);
  30300. }
  30301. _super.prototype._checkInputs.call(this);
  30302. };
  30303. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  30304. if (this.rotationQuaternion) {
  30305. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  30306. //update the up vector!
  30307. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  30308. }
  30309. else {
  30310. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  30311. }
  30312. };
  30313. TargetCamera.prototype._getViewMatrix = function () {
  30314. if (!this.lockedTarget) {
  30315. // Compute
  30316. this._updateCameraRotationMatrix();
  30317. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  30318. // Computing target and final matrix
  30319. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  30320. }
  30321. else {
  30322. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  30323. }
  30324. if (this.getScene().useRightHandedSystem) {
  30325. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  30326. }
  30327. else {
  30328. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  30329. }
  30330. return this._viewMatrix;
  30331. };
  30332. /**
  30333. * @override
  30334. * Override Camera.createRigCamera
  30335. */
  30336. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  30337. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  30338. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  30339. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  30340. if (!this.rotationQuaternion) {
  30341. this.rotationQuaternion = new BABYLON.Quaternion();
  30342. }
  30343. rigCamera._cameraRigParams = {};
  30344. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  30345. }
  30346. return rigCamera;
  30347. }
  30348. return null;
  30349. };
  30350. /**
  30351. * @override
  30352. * Override Camera._updateRigCameras
  30353. */
  30354. TargetCamera.prototype._updateRigCameras = function () {
  30355. var camLeft = this._rigCameras[0];
  30356. var camRight = this._rigCameras[1];
  30357. switch (this.cameraRigMode) {
  30358. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  30359. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  30360. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  30361. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  30362. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  30363. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  30364. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  30365. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  30366. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  30367. camLeft.setTarget(this.getTarget());
  30368. camRight.setTarget(this.getTarget());
  30369. break;
  30370. case BABYLON.Camera.RIG_MODE_VR:
  30371. if (camLeft.rotationQuaternion) {
  30372. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30373. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  30374. }
  30375. else {
  30376. camLeft.rotation.copyFrom(this.rotation);
  30377. camRight.rotation.copyFrom(this.rotation);
  30378. }
  30379. camLeft.position.copyFrom(this.position);
  30380. camRight.position.copyFrom(this.position);
  30381. break;
  30382. }
  30383. _super.prototype._updateRigCameras.call(this);
  30384. };
  30385. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  30386. if (!this._rigCamTransformMatrix) {
  30387. this._rigCamTransformMatrix = new BABYLON.Matrix();
  30388. }
  30389. var target = this.getTarget();
  30390. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  30391. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  30392. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  30393. };
  30394. TargetCamera.prototype.getClassName = function () {
  30395. return "TargetCamera";
  30396. };
  30397. return TargetCamera;
  30398. }(BABYLON.Camera));
  30399. __decorate([
  30400. BABYLON.serializeAsVector3()
  30401. ], TargetCamera.prototype, "rotation", void 0);
  30402. __decorate([
  30403. BABYLON.serialize()
  30404. ], TargetCamera.prototype, "speed", void 0);
  30405. __decorate([
  30406. BABYLON.serializeAsMeshReference("lockedTargetId")
  30407. ], TargetCamera.prototype, "lockedTarget", void 0);
  30408. BABYLON.TargetCamera = TargetCamera;
  30409. })(BABYLON || (BABYLON = {}));
  30410. //# sourceMappingURL=babylon.targetCamera.js.map
  30411. var BABYLON;
  30412. (function (BABYLON) {
  30413. var FreeCamera = (function (_super) {
  30414. __extends(FreeCamera, _super);
  30415. function FreeCamera(name, position, scene) {
  30416. var _this = _super.call(this, name, position, scene) || this;
  30417. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  30418. _this.checkCollisions = false;
  30419. _this.applyGravity = false;
  30420. _this._needMoveForGravity = false;
  30421. _this._oldPosition = BABYLON.Vector3.Zero();
  30422. _this._diffPosition = BABYLON.Vector3.Zero();
  30423. _this._newPosition = BABYLON.Vector3.Zero();
  30424. // Collisions
  30425. _this._collisionMask = -1;
  30426. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  30427. if (collidedMesh === void 0) { collidedMesh = null; }
  30428. //TODO move this to the collision coordinator!
  30429. if (_this.getScene().workerCollisions)
  30430. newPosition.multiplyInPlace(_this._collider.radius);
  30431. var updatePosition = function (newPos) {
  30432. _this._newPosition.copyFrom(newPos);
  30433. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  30434. var oldPosition = _this.position.clone();
  30435. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  30436. _this.position.addInPlace(_this._diffPosition);
  30437. if (_this.onCollide && collidedMesh) {
  30438. _this.onCollide(collidedMesh);
  30439. }
  30440. }
  30441. };
  30442. updatePosition(newPosition);
  30443. };
  30444. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  30445. _this.inputs.addKeyboard().addMouse();
  30446. return _this;
  30447. }
  30448. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  30449. //-- begin properties for backward compatibility for inputs
  30450. get: function () {
  30451. var mouse = this.inputs.attached["mouse"];
  30452. if (mouse)
  30453. return mouse.angularSensibility;
  30454. },
  30455. set: function (value) {
  30456. var mouse = this.inputs.attached["mouse"];
  30457. if (mouse)
  30458. mouse.angularSensibility = value;
  30459. },
  30460. enumerable: true,
  30461. configurable: true
  30462. });
  30463. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  30464. get: function () {
  30465. var keyboard = this.inputs.attached["keyboard"];
  30466. if (keyboard)
  30467. return keyboard.keysUp;
  30468. },
  30469. set: function (value) {
  30470. var keyboard = this.inputs.attached["keyboard"];
  30471. if (keyboard)
  30472. keyboard.keysUp = value;
  30473. },
  30474. enumerable: true,
  30475. configurable: true
  30476. });
  30477. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  30478. get: function () {
  30479. var keyboard = this.inputs.attached["keyboard"];
  30480. if (keyboard)
  30481. return keyboard.keysDown;
  30482. },
  30483. set: function (value) {
  30484. var keyboard = this.inputs.attached["keyboard"];
  30485. if (keyboard)
  30486. keyboard.keysDown = value;
  30487. },
  30488. enumerable: true,
  30489. configurable: true
  30490. });
  30491. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  30492. get: function () {
  30493. var keyboard = this.inputs.attached["keyboard"];
  30494. if (keyboard)
  30495. return keyboard.keysLeft;
  30496. },
  30497. set: function (value) {
  30498. var keyboard = this.inputs.attached["keyboard"];
  30499. if (keyboard)
  30500. keyboard.keysLeft = value;
  30501. },
  30502. enumerable: true,
  30503. configurable: true
  30504. });
  30505. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  30506. get: function () {
  30507. var keyboard = this.inputs.attached["keyboard"];
  30508. if (keyboard)
  30509. return keyboard.keysRight;
  30510. },
  30511. set: function (value) {
  30512. var keyboard = this.inputs.attached["keyboard"];
  30513. if (keyboard)
  30514. keyboard.keysRight = value;
  30515. },
  30516. enumerable: true,
  30517. configurable: true
  30518. });
  30519. // Controls
  30520. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  30521. this.inputs.attachElement(element, noPreventDefault);
  30522. };
  30523. FreeCamera.prototype.detachControl = function (element) {
  30524. this.inputs.detachElement(element);
  30525. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  30526. this.cameraRotation = new BABYLON.Vector2(0, 0);
  30527. };
  30528. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  30529. get: function () {
  30530. return this._collisionMask;
  30531. },
  30532. set: function (mask) {
  30533. this._collisionMask = !isNaN(mask) ? mask : -1;
  30534. },
  30535. enumerable: true,
  30536. configurable: true
  30537. });
  30538. FreeCamera.prototype._collideWithWorld = function (velocity) {
  30539. var globalPosition;
  30540. if (this.parent) {
  30541. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  30542. }
  30543. else {
  30544. globalPosition = this.position;
  30545. }
  30546. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  30547. if (!this._collider) {
  30548. this._collider = new BABYLON.Collider();
  30549. }
  30550. this._collider.radius = this.ellipsoid;
  30551. this._collider.collisionMask = this._collisionMask;
  30552. //no need for clone, as long as gravity is not on.
  30553. var actualVelocity = velocity;
  30554. //add gravity to the velocity to prevent the dual-collision checking
  30555. if (this.applyGravity) {
  30556. //this prevents mending with cameraDirection, a global variable of the free camera class.
  30557. actualVelocity = velocity.add(this.getScene().gravity);
  30558. }
  30559. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  30560. };
  30561. FreeCamera.prototype._checkInputs = function () {
  30562. if (!this._localDirection) {
  30563. this._localDirection = BABYLON.Vector3.Zero();
  30564. this._transformedDirection = BABYLON.Vector3.Zero();
  30565. }
  30566. this.inputs.checkInputs();
  30567. _super.prototype._checkInputs.call(this);
  30568. };
  30569. FreeCamera.prototype._decideIfNeedsToMove = function () {
  30570. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  30571. };
  30572. FreeCamera.prototype._updatePosition = function () {
  30573. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  30574. this._collideWithWorld(this.cameraDirection);
  30575. }
  30576. else {
  30577. _super.prototype._updatePosition.call(this);
  30578. }
  30579. };
  30580. FreeCamera.prototype.dispose = function () {
  30581. this.inputs.clear();
  30582. _super.prototype.dispose.call(this);
  30583. };
  30584. FreeCamera.prototype.getClassName = function () {
  30585. return "FreeCamera";
  30586. };
  30587. return FreeCamera;
  30588. }(BABYLON.TargetCamera));
  30589. __decorate([
  30590. BABYLON.serializeAsVector3()
  30591. ], FreeCamera.prototype, "ellipsoid", void 0);
  30592. __decorate([
  30593. BABYLON.serialize()
  30594. ], FreeCamera.prototype, "checkCollisions", void 0);
  30595. __decorate([
  30596. BABYLON.serialize()
  30597. ], FreeCamera.prototype, "applyGravity", void 0);
  30598. BABYLON.FreeCamera = FreeCamera;
  30599. })(BABYLON || (BABYLON = {}));
  30600. //# sourceMappingURL=babylon.freeCamera.js.map
  30601. var BABYLON;
  30602. (function (BABYLON) {
  30603. var ArcRotateCameraKeyboardMoveInput = (function () {
  30604. function ArcRotateCameraKeyboardMoveInput() {
  30605. this._keys = [];
  30606. this.keysUp = [38];
  30607. this.keysDown = [40];
  30608. this.keysLeft = [37];
  30609. this.keysRight = [39];
  30610. }
  30611. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  30612. var _this = this;
  30613. element.tabIndex = 1;
  30614. this._onKeyDown = function (evt) {
  30615. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30616. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30617. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30618. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30619. var index = _this._keys.indexOf(evt.keyCode);
  30620. if (index === -1) {
  30621. _this._keys.push(evt.keyCode);
  30622. }
  30623. if (evt.preventDefault) {
  30624. if (!noPreventDefault) {
  30625. evt.preventDefault();
  30626. }
  30627. }
  30628. }
  30629. };
  30630. this._onKeyUp = function (evt) {
  30631. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  30632. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  30633. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  30634. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  30635. var index = _this._keys.indexOf(evt.keyCode);
  30636. if (index >= 0) {
  30637. _this._keys.splice(index, 1);
  30638. }
  30639. if (evt.preventDefault) {
  30640. if (!noPreventDefault) {
  30641. evt.preventDefault();
  30642. }
  30643. }
  30644. }
  30645. };
  30646. this._onLostFocus = function () {
  30647. _this._keys = [];
  30648. };
  30649. element.addEventListener("keydown", this._onKeyDown, false);
  30650. element.addEventListener("keyup", this._onKeyUp, false);
  30651. BABYLON.Tools.RegisterTopRootEvents([
  30652. { name: "blur", handler: this._onLostFocus }
  30653. ]);
  30654. };
  30655. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  30656. if (element) {
  30657. element.removeEventListener("keydown", this._onKeyDown);
  30658. element.removeEventListener("keyup", this._onKeyUp);
  30659. }
  30660. BABYLON.Tools.UnregisterTopRootEvents([
  30661. { name: "blur", handler: this._onLostFocus }
  30662. ]);
  30663. this._keys = [];
  30664. this._onKeyDown = null;
  30665. this._onKeyUp = null;
  30666. this._onLostFocus = null;
  30667. };
  30668. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  30669. if (this._onKeyDown) {
  30670. var camera = this.camera;
  30671. for (var index = 0; index < this._keys.length; index++) {
  30672. var keyCode = this._keys[index];
  30673. if (this.keysLeft.indexOf(keyCode) !== -1) {
  30674. camera.inertialAlphaOffset -= 0.01;
  30675. }
  30676. else if (this.keysUp.indexOf(keyCode) !== -1) {
  30677. camera.inertialBetaOffset -= 0.01;
  30678. }
  30679. else if (this.keysRight.indexOf(keyCode) !== -1) {
  30680. camera.inertialAlphaOffset += 0.01;
  30681. }
  30682. else if (this.keysDown.indexOf(keyCode) !== -1) {
  30683. camera.inertialBetaOffset += 0.01;
  30684. }
  30685. }
  30686. }
  30687. };
  30688. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  30689. return "ArcRotateCameraKeyboardMoveInput";
  30690. };
  30691. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  30692. return "keyboard";
  30693. };
  30694. return ArcRotateCameraKeyboardMoveInput;
  30695. }());
  30696. __decorate([
  30697. BABYLON.serialize()
  30698. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  30699. __decorate([
  30700. BABYLON.serialize()
  30701. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  30702. __decorate([
  30703. BABYLON.serialize()
  30704. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  30705. __decorate([
  30706. BABYLON.serialize()
  30707. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  30708. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  30709. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  30710. })(BABYLON || (BABYLON = {}));
  30711. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  30712. var BABYLON;
  30713. (function (BABYLON) {
  30714. var ArcRotateCameraMouseWheelInput = (function () {
  30715. function ArcRotateCameraMouseWheelInput() {
  30716. this.wheelPrecision = 3.0;
  30717. }
  30718. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  30719. var _this = this;
  30720. this._wheel = function (p, s) {
  30721. //sanity check - this should be a PointerWheel event.
  30722. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  30723. return;
  30724. var event = p.event;
  30725. var delta = 0;
  30726. if (event.wheelDelta) {
  30727. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  30728. }
  30729. else if (event.detail) {
  30730. delta = -event.detail / _this.wheelPrecision;
  30731. }
  30732. if (delta)
  30733. _this.camera.inertialRadiusOffset += delta;
  30734. if (event.preventDefault) {
  30735. if (!noPreventDefault) {
  30736. event.preventDefault();
  30737. }
  30738. }
  30739. };
  30740. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  30741. };
  30742. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  30743. if (this._observer && element) {
  30744. this.camera.getScene().onPointerObservable.remove(this._observer);
  30745. this._observer = null;
  30746. this._wheel = null;
  30747. }
  30748. };
  30749. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  30750. return "ArcRotateCameraMouseWheelInput";
  30751. };
  30752. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  30753. return "mousewheel";
  30754. };
  30755. return ArcRotateCameraMouseWheelInput;
  30756. }());
  30757. __decorate([
  30758. BABYLON.serialize()
  30759. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  30760. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  30761. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  30762. })(BABYLON || (BABYLON = {}));
  30763. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  30764. var BABYLON;
  30765. (function (BABYLON) {
  30766. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  30767. var ArcRotateCameraPointersInput = (function () {
  30768. function ArcRotateCameraPointersInput() {
  30769. this.buttons = [0, 1, 2];
  30770. this.angularSensibilityX = 1000.0;
  30771. this.angularSensibilityY = 1000.0;
  30772. this.pinchPrecision = 6.0;
  30773. this.panningSensibility = 50.0;
  30774. this._isPanClick = false;
  30775. this.pinchInwards = true;
  30776. }
  30777. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  30778. var _this = this;
  30779. var engine = this.camera.getEngine();
  30780. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  30781. var pointA, pointB;
  30782. var previousPinchDistance = 0;
  30783. this._pointerInput = function (p, s) {
  30784. var evt = p.event;
  30785. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  30786. return;
  30787. }
  30788. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  30789. try {
  30790. evt.srcElement.setPointerCapture(evt.pointerId);
  30791. }
  30792. catch (e) {
  30793. //Nothing to do with the error. Execution will continue.
  30794. }
  30795. // Manage panning with pan button click
  30796. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  30797. // manage pointers
  30798. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  30799. if (pointA === undefined) {
  30800. pointA = cacheSoloPointer;
  30801. }
  30802. else if (pointB === undefined) {
  30803. pointB = cacheSoloPointer;
  30804. }
  30805. if (!noPreventDefault) {
  30806. evt.preventDefault();
  30807. element.focus();
  30808. }
  30809. }
  30810. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  30811. try {
  30812. evt.srcElement.releasePointerCapture(evt.pointerId);
  30813. }
  30814. catch (e) {
  30815. //Nothing to do with the error.
  30816. }
  30817. cacheSoloPointer = null;
  30818. previousPinchDistance = 0;
  30819. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  30820. //but emptying completly pointers collection is required to fix a bug on iPhone :
  30821. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  30822. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  30823. pointA = pointB = undefined;
  30824. if (!noPreventDefault) {
  30825. evt.preventDefault();
  30826. }
  30827. }
  30828. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  30829. if (!noPreventDefault) {
  30830. evt.preventDefault();
  30831. }
  30832. // One button down
  30833. if (pointA && pointB === undefined) {
  30834. if (_this.panningSensibility !== 0 &&
  30835. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  30836. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  30837. _this.camera
  30838. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  30839. _this.camera
  30840. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  30841. }
  30842. else {
  30843. var offsetX = evt.clientX - cacheSoloPointer.x;
  30844. var offsetY = evt.clientY - cacheSoloPointer.y;
  30845. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30846. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30847. }
  30848. cacheSoloPointer.x = evt.clientX;
  30849. cacheSoloPointer.y = evt.clientY;
  30850. }
  30851. else if (pointA && pointB) {
  30852. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  30853. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  30854. ed.x = evt.clientX;
  30855. ed.y = evt.clientY;
  30856. var direction = _this.pinchInwards ? 1 : -1;
  30857. var distX = pointA.x - pointB.x;
  30858. var distY = pointA.y - pointB.y;
  30859. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  30860. if (previousPinchDistance === 0) {
  30861. previousPinchDistance = pinchSquaredDistance;
  30862. return;
  30863. }
  30864. if (pinchSquaredDistance !== previousPinchDistance) {
  30865. _this.camera
  30866. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  30867. (_this.pinchPrecision *
  30868. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  30869. direction);
  30870. previousPinchDistance = pinchSquaredDistance;
  30871. }
  30872. }
  30873. }
  30874. };
  30875. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  30876. this._onContextMenu = function (evt) {
  30877. evt.preventDefault();
  30878. };
  30879. if (!this.camera._useCtrlForPanning) {
  30880. element.addEventListener("contextmenu", this._onContextMenu, false);
  30881. }
  30882. this._onLostFocus = function () {
  30883. //this._keys = [];
  30884. pointA = pointB = undefined;
  30885. previousPinchDistance = 0;
  30886. cacheSoloPointer = null;
  30887. };
  30888. this._onMouseMove = function (evt) {
  30889. if (!engine.isPointerLock) {
  30890. return;
  30891. }
  30892. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  30893. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  30894. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  30895. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  30896. if (!noPreventDefault) {
  30897. evt.preventDefault();
  30898. }
  30899. };
  30900. this._onGestureStart = function (e) {
  30901. if (window.MSGesture === undefined) {
  30902. return;
  30903. }
  30904. if (!_this._MSGestureHandler) {
  30905. _this._MSGestureHandler = new MSGesture();
  30906. _this._MSGestureHandler.target = element;
  30907. }
  30908. _this._MSGestureHandler.addPointer(e.pointerId);
  30909. };
  30910. this._onGesture = function (e) {
  30911. _this.camera.radius *= e.scale;
  30912. if (e.preventDefault) {
  30913. if (!noPreventDefault) {
  30914. e.stopPropagation();
  30915. e.preventDefault();
  30916. }
  30917. }
  30918. };
  30919. element.addEventListener("mousemove", this._onMouseMove, false);
  30920. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  30921. element.addEventListener("MSGestureChange", this._onGesture, false);
  30922. element.addEventListener("keydown", this._onKeyDown, false);
  30923. element.addEventListener("keyup", this._onKeyUp, false);
  30924. BABYLON.Tools.RegisterTopRootEvents([
  30925. { name: "blur", handler: this._onLostFocus }
  30926. ]);
  30927. };
  30928. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  30929. if (element && this._observer) {
  30930. this.camera.getScene().onPointerObservable.remove(this._observer);
  30931. this._observer = null;
  30932. element.removeEventListener("contextmenu", this._onContextMenu);
  30933. element.removeEventListener("mousemove", this._onMouseMove);
  30934. element.removeEventListener("MSPointerDown", this._onGestureStart);
  30935. element.removeEventListener("MSGestureChange", this._onGesture);
  30936. element.removeEventListener("keydown", this._onKeyDown);
  30937. element.removeEventListener("keyup", this._onKeyUp);
  30938. this._isPanClick = false;
  30939. this.pinchInwards = true;
  30940. this._onKeyDown = null;
  30941. this._onKeyUp = null;
  30942. this._onMouseMove = null;
  30943. this._onGestureStart = null;
  30944. this._onGesture = null;
  30945. this._MSGestureHandler = null;
  30946. this._onLostFocus = null;
  30947. this._onContextMenu = null;
  30948. }
  30949. BABYLON.Tools.UnregisterTopRootEvents([
  30950. { name: "blur", handler: this._onLostFocus }
  30951. ]);
  30952. };
  30953. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  30954. return "ArcRotateCameraPointersInput";
  30955. };
  30956. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  30957. return "pointers";
  30958. };
  30959. return ArcRotateCameraPointersInput;
  30960. }());
  30961. __decorate([
  30962. BABYLON.serialize()
  30963. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  30964. __decorate([
  30965. BABYLON.serialize()
  30966. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  30967. __decorate([
  30968. BABYLON.serialize()
  30969. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  30970. __decorate([
  30971. BABYLON.serialize()
  30972. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  30973. __decorate([
  30974. BABYLON.serialize()
  30975. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  30976. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  30977. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  30978. })(BABYLON || (BABYLON = {}));
  30979. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  30980. /// <reference path="babylon.targetCamera.ts" />
  30981. /// <reference path="..\Tools\babylon.tools.ts" />
  30982. var BABYLON;
  30983. (function (BABYLON) {
  30984. var ArcRotateCamera = (function (_super) {
  30985. __extends(ArcRotateCamera, _super);
  30986. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  30987. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  30988. _this.inertialAlphaOffset = 0;
  30989. _this.inertialBetaOffset = 0;
  30990. _this.inertialRadiusOffset = 0;
  30991. _this.lowerAlphaLimit = null;
  30992. _this.upperAlphaLimit = null;
  30993. _this.lowerBetaLimit = 0.01;
  30994. _this.upperBetaLimit = Math.PI;
  30995. _this.lowerRadiusLimit = null;
  30996. _this.upperRadiusLimit = null;
  30997. _this.inertialPanningX = 0;
  30998. _this.inertialPanningY = 0;
  30999. //-- end properties for backward compatibility for inputs
  31000. _this.zoomOnFactor = 1;
  31001. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  31002. _this.allowUpsideDown = true;
  31003. _this._viewMatrix = new BABYLON.Matrix();
  31004. // Panning
  31005. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  31006. _this.checkCollisions = false;
  31007. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  31008. _this._previousPosition = BABYLON.Vector3.Zero();
  31009. _this._collisionVelocity = BABYLON.Vector3.Zero();
  31010. _this._newPosition = BABYLON.Vector3.Zero();
  31011. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  31012. if (collidedMesh === void 0) { collidedMesh = null; }
  31013. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  31014. newPosition.multiplyInPlace(_this._collider.radius);
  31015. }
  31016. if (!collidedMesh) {
  31017. _this._previousPosition.copyFrom(_this.position);
  31018. }
  31019. else {
  31020. _this.setPosition(newPosition);
  31021. if (_this.onCollide) {
  31022. _this.onCollide(collidedMesh);
  31023. }
  31024. }
  31025. // Recompute because of constraints
  31026. var cosa = Math.cos(_this.alpha);
  31027. var sina = Math.sin(_this.alpha);
  31028. var cosb = Math.cos(_this.beta);
  31029. var sinb = Math.sin(_this.beta);
  31030. if (sinb === 0) {
  31031. sinb = 0.0001;
  31032. }
  31033. var target = _this._getTargetPosition();
  31034. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  31035. _this.position.copyFrom(_this._newPosition);
  31036. var up = _this.upVector;
  31037. if (_this.allowUpsideDown && _this.beta < 0) {
  31038. up = up.clone();
  31039. up = up.negate();
  31040. }
  31041. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  31042. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  31043. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  31044. _this._collisionTriggered = false;
  31045. };
  31046. if (!target) {
  31047. _this._target = BABYLON.Vector3.Zero();
  31048. }
  31049. else {
  31050. _this.setTarget(target);
  31051. }
  31052. _this.alpha = alpha;
  31053. _this.beta = beta;
  31054. _this.radius = radius;
  31055. _this.getViewMatrix();
  31056. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  31057. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  31058. return _this;
  31059. }
  31060. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  31061. get: function () {
  31062. return this._target;
  31063. },
  31064. set: function (value) {
  31065. this.setTarget(value);
  31066. },
  31067. enumerable: true,
  31068. configurable: true
  31069. });
  31070. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  31071. //-- begin properties for backward compatibility for inputs
  31072. get: function () {
  31073. var pointers = this.inputs.attached["pointers"];
  31074. if (pointers)
  31075. return pointers.angularSensibilityX;
  31076. },
  31077. set: function (value) {
  31078. var pointers = this.inputs.attached["pointers"];
  31079. if (pointers) {
  31080. pointers.angularSensibilityX = value;
  31081. }
  31082. },
  31083. enumerable: true,
  31084. configurable: true
  31085. });
  31086. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  31087. get: function () {
  31088. var pointers = this.inputs.attached["pointers"];
  31089. if (pointers)
  31090. return pointers.angularSensibilityY;
  31091. },
  31092. set: function (value) {
  31093. var pointers = this.inputs.attached["pointers"];
  31094. if (pointers) {
  31095. pointers.angularSensibilityY = value;
  31096. }
  31097. },
  31098. enumerable: true,
  31099. configurable: true
  31100. });
  31101. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  31102. get: function () {
  31103. var pointers = this.inputs.attached["pointers"];
  31104. if (pointers)
  31105. return pointers.pinchPrecision;
  31106. },
  31107. set: function (value) {
  31108. var pointers = this.inputs.attached["pointers"];
  31109. if (pointers) {
  31110. pointers.pinchPrecision = value;
  31111. }
  31112. },
  31113. enumerable: true,
  31114. configurable: true
  31115. });
  31116. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  31117. get: function () {
  31118. var pointers = this.inputs.attached["pointers"];
  31119. if (pointers)
  31120. return pointers.panningSensibility;
  31121. },
  31122. set: function (value) {
  31123. var pointers = this.inputs.attached["pointers"];
  31124. if (pointers) {
  31125. pointers.panningSensibility = value;
  31126. }
  31127. },
  31128. enumerable: true,
  31129. configurable: true
  31130. });
  31131. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  31132. get: function () {
  31133. var keyboard = this.inputs.attached["keyboard"];
  31134. if (keyboard)
  31135. return keyboard.keysUp;
  31136. },
  31137. set: function (value) {
  31138. var keyboard = this.inputs.attached["keyboard"];
  31139. if (keyboard)
  31140. keyboard.keysUp = value;
  31141. },
  31142. enumerable: true,
  31143. configurable: true
  31144. });
  31145. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  31146. get: function () {
  31147. var keyboard = this.inputs.attached["keyboard"];
  31148. if (keyboard)
  31149. return keyboard.keysDown;
  31150. },
  31151. set: function (value) {
  31152. var keyboard = this.inputs.attached["keyboard"];
  31153. if (keyboard)
  31154. keyboard.keysDown = value;
  31155. },
  31156. enumerable: true,
  31157. configurable: true
  31158. });
  31159. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  31160. get: function () {
  31161. var keyboard = this.inputs.attached["keyboard"];
  31162. if (keyboard)
  31163. return keyboard.keysLeft;
  31164. },
  31165. set: function (value) {
  31166. var keyboard = this.inputs.attached["keyboard"];
  31167. if (keyboard)
  31168. keyboard.keysLeft = value;
  31169. },
  31170. enumerable: true,
  31171. configurable: true
  31172. });
  31173. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  31174. get: function () {
  31175. var keyboard = this.inputs.attached["keyboard"];
  31176. if (keyboard)
  31177. return keyboard.keysRight;
  31178. },
  31179. set: function (value) {
  31180. var keyboard = this.inputs.attached["keyboard"];
  31181. if (keyboard)
  31182. keyboard.keysRight = value;
  31183. },
  31184. enumerable: true,
  31185. configurable: true
  31186. });
  31187. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  31188. get: function () {
  31189. var mousewheel = this.inputs.attached["mousewheel"];
  31190. if (mousewheel)
  31191. return mousewheel.wheelPrecision;
  31192. },
  31193. set: function (value) {
  31194. var mousewheel = this.inputs.attached["mousewheel"];
  31195. if (mousewheel)
  31196. mousewheel.wheelPrecision = value;
  31197. },
  31198. enumerable: true,
  31199. configurable: true
  31200. });
  31201. // Cache
  31202. ArcRotateCamera.prototype._initCache = function () {
  31203. _super.prototype._initCache.call(this);
  31204. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  31205. this._cache.alpha = undefined;
  31206. this._cache.beta = undefined;
  31207. this._cache.radius = undefined;
  31208. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  31209. };
  31210. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  31211. if (!ignoreParentClass) {
  31212. _super.prototype._updateCache.call(this);
  31213. }
  31214. this._cache._target.copyFrom(this._getTargetPosition());
  31215. this._cache.alpha = this.alpha;
  31216. this._cache.beta = this.beta;
  31217. this._cache.radius = this.radius;
  31218. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  31219. };
  31220. ArcRotateCamera.prototype._getTargetPosition = function () {
  31221. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  31222. var pos = this._targetHost.getAbsolutePosition();
  31223. if (this._targetBoundingCenter) {
  31224. pos.addToRef(this._targetBoundingCenter, this._target);
  31225. }
  31226. else {
  31227. this._target.copyFrom(pos);
  31228. }
  31229. }
  31230. return this._target;
  31231. };
  31232. // Synchronized
  31233. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  31234. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  31235. return false;
  31236. return this._cache._target.equals(this._target)
  31237. && this._cache.alpha === this.alpha
  31238. && this._cache.beta === this.beta
  31239. && this._cache.radius === this.radius
  31240. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  31241. };
  31242. // Methods
  31243. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  31244. var _this = this;
  31245. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  31246. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  31247. this._useCtrlForPanning = useCtrlForPanning;
  31248. this._panningMouseButton = panningMouseButton;
  31249. this.inputs.attachElement(element, noPreventDefault);
  31250. this._reset = function () {
  31251. _this.inertialAlphaOffset = 0;
  31252. _this.inertialBetaOffset = 0;
  31253. _this.inertialRadiusOffset = 0;
  31254. };
  31255. };
  31256. ArcRotateCamera.prototype.detachControl = function (element) {
  31257. this.inputs.detachElement(element);
  31258. if (this._reset) {
  31259. this._reset();
  31260. }
  31261. };
  31262. ArcRotateCamera.prototype._checkInputs = function () {
  31263. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  31264. if (this._collisionTriggered) {
  31265. return;
  31266. }
  31267. this.inputs.checkInputs();
  31268. // Inertia
  31269. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  31270. if (this.getScene().useRightHandedSystem) {
  31271. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  31272. }
  31273. else {
  31274. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  31275. }
  31276. this.beta += this.inertialBetaOffset;
  31277. this.radius -= this.inertialRadiusOffset;
  31278. this.inertialAlphaOffset *= this.inertia;
  31279. this.inertialBetaOffset *= this.inertia;
  31280. this.inertialRadiusOffset *= this.inertia;
  31281. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  31282. this.inertialAlphaOffset = 0;
  31283. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  31284. this.inertialBetaOffset = 0;
  31285. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  31286. this.inertialRadiusOffset = 0;
  31287. }
  31288. // Panning inertia
  31289. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  31290. if (!this._localDirection) {
  31291. this._localDirection = BABYLON.Vector3.Zero();
  31292. this._transformedDirection = BABYLON.Vector3.Zero();
  31293. }
  31294. this.inertialPanningX *= this.inertia;
  31295. this.inertialPanningY *= this.inertia;
  31296. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  31297. this.inertialPanningX = 0;
  31298. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  31299. this.inertialPanningY = 0;
  31300. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  31301. this._localDirection.multiplyInPlace(this.panningAxis);
  31302. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  31303. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  31304. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  31305. if (!this.panningAxis.y) {
  31306. this._transformedDirection.y = 0;
  31307. }
  31308. if (!this._targetHost) {
  31309. this._target.addInPlace(this._transformedDirection);
  31310. }
  31311. }
  31312. // Limits
  31313. this._checkLimits();
  31314. _super.prototype._checkInputs.call(this);
  31315. };
  31316. ArcRotateCamera.prototype._checkLimits = function () {
  31317. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  31318. if (this.allowUpsideDown && this.beta > Math.PI) {
  31319. this.beta = this.beta - (2 * Math.PI);
  31320. }
  31321. }
  31322. else {
  31323. if (this.beta < this.lowerBetaLimit) {
  31324. this.beta = this.lowerBetaLimit;
  31325. }
  31326. }
  31327. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  31328. if (this.allowUpsideDown && this.beta < -Math.PI) {
  31329. this.beta = this.beta + (2 * Math.PI);
  31330. }
  31331. }
  31332. else {
  31333. if (this.beta > this.upperBetaLimit) {
  31334. this.beta = this.upperBetaLimit;
  31335. }
  31336. }
  31337. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  31338. this.alpha = this.lowerAlphaLimit;
  31339. }
  31340. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  31341. this.alpha = this.upperAlphaLimit;
  31342. }
  31343. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  31344. this.radius = this.lowerRadiusLimit;
  31345. }
  31346. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  31347. this.radius = this.upperRadiusLimit;
  31348. }
  31349. };
  31350. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  31351. var radiusv3 = this.position.subtract(this._getTargetPosition());
  31352. this.radius = radiusv3.length();
  31353. // Alpha
  31354. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  31355. if (radiusv3.z < 0) {
  31356. this.alpha = 2 * Math.PI - this.alpha;
  31357. }
  31358. // Beta
  31359. this.beta = Math.acos(radiusv3.y / this.radius);
  31360. this._checkLimits();
  31361. };
  31362. ArcRotateCamera.prototype.setPosition = function (position) {
  31363. if (this.position.equals(position)) {
  31364. return;
  31365. }
  31366. this.position.copyFrom(position);
  31367. this.rebuildAnglesAndRadius();
  31368. };
  31369. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  31370. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  31371. if (allowSamePosition === void 0) { allowSamePosition = false; }
  31372. if (target.getBoundingInfo) {
  31373. if (toBoundingCenter) {
  31374. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  31375. }
  31376. else {
  31377. this._targetBoundingCenter = null;
  31378. }
  31379. this._targetHost = target;
  31380. this._target = this._getTargetPosition();
  31381. }
  31382. else {
  31383. var newTarget = target;
  31384. var currentTarget = this._getTargetPosition();
  31385. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  31386. return;
  31387. }
  31388. this._target = newTarget;
  31389. this._targetBoundingCenter = null;
  31390. }
  31391. this.rebuildAnglesAndRadius();
  31392. };
  31393. ArcRotateCamera.prototype._getViewMatrix = function () {
  31394. // Compute
  31395. var cosa = Math.cos(this.alpha);
  31396. var sina = Math.sin(this.alpha);
  31397. var cosb = Math.cos(this.beta);
  31398. var sinb = Math.sin(this.beta);
  31399. if (sinb === 0) {
  31400. sinb = 0.0001;
  31401. }
  31402. var target = this._getTargetPosition();
  31403. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  31404. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  31405. if (!this._collider) {
  31406. this._collider = new BABYLON.Collider();
  31407. }
  31408. this._collider.radius = this.collisionRadius;
  31409. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  31410. this._collisionTriggered = true;
  31411. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  31412. }
  31413. else {
  31414. this.position.copyFrom(this._newPosition);
  31415. var up = this.upVector;
  31416. if (this.allowUpsideDown && sinb < 0) {
  31417. up = up.clone();
  31418. up = up.negate();
  31419. }
  31420. if (this.getScene().useRightHandedSystem) {
  31421. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  31422. }
  31423. else {
  31424. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  31425. }
  31426. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  31427. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  31428. }
  31429. this._currentTarget = target;
  31430. return this._viewMatrix;
  31431. };
  31432. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  31433. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  31434. meshes = meshes || this.getScene().meshes;
  31435. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  31436. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  31437. this.radius = distance * this.zoomOnFactor;
  31438. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  31439. };
  31440. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  31441. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  31442. var meshesOrMinMaxVector;
  31443. var distance;
  31444. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  31445. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  31446. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  31447. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  31448. }
  31449. else {
  31450. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  31451. distance = meshesOrMinMaxVectorAndDistance.distance;
  31452. }
  31453. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  31454. if (!doNotUpdateMaxZ) {
  31455. this.maxZ = distance * 2;
  31456. }
  31457. };
  31458. /**
  31459. * @override
  31460. * Override Camera.createRigCamera
  31461. */
  31462. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  31463. var alphaShift;
  31464. switch (this.cameraRigMode) {
  31465. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31466. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31467. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31468. case BABYLON.Camera.RIG_MODE_VR:
  31469. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  31470. break;
  31471. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31472. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  31473. break;
  31474. }
  31475. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  31476. rigCam._cameraRigParams = {};
  31477. return rigCam;
  31478. };
  31479. /**
  31480. * @override
  31481. * Override Camera._updateRigCameras
  31482. */
  31483. ArcRotateCamera.prototype._updateRigCameras = function () {
  31484. var camLeft = this._rigCameras[0];
  31485. var camRight = this._rigCameras[1];
  31486. camLeft.beta = camRight.beta = this.beta;
  31487. camLeft.radius = camRight.radius = this.radius;
  31488. switch (this.cameraRigMode) {
  31489. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  31490. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  31491. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  31492. case BABYLON.Camera.RIG_MODE_VR:
  31493. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  31494. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  31495. break;
  31496. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  31497. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  31498. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  31499. break;
  31500. }
  31501. _super.prototype._updateRigCameras.call(this);
  31502. };
  31503. ArcRotateCamera.prototype.dispose = function () {
  31504. this.inputs.clear();
  31505. _super.prototype.dispose.call(this);
  31506. };
  31507. ArcRotateCamera.prototype.getClassName = function () {
  31508. return "ArcRotateCamera";
  31509. };
  31510. return ArcRotateCamera;
  31511. }(BABYLON.TargetCamera));
  31512. __decorate([
  31513. BABYLON.serialize()
  31514. ], ArcRotateCamera.prototype, "alpha", void 0);
  31515. __decorate([
  31516. BABYLON.serialize()
  31517. ], ArcRotateCamera.prototype, "beta", void 0);
  31518. __decorate([
  31519. BABYLON.serialize()
  31520. ], ArcRotateCamera.prototype, "radius", void 0);
  31521. __decorate([
  31522. BABYLON.serializeAsVector3("target")
  31523. ], ArcRotateCamera.prototype, "_target", void 0);
  31524. __decorate([
  31525. BABYLON.serialize()
  31526. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  31527. __decorate([
  31528. BABYLON.serialize()
  31529. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  31530. __decorate([
  31531. BABYLON.serialize()
  31532. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  31533. __decorate([
  31534. BABYLON.serialize()
  31535. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  31536. __decorate([
  31537. BABYLON.serialize()
  31538. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  31539. __decorate([
  31540. BABYLON.serialize()
  31541. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  31542. __decorate([
  31543. BABYLON.serialize()
  31544. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  31545. __decorate([
  31546. BABYLON.serialize()
  31547. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  31548. __decorate([
  31549. BABYLON.serialize()
  31550. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  31551. __decorate([
  31552. BABYLON.serialize()
  31553. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  31554. __decorate([
  31555. BABYLON.serialize()
  31556. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  31557. __decorate([
  31558. BABYLON.serialize()
  31559. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  31560. __decorate([
  31561. BABYLON.serialize()
  31562. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  31563. BABYLON.ArcRotateCamera = ArcRotateCamera;
  31564. })(BABYLON || (BABYLON = {}));
  31565. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  31566. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  31567. var BABYLON;
  31568. (function (BABYLON) {
  31569. var ArcRotateCameraInputsManager = (function (_super) {
  31570. __extends(ArcRotateCameraInputsManager, _super);
  31571. function ArcRotateCameraInputsManager(camera) {
  31572. return _super.call(this, camera) || this;
  31573. }
  31574. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  31575. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  31576. return this;
  31577. };
  31578. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  31579. this.add(new BABYLON.ArcRotateCameraPointersInput());
  31580. return this;
  31581. };
  31582. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  31583. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  31584. return this;
  31585. };
  31586. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  31587. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  31588. return this;
  31589. };
  31590. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  31591. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  31592. return this;
  31593. };
  31594. return ArcRotateCameraInputsManager;
  31595. }(BABYLON.CameraInputsManager));
  31596. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  31597. })(BABYLON || (BABYLON = {}));
  31598. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  31599. var BABYLON;
  31600. (function (BABYLON) {
  31601. var HemisphericLight = (function (_super) {
  31602. __extends(HemisphericLight, _super);
  31603. /**
  31604. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  31605. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  31606. * The HemisphericLight can't cast shadows.
  31607. * Documentation : http://doc.babylonjs.com/tutorials/lights
  31608. */
  31609. function HemisphericLight(name, direction, scene) {
  31610. var _this = _super.call(this, name, scene) || this;
  31611. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  31612. _this.direction = direction;
  31613. return _this;
  31614. }
  31615. HemisphericLight.prototype._buildUniformLayout = function () {
  31616. this._uniformBuffer.addUniform("vLightData", 4);
  31617. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  31618. this._uniformBuffer.addUniform("vLightSpecular", 3);
  31619. this._uniformBuffer.addUniform("vLightGround", 3);
  31620. this._uniformBuffer.addUniform("shadowsInfo", 3);
  31621. this._uniformBuffer.create();
  31622. };
  31623. /**
  31624. * Returns the string "HemisphericLight".
  31625. */
  31626. HemisphericLight.prototype.getClassName = function () {
  31627. return "HemisphericLight";
  31628. };
  31629. /**
  31630. * Sets the HemisphericLight direction towards the passed target (Vector3).
  31631. * Returns the updated direction.
  31632. */
  31633. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  31634. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  31635. return this.direction;
  31636. };
  31637. HemisphericLight.prototype.getShadowGenerator = function () {
  31638. return null;
  31639. };
  31640. /**
  31641. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  31642. * Returns the HemisphericLight.
  31643. */
  31644. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  31645. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  31646. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  31647. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  31648. return this;
  31649. };
  31650. HemisphericLight.prototype._getWorldMatrix = function () {
  31651. if (!this._worldMatrix) {
  31652. this._worldMatrix = BABYLON.Matrix.Identity();
  31653. }
  31654. return this._worldMatrix;
  31655. };
  31656. /**
  31657. * Returns the integer 3.
  31658. */
  31659. HemisphericLight.prototype.getTypeID = function () {
  31660. return 3;
  31661. };
  31662. return HemisphericLight;
  31663. }(BABYLON.Light));
  31664. __decorate([
  31665. BABYLON.serializeAsColor3()
  31666. ], HemisphericLight.prototype, "groundColor", void 0);
  31667. __decorate([
  31668. BABYLON.serializeAsVector3()
  31669. ], HemisphericLight.prototype, "direction", void 0);
  31670. BABYLON.HemisphericLight = HemisphericLight;
  31671. })(BABYLON || (BABYLON = {}));
  31672. //# sourceMappingURL=babylon.hemisphericLight.js.map
  31673. var BABYLON;
  31674. (function (BABYLON) {
  31675. var PointLight = (function (_super) {
  31676. __extends(PointLight, _super);
  31677. /**
  31678. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  31679. * A PointLight emits the light in every direction.
  31680. * It can cast shadows.
  31681. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  31682. * ```javascript
  31683. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  31684. * ```
  31685. * Documentation : http://doc.babylonjs.com/tutorials/lights
  31686. */
  31687. function PointLight(name, position, scene) {
  31688. var _this = _super.call(this, name, scene) || this;
  31689. _this.position = position;
  31690. return _this;
  31691. }
  31692. PointLight.prototype._buildUniformLayout = function () {
  31693. this._uniformBuffer.addUniform("vLightData", 4);
  31694. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  31695. this._uniformBuffer.addUniform("vLightSpecular", 3);
  31696. this._uniformBuffer.addUniform("shadowsInfo", 3);
  31697. this._uniformBuffer.create();
  31698. };
  31699. /**
  31700. * Returns the string "PointLight"
  31701. */
  31702. PointLight.prototype.getClassName = function () {
  31703. return "PointLight";
  31704. };
  31705. /**
  31706. * Returns a Vector3, the PointLight absolute position in the World.
  31707. */
  31708. PointLight.prototype.getAbsolutePosition = function () {
  31709. return this.transformedPosition ? this.transformedPosition : this.position;
  31710. };
  31711. /**
  31712. * Computes the PointLight transformed position if parented. Returns true if ok, false if not parented.
  31713. */
  31714. PointLight.prototype.computeTransformedPosition = function () {
  31715. if (this.parent && this.parent.getWorldMatrix) {
  31716. if (!this.transformedPosition) {
  31717. this.transformedPosition = BABYLON.Vector3.Zero();
  31718. }
  31719. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  31720. return true;
  31721. }
  31722. return false;
  31723. };
  31724. /**
  31725. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  31726. * Returns the PointLight.
  31727. */
  31728. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  31729. if (this.parent && this.parent.getWorldMatrix) {
  31730. this.computeTransformedPosition();
  31731. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  31732. return this;
  31733. }
  31734. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  31735. return this;
  31736. };
  31737. /**
  31738. * Boolean : returns true by default.
  31739. */
  31740. PointLight.prototype.needCube = function () {
  31741. return true;
  31742. };
  31743. /**
  31744. * Boolean : returns false by default.
  31745. */
  31746. PointLight.prototype.needRefreshPerFrame = function () {
  31747. return false;
  31748. };
  31749. /**
  31750. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  31751. */
  31752. PointLight.prototype.getShadowDirection = function (faceIndex) {
  31753. switch (faceIndex) {
  31754. case 0:
  31755. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  31756. case 1:
  31757. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  31758. case 2:
  31759. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  31760. case 3:
  31761. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  31762. case 4:
  31763. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  31764. case 5:
  31765. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  31766. }
  31767. return BABYLON.Vector3.Zero();
  31768. };
  31769. /**
  31770. * Return the depth scale used for the shadow map.
  31771. */
  31772. PointLight.prototype.getDepthScale = function () {
  31773. return 30.0;
  31774. };
  31775. /**
  31776. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  31777. * - fov = PI / 2
  31778. * - aspect ratio : 1.0
  31779. * - z-near and far equal to the active camera minZ and maxZ.
  31780. * Returns the PointLight.
  31781. */
  31782. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  31783. if (this.customProjectionMatrixBuilder) {
  31784. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  31785. }
  31786. else {
  31787. var activeCamera = this.getScene().activeCamera;
  31788. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  31789. }
  31790. return this;
  31791. };
  31792. PointLight.prototype._getWorldMatrix = function () {
  31793. if (!this._worldMatrix) {
  31794. this._worldMatrix = BABYLON.Matrix.Identity();
  31795. }
  31796. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  31797. return this._worldMatrix;
  31798. };
  31799. /**
  31800. * Returns the integer 0.
  31801. */
  31802. PointLight.prototype.getTypeID = function () {
  31803. return 0;
  31804. };
  31805. return PointLight;
  31806. }(BABYLON.Light));
  31807. __decorate([
  31808. BABYLON.serializeAsVector3()
  31809. ], PointLight.prototype, "position", void 0);
  31810. __decorate([
  31811. BABYLON.serialize()
  31812. ], PointLight.prototype, "shadowMinZ", void 0);
  31813. __decorate([
  31814. BABYLON.serialize()
  31815. ], PointLight.prototype, "shadowMaxZ", void 0);
  31816. BABYLON.PointLight = PointLight;
  31817. })(BABYLON || (BABYLON = {}));
  31818. //# sourceMappingURL=babylon.pointLight.js.map
  31819. /// <reference path="babylon.light.ts" />
  31820. var BABYLON;
  31821. (function (BABYLON) {
  31822. var DirectionalLight = (function (_super) {
  31823. __extends(DirectionalLight, _super);
  31824. /**
  31825. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  31826. * The directional light is emitted from everywhere in the given direction.
  31827. * It can cast shawdows.
  31828. * Documentation : http://doc.babylonjs.com/tutorials/lights
  31829. */
  31830. function DirectionalLight(name, direction, scene) {
  31831. var _this = _super.call(this, name, scene) || this;
  31832. _this.shadowOrthoScale = 0.5;
  31833. _this.autoUpdateExtends = true;
  31834. // Cache
  31835. _this._orthoLeft = Number.MAX_VALUE;
  31836. _this._orthoRight = Number.MIN_VALUE;
  31837. _this._orthoTop = Number.MIN_VALUE;
  31838. _this._orthoBottom = Number.MAX_VALUE;
  31839. _this.position = direction.scale(-1.0);
  31840. _this.direction = direction;
  31841. return _this;
  31842. }
  31843. DirectionalLight.prototype._buildUniformLayout = function () {
  31844. this._uniformBuffer.addUniform("vLightData", 4);
  31845. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  31846. this._uniformBuffer.addUniform("vLightSpecular", 3);
  31847. this._uniformBuffer.addUniform("shadowsInfo", 3);
  31848. this._uniformBuffer.create();
  31849. };
  31850. /**
  31851. * Returns the string "DirectionalLight".
  31852. */
  31853. DirectionalLight.prototype.getClassName = function () {
  31854. return "DirectionalLight";
  31855. };
  31856. /**
  31857. * Returns the DirectionalLight absolute position in the World.
  31858. */
  31859. DirectionalLight.prototype.getAbsolutePosition = function () {
  31860. return this.transformedPosition ? this.transformedPosition : this.position;
  31861. };
  31862. /**
  31863. * Sets the DirectionalLight direction toward the passed target (Vector3).
  31864. * Returns the updated DirectionalLight direction (Vector3).
  31865. */
  31866. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  31867. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  31868. return this.direction;
  31869. };
  31870. /**
  31871. * Return the depth scale used for the shadow map.
  31872. */
  31873. DirectionalLight.prototype.getDepthScale = function () {
  31874. return 30.0;
  31875. };
  31876. /**
  31877. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  31878. * Returns the DirectionalLight.
  31879. */
  31880. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  31881. if (this.customProjectionMatrixBuilder) {
  31882. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  31883. }
  31884. else {
  31885. var activeCamera = this.getScene().activeCamera;
  31886. // Check extends
  31887. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  31888. var tempVector3 = BABYLON.Vector3.Zero();
  31889. this._orthoLeft = Number.MAX_VALUE;
  31890. this._orthoRight = Number.MIN_VALUE;
  31891. this._orthoTop = Number.MIN_VALUE;
  31892. this._orthoBottom = Number.MAX_VALUE;
  31893. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  31894. var mesh = renderList[meshIndex];
  31895. if (!mesh) {
  31896. continue;
  31897. }
  31898. var boundingInfo = mesh.getBoundingInfo();
  31899. if (!boundingInfo) {
  31900. continue;
  31901. }
  31902. var boundingBox = boundingInfo.boundingBox;
  31903. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  31904. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  31905. if (tempVector3.x < this._orthoLeft)
  31906. this._orthoLeft = tempVector3.x;
  31907. if (tempVector3.y < this._orthoBottom)
  31908. this._orthoBottom = tempVector3.y;
  31909. if (tempVector3.x > this._orthoRight)
  31910. this._orthoRight = tempVector3.x;
  31911. if (tempVector3.y > this._orthoTop)
  31912. this._orthoTop = tempVector3.y;
  31913. }
  31914. }
  31915. }
  31916. var xOffset = this._orthoRight - this._orthoLeft;
  31917. var yOffset = this._orthoTop - this._orthoBottom;
  31918. 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);
  31919. }
  31920. return this;
  31921. };
  31922. /**
  31923. * Boolean : true by default.
  31924. */
  31925. DirectionalLight.prototype.needRefreshPerFrame = function () {
  31926. return true;
  31927. };
  31928. /**
  31929. * Boolean : false by default.
  31930. */
  31931. DirectionalLight.prototype.needCube = function () {
  31932. return false;
  31933. };
  31934. /**
  31935. * Returns the light direction (Vector3) for any passed face index.
  31936. */
  31937. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  31938. return this.direction;
  31939. };
  31940. /**
  31941. * Computes the light transformed position in case the light is parented. Returns true if parented, else false.
  31942. */
  31943. DirectionalLight.prototype.computeTransformedPosition = function () {
  31944. if (this.parent && this.parent.getWorldMatrix) {
  31945. if (!this.transformedPosition) {
  31946. this.transformedPosition = BABYLON.Vector3.Zero();
  31947. }
  31948. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  31949. return true;
  31950. }
  31951. return false;
  31952. };
  31953. /**
  31954. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  31955. * Returns the DirectionalLight.
  31956. */
  31957. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  31958. if (this.parent && this.parent.getWorldMatrix) {
  31959. if (!this._transformedDirection) {
  31960. this._transformedDirection = BABYLON.Vector3.Zero();
  31961. }
  31962. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  31963. this._uniformBuffer.updateFloat4("vLightData", this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1, lightIndex);
  31964. return this;
  31965. }
  31966. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  31967. return this;
  31968. };
  31969. DirectionalLight.prototype._getWorldMatrix = function () {
  31970. if (!this._worldMatrix) {
  31971. this._worldMatrix = BABYLON.Matrix.Identity();
  31972. }
  31973. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  31974. return this._worldMatrix;
  31975. };
  31976. /**
  31977. * Returns the integer 1.
  31978. */
  31979. DirectionalLight.prototype.getTypeID = function () {
  31980. return 1;
  31981. };
  31982. return DirectionalLight;
  31983. }(BABYLON.Light));
  31984. __decorate([
  31985. BABYLON.serializeAsVector3()
  31986. ], DirectionalLight.prototype, "position", void 0);
  31987. __decorate([
  31988. BABYLON.serializeAsVector3()
  31989. ], DirectionalLight.prototype, "direction", void 0);
  31990. __decorate([
  31991. BABYLON.serialize()
  31992. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  31993. __decorate([
  31994. BABYLON.serialize()
  31995. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  31996. __decorate([
  31997. BABYLON.serialize()
  31998. ], DirectionalLight.prototype, "shadowMinZ", void 0);
  31999. __decorate([
  32000. BABYLON.serialize()
  32001. ], DirectionalLight.prototype, "shadowMaxZ", void 0);
  32002. BABYLON.DirectionalLight = DirectionalLight;
  32003. })(BABYLON || (BABYLON = {}));
  32004. //# sourceMappingURL=babylon.directionalLight.js.map
  32005. var BABYLON;
  32006. (function (BABYLON) {
  32007. var SpotLight = (function (_super) {
  32008. __extends(SpotLight, _super);
  32009. /**
  32010. * Creates a SpotLight object in the scene with the passed parameters :
  32011. * - `position` (Vector3) is the initial SpotLight position,
  32012. * - `direction` (Vector3) is the initial SpotLight direction,
  32013. * - `angle` (float, in radians) is the spot light cone angle,
  32014. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  32015. * A spot light is a simply light oriented cone.
  32016. * It can cast shadows.
  32017. * Documentation : http://doc.babylonjs.com/tutorials/lights
  32018. */
  32019. function SpotLight(name, position, direction, angle, exponent, scene) {
  32020. var _this = _super.call(this, name, scene) || this;
  32021. _this.position = position;
  32022. _this.direction = direction;
  32023. _this.angle = angle;
  32024. _this.exponent = exponent;
  32025. return _this;
  32026. }
  32027. SpotLight.prototype._buildUniformLayout = function () {
  32028. this._uniformBuffer.addUniform("vLightData", 4);
  32029. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  32030. this._uniformBuffer.addUniform("vLightSpecular", 3);
  32031. this._uniformBuffer.addUniform("vLightDirection", 3);
  32032. this._uniformBuffer.addUniform("shadowsInfo", 3);
  32033. this._uniformBuffer.create();
  32034. };
  32035. /**
  32036. * Returns the string "SpotLight".
  32037. */
  32038. SpotLight.prototype.getClassName = function () {
  32039. return "SpotLight";
  32040. };
  32041. /**
  32042. * Returns the SpotLight absolute position in the World (Vector3).
  32043. */
  32044. SpotLight.prototype.getAbsolutePosition = function () {
  32045. return this.transformedPosition ? this.transformedPosition : this.position;
  32046. };
  32047. /**
  32048. * Return the depth scale used for the shadow map.
  32049. */
  32050. SpotLight.prototype.getDepthScale = function () {
  32051. return 30.0;
  32052. };
  32053. /**
  32054. * 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.
  32055. * Returns the SpotLight.
  32056. */
  32057. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  32058. if (this.customProjectionMatrixBuilder) {
  32059. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  32060. }
  32061. else {
  32062. var activeCamera = this.getScene().activeCamera;
  32063. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  32064. }
  32065. return this;
  32066. };
  32067. /**
  32068. * Boolean : false by default.
  32069. */
  32070. SpotLight.prototype.needCube = function () {
  32071. return false;
  32072. };
  32073. /**
  32074. * Boolean : false by default.
  32075. */
  32076. SpotLight.prototype.needRefreshPerFrame = function () {
  32077. return false;
  32078. };
  32079. /**
  32080. * Returns the SpotLight direction (Vector3) for any passed face index.
  32081. */
  32082. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  32083. return this.direction;
  32084. };
  32085. /**
  32086. * Updates the SpotLight direction towards the passed target (Vector3).
  32087. * Returns the updated direction.
  32088. */
  32089. SpotLight.prototype.setDirectionToTarget = function (target) {
  32090. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  32091. return this.direction;
  32092. };
  32093. /**
  32094. * Computes the SpotLight transformed position if parented. Returns true if parented, else false.
  32095. */
  32096. SpotLight.prototype.computeTransformedPosition = function () {
  32097. if (this.parent && this.parent.getWorldMatrix) {
  32098. if (!this.transformedPosition) {
  32099. this.transformedPosition = BABYLON.Vector3.Zero();
  32100. }
  32101. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  32102. return true;
  32103. }
  32104. return false;
  32105. };
  32106. /**
  32107. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  32108. * Return the SpotLight.
  32109. */
  32110. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  32111. var normalizeDirection;
  32112. if (this.parent && this.parent.getWorldMatrix) {
  32113. if (!this._transformedDirection) {
  32114. this._transformedDirection = BABYLON.Vector3.Zero();
  32115. }
  32116. this.computeTransformedPosition();
  32117. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  32118. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  32119. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  32120. }
  32121. else {
  32122. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  32123. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  32124. }
  32125. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  32126. return this;
  32127. };
  32128. SpotLight.prototype._getWorldMatrix = function () {
  32129. if (!this._worldMatrix) {
  32130. this._worldMatrix = BABYLON.Matrix.Identity();
  32131. }
  32132. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  32133. return this._worldMatrix;
  32134. };
  32135. /**
  32136. * Returns the integer 2.
  32137. */
  32138. SpotLight.prototype.getTypeID = function () {
  32139. return 2;
  32140. };
  32141. /**
  32142. * Returns the SpotLight rotation (Vector3).
  32143. */
  32144. SpotLight.prototype.getRotation = function () {
  32145. this.direction.normalize();
  32146. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  32147. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  32148. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  32149. };
  32150. return SpotLight;
  32151. }(BABYLON.Light));
  32152. __decorate([
  32153. BABYLON.serializeAsVector3()
  32154. ], SpotLight.prototype, "position", void 0);
  32155. __decorate([
  32156. BABYLON.serializeAsVector3()
  32157. ], SpotLight.prototype, "direction", void 0);
  32158. __decorate([
  32159. BABYLON.serialize()
  32160. ], SpotLight.prototype, "angle", void 0);
  32161. __decorate([
  32162. BABYLON.serialize()
  32163. ], SpotLight.prototype, "exponent", void 0);
  32164. __decorate([
  32165. BABYLON.serialize()
  32166. ], SpotLight.prototype, "shadowMinZ", void 0);
  32167. __decorate([
  32168. BABYLON.serialize()
  32169. ], SpotLight.prototype, "shadowMaxZ", void 0);
  32170. BABYLON.SpotLight = SpotLight;
  32171. })(BABYLON || (BABYLON = {}));
  32172. //# sourceMappingURL=babylon.spotLight.js.map
  32173. var BABYLON;
  32174. (function (BABYLON) {
  32175. var AnimationRange = (function () {
  32176. function AnimationRange(name, from, to) {
  32177. this.name = name;
  32178. this.from = from;
  32179. this.to = to;
  32180. }
  32181. AnimationRange.prototype.clone = function () {
  32182. return new AnimationRange(this.name, this.from, this.to);
  32183. };
  32184. return AnimationRange;
  32185. }());
  32186. BABYLON.AnimationRange = AnimationRange;
  32187. /**
  32188. * Composed of a frame, and an action function
  32189. */
  32190. var AnimationEvent = (function () {
  32191. function AnimationEvent(frame, action, onlyOnce) {
  32192. this.frame = frame;
  32193. this.action = action;
  32194. this.onlyOnce = onlyOnce;
  32195. this.isDone = false;
  32196. }
  32197. return AnimationEvent;
  32198. }());
  32199. BABYLON.AnimationEvent = AnimationEvent;
  32200. var PathCursor = (function () {
  32201. function PathCursor(path) {
  32202. this.path = path;
  32203. this._onchange = new Array();
  32204. this.value = 0;
  32205. this.animations = new Array();
  32206. }
  32207. PathCursor.prototype.getPoint = function () {
  32208. var point = this.path.getPointAtLengthPosition(this.value);
  32209. return new BABYLON.Vector3(point.x, 0, point.y);
  32210. };
  32211. PathCursor.prototype.moveAhead = function (step) {
  32212. if (step === void 0) { step = 0.002; }
  32213. this.move(step);
  32214. return this;
  32215. };
  32216. PathCursor.prototype.moveBack = function (step) {
  32217. if (step === void 0) { step = 0.002; }
  32218. this.move(-step);
  32219. return this;
  32220. };
  32221. PathCursor.prototype.move = function (step) {
  32222. if (Math.abs(step) > 1) {
  32223. throw "step size should be less than 1.";
  32224. }
  32225. this.value += step;
  32226. this.ensureLimits();
  32227. this.raiseOnChange();
  32228. return this;
  32229. };
  32230. PathCursor.prototype.ensureLimits = function () {
  32231. while (this.value > 1) {
  32232. this.value -= 1;
  32233. }
  32234. while (this.value < 0) {
  32235. this.value += 1;
  32236. }
  32237. return this;
  32238. };
  32239. // used by animation engine
  32240. PathCursor.prototype.markAsDirty = function (propertyName) {
  32241. this.ensureLimits();
  32242. this.raiseOnChange();
  32243. return this;
  32244. };
  32245. PathCursor.prototype.raiseOnChange = function () {
  32246. var _this = this;
  32247. this._onchange.forEach(function (f) { return f(_this); });
  32248. return this;
  32249. };
  32250. PathCursor.prototype.onchange = function (f) {
  32251. this._onchange.push(f);
  32252. return this;
  32253. };
  32254. return PathCursor;
  32255. }());
  32256. BABYLON.PathCursor = PathCursor;
  32257. var Animation = (function () {
  32258. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  32259. this.name = name;
  32260. this.targetProperty = targetProperty;
  32261. this.framePerSecond = framePerSecond;
  32262. this.dataType = dataType;
  32263. this.loopMode = loopMode;
  32264. this.enableBlending = enableBlending;
  32265. this._offsetsCache = {};
  32266. this._highLimitsCache = {};
  32267. this._stopped = false;
  32268. this._blendingFactor = 0;
  32269. // The set of event that will be linked to this animation
  32270. this._events = new Array();
  32271. this.allowMatricesInterpolation = false;
  32272. this.blendingSpeed = 0.01;
  32273. this._ranges = {};
  32274. this.targetPropertyPath = targetProperty.split(".");
  32275. this.dataType = dataType;
  32276. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  32277. }
  32278. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  32279. var dataType = undefined;
  32280. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  32281. dataType = Animation.ANIMATIONTYPE_FLOAT;
  32282. }
  32283. else if (from instanceof BABYLON.Quaternion) {
  32284. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  32285. }
  32286. else if (from instanceof BABYLON.Vector3) {
  32287. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  32288. }
  32289. else if (from instanceof BABYLON.Vector2) {
  32290. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  32291. }
  32292. else if (from instanceof BABYLON.Color3) {
  32293. dataType = Animation.ANIMATIONTYPE_COLOR3;
  32294. }
  32295. else if (from instanceof BABYLON.Size) {
  32296. dataType = Animation.ANIMATIONTYPE_SIZE;
  32297. }
  32298. if (dataType == undefined) {
  32299. return null;
  32300. }
  32301. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  32302. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  32303. animation.setKeys(keys);
  32304. if (easingFunction !== undefined) {
  32305. animation.setEasingFunction(easingFunction);
  32306. }
  32307. return animation;
  32308. };
  32309. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32310. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32311. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32312. };
  32313. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  32314. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  32315. node.animations.push(animation);
  32316. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  32317. };
  32318. // Methods
  32319. /**
  32320. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  32321. */
  32322. Animation.prototype.toString = function (fullDetails) {
  32323. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  32324. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  32325. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  32326. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  32327. if (fullDetails) {
  32328. ret += ", Ranges: {";
  32329. var first = true;
  32330. for (var name in this._ranges) {
  32331. if (first) {
  32332. ret += ", ";
  32333. first = false;
  32334. }
  32335. ret += name;
  32336. }
  32337. ret += "}";
  32338. }
  32339. return ret;
  32340. };
  32341. /**
  32342. * Add an event to this animation.
  32343. */
  32344. Animation.prototype.addEvent = function (event) {
  32345. this._events.push(event);
  32346. };
  32347. /**
  32348. * Remove all events found at the given frame
  32349. * @param frame
  32350. */
  32351. Animation.prototype.removeEvents = function (frame) {
  32352. for (var index = 0; index < this._events.length; index++) {
  32353. if (this._events[index].frame === frame) {
  32354. this._events.splice(index, 1);
  32355. index--;
  32356. }
  32357. }
  32358. };
  32359. Animation.prototype.createRange = function (name, from, to) {
  32360. // check name not already in use; could happen for bones after serialized
  32361. if (!this._ranges[name]) {
  32362. this._ranges[name] = new AnimationRange(name, from, to);
  32363. }
  32364. };
  32365. Animation.prototype.deleteRange = function (name, deleteFrames) {
  32366. if (deleteFrames === void 0) { deleteFrames = true; }
  32367. if (this._ranges[name]) {
  32368. if (deleteFrames) {
  32369. var from = this._ranges[name].from;
  32370. var to = this._ranges[name].to;
  32371. // this loop MUST go high to low for multiple splices to work
  32372. for (var key = this._keys.length - 1; key >= 0; key--) {
  32373. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  32374. this._keys.splice(key, 1);
  32375. }
  32376. }
  32377. }
  32378. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  32379. }
  32380. };
  32381. Animation.prototype.getRange = function (name) {
  32382. return this._ranges[name];
  32383. };
  32384. Animation.prototype.reset = function () {
  32385. this._offsetsCache = {};
  32386. this._highLimitsCache = {};
  32387. this.currentFrame = 0;
  32388. this._blendingFactor = 0;
  32389. this._originalBlendValue = null;
  32390. };
  32391. Animation.prototype.isStopped = function () {
  32392. return this._stopped;
  32393. };
  32394. Animation.prototype.getKeys = function () {
  32395. return this._keys;
  32396. };
  32397. Animation.prototype.getHighestFrame = function () {
  32398. var ret = 0;
  32399. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  32400. if (ret < this._keys[key].frame) {
  32401. ret = this._keys[key].frame;
  32402. }
  32403. }
  32404. return ret;
  32405. };
  32406. Animation.prototype.getEasingFunction = function () {
  32407. return this._easingFunction;
  32408. };
  32409. Animation.prototype.setEasingFunction = function (easingFunction) {
  32410. this._easingFunction = easingFunction;
  32411. };
  32412. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  32413. return startValue + (endValue - startValue) * gradient;
  32414. };
  32415. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  32416. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  32417. };
  32418. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  32419. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  32420. };
  32421. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  32422. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  32423. };
  32424. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  32425. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  32426. };
  32427. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  32428. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  32429. };
  32430. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  32431. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  32432. };
  32433. Animation.prototype.clone = function () {
  32434. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  32435. clone.enableBlending = this.enableBlending;
  32436. clone.blendingSpeed = this.blendingSpeed;
  32437. if (this._keys) {
  32438. clone.setKeys(this._keys);
  32439. }
  32440. if (this._ranges) {
  32441. clone._ranges = {};
  32442. for (var name in this._ranges) {
  32443. clone._ranges[name] = this._ranges[name].clone();
  32444. }
  32445. }
  32446. return clone;
  32447. };
  32448. Animation.prototype.setKeys = function (values) {
  32449. this._keys = values.slice(0);
  32450. this._offsetsCache = {};
  32451. this._highLimitsCache = {};
  32452. };
  32453. Animation.prototype._getKeyValue = function (value) {
  32454. if (typeof value === "function") {
  32455. return value();
  32456. }
  32457. return value;
  32458. };
  32459. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  32460. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  32461. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  32462. }
  32463. this.currentFrame = currentFrame;
  32464. // Try to get a hash to find the right key
  32465. var startKey = 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));
  32466. if (this._keys[startKey].frame >= currentFrame) {
  32467. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  32468. startKey--;
  32469. }
  32470. }
  32471. for (var key = startKey; key < this._keys.length; key++) {
  32472. if (this._keys[key + 1].frame >= currentFrame) {
  32473. var startValue = this._getKeyValue(this._keys[key].value);
  32474. var endValue = this._getKeyValue(this._keys[key + 1].value);
  32475. // gradient : percent of currentFrame between the frame inf and the frame sup
  32476. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  32477. // check for easingFunction and correction of gradient
  32478. if (this._easingFunction != null) {
  32479. gradient = this._easingFunction.ease(gradient);
  32480. }
  32481. switch (this.dataType) {
  32482. // Float
  32483. case Animation.ANIMATIONTYPE_FLOAT:
  32484. switch (loopMode) {
  32485. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32486. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32487. return this.floatInterpolateFunction(startValue, endValue, gradient);
  32488. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32489. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  32490. }
  32491. break;
  32492. // Quaternion
  32493. case Animation.ANIMATIONTYPE_QUATERNION:
  32494. var quaternion = null;
  32495. switch (loopMode) {
  32496. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32497. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32498. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  32499. break;
  32500. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32501. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32502. break;
  32503. }
  32504. return quaternion;
  32505. // Vector3
  32506. case Animation.ANIMATIONTYPE_VECTOR3:
  32507. switch (loopMode) {
  32508. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32509. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32510. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  32511. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32512. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32513. }
  32514. // Vector2
  32515. case Animation.ANIMATIONTYPE_VECTOR2:
  32516. switch (loopMode) {
  32517. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32518. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32519. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  32520. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32521. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32522. }
  32523. // Size
  32524. case Animation.ANIMATIONTYPE_SIZE:
  32525. switch (loopMode) {
  32526. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32527. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32528. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  32529. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32530. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32531. }
  32532. // Color3
  32533. case Animation.ANIMATIONTYPE_COLOR3:
  32534. switch (loopMode) {
  32535. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32536. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32537. return this.color3InterpolateFunction(startValue, endValue, gradient);
  32538. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32539. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  32540. }
  32541. // Matrix
  32542. case Animation.ANIMATIONTYPE_MATRIX:
  32543. switch (loopMode) {
  32544. case Animation.ANIMATIONLOOPMODE_CYCLE:
  32545. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  32546. if (this.allowMatricesInterpolation) {
  32547. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  32548. }
  32549. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  32550. return startValue;
  32551. }
  32552. default:
  32553. break;
  32554. }
  32555. break;
  32556. }
  32557. }
  32558. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  32559. };
  32560. Animation.prototype.setValue = function (currentValue, blend) {
  32561. if (blend === void 0) { blend = false; }
  32562. // Set value
  32563. var path;
  32564. var destination;
  32565. if (this.targetPropertyPath.length > 1) {
  32566. var property = this._target[this.targetPropertyPath[0]];
  32567. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  32568. property = property[this.targetPropertyPath[index]];
  32569. }
  32570. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  32571. destination = property;
  32572. }
  32573. else {
  32574. path = this.targetPropertyPath[0];
  32575. destination = this._target;
  32576. }
  32577. // Blending
  32578. if (this.enableBlending && this._blendingFactor <= 1.0) {
  32579. if (!this._originalBlendValue) {
  32580. if (destination[path].clone) {
  32581. this._originalBlendValue = destination[path].clone();
  32582. }
  32583. else {
  32584. this._originalBlendValue = destination[path];
  32585. }
  32586. }
  32587. if (this._originalBlendValue.prototype) {
  32588. if (this._originalBlendValue.prototype.Lerp) {
  32589. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  32590. }
  32591. else {
  32592. destination[path] = currentValue;
  32593. }
  32594. }
  32595. else if (this._originalBlendValue.m) {
  32596. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  32597. }
  32598. else {
  32599. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  32600. }
  32601. this._blendingFactor += this.blendingSpeed;
  32602. }
  32603. else {
  32604. destination[path] = currentValue;
  32605. }
  32606. if (this._target.markAsDirty) {
  32607. this._target.markAsDirty(this.targetProperty);
  32608. }
  32609. };
  32610. Animation.prototype.goToFrame = function (frame) {
  32611. if (frame < this._keys[0].frame) {
  32612. frame = this._keys[0].frame;
  32613. }
  32614. else if (frame > this._keys[this._keys.length - 1].frame) {
  32615. frame = this._keys[this._keys.length - 1].frame;
  32616. }
  32617. var currentValue = this._interpolate(frame, 0, this.loopMode);
  32618. this.setValue(currentValue);
  32619. };
  32620. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  32621. if (blend === void 0) { blend = false; }
  32622. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  32623. this._stopped = true;
  32624. return false;
  32625. }
  32626. var returnValue = true;
  32627. // Adding a start key at frame 0 if missing
  32628. if (this._keys[0].frame !== 0) {
  32629. var newKey = { frame: 0, value: this._keys[0].value };
  32630. this._keys.splice(0, 0, newKey);
  32631. }
  32632. // Check limits
  32633. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  32634. from = this._keys[0].frame;
  32635. }
  32636. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  32637. to = this._keys[this._keys.length - 1].frame;
  32638. }
  32639. //to and from cannot be the same key
  32640. if (from === to) {
  32641. from++;
  32642. }
  32643. // Compute ratio
  32644. var range = to - from;
  32645. var offsetValue;
  32646. // ratio represents the frame delta between from and to
  32647. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  32648. var highLimitValue = 0;
  32649. if (ratio > range && !loop) {
  32650. returnValue = false;
  32651. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  32652. }
  32653. else {
  32654. // Get max value if required
  32655. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  32656. var keyOffset = to.toString() + from.toString();
  32657. if (!this._offsetsCache[keyOffset]) {
  32658. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32659. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  32660. switch (this.dataType) {
  32661. // Float
  32662. case Animation.ANIMATIONTYPE_FLOAT:
  32663. this._offsetsCache[keyOffset] = toValue - fromValue;
  32664. break;
  32665. // Quaternion
  32666. case Animation.ANIMATIONTYPE_QUATERNION:
  32667. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32668. break;
  32669. // Vector3
  32670. case Animation.ANIMATIONTYPE_VECTOR3:
  32671. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32672. // Vector2
  32673. case Animation.ANIMATIONTYPE_VECTOR2:
  32674. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32675. // Size
  32676. case Animation.ANIMATIONTYPE_SIZE:
  32677. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32678. // Color3
  32679. case Animation.ANIMATIONTYPE_COLOR3:
  32680. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  32681. default:
  32682. break;
  32683. }
  32684. this._highLimitsCache[keyOffset] = toValue;
  32685. }
  32686. highLimitValue = this._highLimitsCache[keyOffset];
  32687. offsetValue = this._offsetsCache[keyOffset];
  32688. }
  32689. }
  32690. if (offsetValue === undefined) {
  32691. switch (this.dataType) {
  32692. // Float
  32693. case Animation.ANIMATIONTYPE_FLOAT:
  32694. offsetValue = 0;
  32695. break;
  32696. // Quaternion
  32697. case Animation.ANIMATIONTYPE_QUATERNION:
  32698. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  32699. break;
  32700. // Vector3
  32701. case Animation.ANIMATIONTYPE_VECTOR3:
  32702. offsetValue = BABYLON.Vector3.Zero();
  32703. break;
  32704. // Vector2
  32705. case Animation.ANIMATIONTYPE_VECTOR2:
  32706. offsetValue = BABYLON.Vector2.Zero();
  32707. break;
  32708. // Size
  32709. case Animation.ANIMATIONTYPE_SIZE:
  32710. offsetValue = BABYLON.Size.Zero();
  32711. break;
  32712. // Color3
  32713. case Animation.ANIMATIONTYPE_COLOR3:
  32714. offsetValue = BABYLON.Color3.Black();
  32715. }
  32716. }
  32717. // Compute value
  32718. var repeatCount = (ratio / range) >> 0;
  32719. var currentFrame = returnValue ? from + ratio % range : to;
  32720. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  32721. // Set value
  32722. this.setValue(currentValue);
  32723. // Check events
  32724. for (var index = 0; index < this._events.length; index++) {
  32725. if (currentFrame >= this._events[index].frame) {
  32726. var event = this._events[index];
  32727. if (!event.isDone) {
  32728. // If event should be done only once, remove it.
  32729. if (event.onlyOnce) {
  32730. this._events.splice(index, 1);
  32731. index--;
  32732. }
  32733. event.isDone = true;
  32734. event.action();
  32735. } // Don't do anything if the event has already be done.
  32736. }
  32737. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  32738. // reset event, the animation is looping
  32739. this._events[index].isDone = false;
  32740. }
  32741. }
  32742. if (!returnValue) {
  32743. this._stopped = true;
  32744. }
  32745. return returnValue;
  32746. };
  32747. Animation.prototype.serialize = function () {
  32748. var serializationObject = {};
  32749. serializationObject.name = this.name;
  32750. serializationObject.property = this.targetProperty;
  32751. serializationObject.framePerSecond = this.framePerSecond;
  32752. serializationObject.dataType = this.dataType;
  32753. serializationObject.loopBehavior = this.loopMode;
  32754. serializationObject.enableBlending = this.enableBlending;
  32755. serializationObject.blendingSpeed = this.blendingSpeed;
  32756. var dataType = this.dataType;
  32757. serializationObject.keys = [];
  32758. var keys = this.getKeys();
  32759. for (var index = 0; index < keys.length; index++) {
  32760. var animationKey = keys[index];
  32761. var key = {};
  32762. key.frame = animationKey.frame;
  32763. switch (dataType) {
  32764. case Animation.ANIMATIONTYPE_FLOAT:
  32765. key.values = [animationKey.value];
  32766. break;
  32767. case Animation.ANIMATIONTYPE_QUATERNION:
  32768. case Animation.ANIMATIONTYPE_MATRIX:
  32769. case Animation.ANIMATIONTYPE_VECTOR3:
  32770. case Animation.ANIMATIONTYPE_COLOR3:
  32771. key.values = animationKey.value.asArray();
  32772. break;
  32773. }
  32774. serializationObject.keys.push(key);
  32775. }
  32776. serializationObject.ranges = [];
  32777. for (var name in this._ranges) {
  32778. var range = {};
  32779. range.name = name;
  32780. range.from = this._ranges[name].from;
  32781. range.to = this._ranges[name].to;
  32782. serializationObject.ranges.push(range);
  32783. }
  32784. return serializationObject;
  32785. };
  32786. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  32787. get: function () {
  32788. return Animation._ANIMATIONTYPE_FLOAT;
  32789. },
  32790. enumerable: true,
  32791. configurable: true
  32792. });
  32793. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  32794. get: function () {
  32795. return Animation._ANIMATIONTYPE_VECTOR3;
  32796. },
  32797. enumerable: true,
  32798. configurable: true
  32799. });
  32800. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  32801. get: function () {
  32802. return Animation._ANIMATIONTYPE_VECTOR2;
  32803. },
  32804. enumerable: true,
  32805. configurable: true
  32806. });
  32807. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  32808. get: function () {
  32809. return Animation._ANIMATIONTYPE_SIZE;
  32810. },
  32811. enumerable: true,
  32812. configurable: true
  32813. });
  32814. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  32815. get: function () {
  32816. return Animation._ANIMATIONTYPE_QUATERNION;
  32817. },
  32818. enumerable: true,
  32819. configurable: true
  32820. });
  32821. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  32822. get: function () {
  32823. return Animation._ANIMATIONTYPE_MATRIX;
  32824. },
  32825. enumerable: true,
  32826. configurable: true
  32827. });
  32828. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  32829. get: function () {
  32830. return Animation._ANIMATIONTYPE_COLOR3;
  32831. },
  32832. enumerable: true,
  32833. configurable: true
  32834. });
  32835. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  32836. get: function () {
  32837. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  32838. },
  32839. enumerable: true,
  32840. configurable: true
  32841. });
  32842. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  32843. get: function () {
  32844. return Animation._ANIMATIONLOOPMODE_CYCLE;
  32845. },
  32846. enumerable: true,
  32847. configurable: true
  32848. });
  32849. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  32850. get: function () {
  32851. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  32852. },
  32853. enumerable: true,
  32854. configurable: true
  32855. });
  32856. Animation.Parse = function (parsedAnimation) {
  32857. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  32858. var dataType = parsedAnimation.dataType;
  32859. var keys = [];
  32860. var data;
  32861. var index;
  32862. if (parsedAnimation.enableBlending) {
  32863. animation.enableBlending = parsedAnimation.enableBlending;
  32864. }
  32865. if (parsedAnimation.blendingSpeed) {
  32866. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  32867. }
  32868. for (index = 0; index < parsedAnimation.keys.length; index++) {
  32869. var key = parsedAnimation.keys[index];
  32870. switch (dataType) {
  32871. case Animation.ANIMATIONTYPE_FLOAT:
  32872. data = key.values[0];
  32873. break;
  32874. case Animation.ANIMATIONTYPE_QUATERNION:
  32875. data = BABYLON.Quaternion.FromArray(key.values);
  32876. break;
  32877. case Animation.ANIMATIONTYPE_MATRIX:
  32878. data = BABYLON.Matrix.FromArray(key.values);
  32879. break;
  32880. case Animation.ANIMATIONTYPE_COLOR3:
  32881. data = BABYLON.Color3.FromArray(key.values);
  32882. break;
  32883. case Animation.ANIMATIONTYPE_VECTOR3:
  32884. default:
  32885. data = BABYLON.Vector3.FromArray(key.values);
  32886. break;
  32887. }
  32888. keys.push({
  32889. frame: key.frame,
  32890. value: data
  32891. });
  32892. }
  32893. animation.setKeys(keys);
  32894. if (parsedAnimation.ranges) {
  32895. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  32896. data = parsedAnimation.ranges[index];
  32897. animation.createRange(data.name, data.from, data.to);
  32898. }
  32899. }
  32900. return animation;
  32901. };
  32902. Animation.AppendSerializedAnimations = function (source, destination) {
  32903. if (source.animations) {
  32904. destination.animations = [];
  32905. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  32906. var animation = source.animations[animationIndex];
  32907. destination.animations.push(animation.serialize());
  32908. }
  32909. }
  32910. };
  32911. return Animation;
  32912. }());
  32913. // Statics
  32914. Animation._ANIMATIONTYPE_FLOAT = 0;
  32915. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  32916. Animation._ANIMATIONTYPE_QUATERNION = 2;
  32917. Animation._ANIMATIONTYPE_MATRIX = 3;
  32918. Animation._ANIMATIONTYPE_COLOR3 = 4;
  32919. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  32920. Animation._ANIMATIONTYPE_SIZE = 6;
  32921. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  32922. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  32923. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  32924. BABYLON.Animation = Animation;
  32925. })(BABYLON || (BABYLON = {}));
  32926. //# sourceMappingURL=babylon.animation.js.map
  32927. var BABYLON;
  32928. (function (BABYLON) {
  32929. var Animatable = (function () {
  32930. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  32931. if (fromFrame === void 0) { fromFrame = 0; }
  32932. if (toFrame === void 0) { toFrame = 100; }
  32933. if (loopAnimation === void 0) { loopAnimation = false; }
  32934. if (speedRatio === void 0) { speedRatio = 1.0; }
  32935. this.target = target;
  32936. this.fromFrame = fromFrame;
  32937. this.toFrame = toFrame;
  32938. this.loopAnimation = loopAnimation;
  32939. this.speedRatio = speedRatio;
  32940. this.onAnimationEnd = onAnimationEnd;
  32941. this._animations = new Array();
  32942. this._paused = false;
  32943. this.animationStarted = false;
  32944. if (animations) {
  32945. this.appendAnimations(target, animations);
  32946. }
  32947. this._scene = scene;
  32948. scene._activeAnimatables.push(this);
  32949. }
  32950. // Methods
  32951. Animatable.prototype.getAnimations = function () {
  32952. return this._animations;
  32953. };
  32954. Animatable.prototype.appendAnimations = function (target, animations) {
  32955. for (var index = 0; index < animations.length; index++) {
  32956. var animation = animations[index];
  32957. animation._target = target;
  32958. this._animations.push(animation);
  32959. }
  32960. };
  32961. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  32962. var animations = this._animations;
  32963. for (var index = 0; index < animations.length; index++) {
  32964. if (animations[index].targetProperty === property) {
  32965. return animations[index];
  32966. }
  32967. }
  32968. return null;
  32969. };
  32970. Animatable.prototype.reset = function () {
  32971. var animations = this._animations;
  32972. for (var index = 0; index < animations.length; index++) {
  32973. animations[index].reset();
  32974. }
  32975. this._localDelayOffset = null;
  32976. this._pausedDelay = null;
  32977. };
  32978. Animatable.prototype.enableBlending = function (blendingSpeed) {
  32979. var animations = this._animations;
  32980. for (var index = 0; index < animations.length; index++) {
  32981. animations[index].enableBlending = true;
  32982. animations[index].blendingSpeed = blendingSpeed;
  32983. }
  32984. };
  32985. Animatable.prototype.disableBlending = function () {
  32986. var animations = this._animations;
  32987. for (var index = 0; index < animations.length; index++) {
  32988. animations[index].enableBlending = false;
  32989. }
  32990. };
  32991. Animatable.prototype.goToFrame = function (frame) {
  32992. var animations = this._animations;
  32993. if (animations[0]) {
  32994. var fps = animations[0].framePerSecond;
  32995. var currentFrame = animations[0].currentFrame;
  32996. var adjustTime = frame - currentFrame;
  32997. var delay = adjustTime * 1000 / fps;
  32998. this._localDelayOffset -= delay;
  32999. }
  33000. for (var index = 0; index < animations.length; index++) {
  33001. animations[index].goToFrame(frame);
  33002. }
  33003. };
  33004. Animatable.prototype.pause = function () {
  33005. if (this._paused) {
  33006. return;
  33007. }
  33008. this._paused = true;
  33009. };
  33010. Animatable.prototype.restart = function () {
  33011. this._paused = false;
  33012. };
  33013. Animatable.prototype.stop = function (animationName) {
  33014. if (animationName) {
  33015. var idx = this._scene._activeAnimatables.indexOf(this);
  33016. if (idx > -1) {
  33017. var animations = this._animations;
  33018. for (var index = animations.length - 1; index >= 0; index--) {
  33019. if (typeof animationName === "string" && animations[index].name != animationName) {
  33020. continue;
  33021. }
  33022. animations[index].reset();
  33023. animations.splice(index, 1);
  33024. }
  33025. if (animations.length == 0) {
  33026. this._scene._activeAnimatables.splice(idx, 1);
  33027. if (this.onAnimationEnd) {
  33028. this.onAnimationEnd();
  33029. }
  33030. }
  33031. }
  33032. }
  33033. else {
  33034. var index = this._scene._activeAnimatables.indexOf(this);
  33035. if (index > -1) {
  33036. this._scene._activeAnimatables.splice(index, 1);
  33037. var animations = this._animations;
  33038. for (var index = 0; index < animations.length; index++) {
  33039. animations[index].reset();
  33040. }
  33041. if (this.onAnimationEnd) {
  33042. this.onAnimationEnd();
  33043. }
  33044. }
  33045. }
  33046. };
  33047. Animatable.prototype._animate = function (delay) {
  33048. if (this._paused) {
  33049. this.animationStarted = false;
  33050. if (!this._pausedDelay) {
  33051. this._pausedDelay = delay;
  33052. }
  33053. return true;
  33054. }
  33055. if (!this._localDelayOffset) {
  33056. this._localDelayOffset = delay;
  33057. }
  33058. else if (this._pausedDelay) {
  33059. this._localDelayOffset += delay - this._pausedDelay;
  33060. this._pausedDelay = null;
  33061. }
  33062. // Animating
  33063. var running = false;
  33064. var animations = this._animations;
  33065. var index;
  33066. for (index = 0; index < animations.length; index++) {
  33067. var animation = animations[index];
  33068. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  33069. running = running || isRunning;
  33070. }
  33071. this.animationStarted = running;
  33072. if (!running) {
  33073. // Remove from active animatables
  33074. index = this._scene._activeAnimatables.indexOf(this);
  33075. this._scene._activeAnimatables.splice(index, 1);
  33076. }
  33077. if (!running && this.onAnimationEnd) {
  33078. this.onAnimationEnd();
  33079. this.onAnimationEnd = null;
  33080. }
  33081. return running;
  33082. };
  33083. return Animatable;
  33084. }());
  33085. BABYLON.Animatable = Animatable;
  33086. })(BABYLON || (BABYLON = {}));
  33087. //# sourceMappingURL=babylon.animatable.js.map
  33088. var BABYLON;
  33089. (function (BABYLON) {
  33090. var EasingFunction = (function () {
  33091. function EasingFunction() {
  33092. // Properties
  33093. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  33094. }
  33095. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  33096. get: function () {
  33097. return EasingFunction._EASINGMODE_EASEIN;
  33098. },
  33099. enumerable: true,
  33100. configurable: true
  33101. });
  33102. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  33103. get: function () {
  33104. return EasingFunction._EASINGMODE_EASEOUT;
  33105. },
  33106. enumerable: true,
  33107. configurable: true
  33108. });
  33109. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  33110. get: function () {
  33111. return EasingFunction._EASINGMODE_EASEINOUT;
  33112. },
  33113. enumerable: true,
  33114. configurable: true
  33115. });
  33116. EasingFunction.prototype.setEasingMode = function (easingMode) {
  33117. var n = Math.min(Math.max(easingMode, 0), 2);
  33118. this._easingMode = n;
  33119. };
  33120. EasingFunction.prototype.getEasingMode = function () {
  33121. return this._easingMode;
  33122. };
  33123. EasingFunction.prototype.easeInCore = function (gradient) {
  33124. throw new Error('You must implement this method');
  33125. };
  33126. EasingFunction.prototype.ease = function (gradient) {
  33127. switch (this._easingMode) {
  33128. case EasingFunction.EASINGMODE_EASEIN:
  33129. return this.easeInCore(gradient);
  33130. case EasingFunction.EASINGMODE_EASEOUT:
  33131. return (1 - this.easeInCore(1 - gradient));
  33132. }
  33133. if (gradient >= 0.5) {
  33134. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  33135. }
  33136. return (this.easeInCore(gradient * 2) * 0.5);
  33137. };
  33138. return EasingFunction;
  33139. }());
  33140. //Statics
  33141. EasingFunction._EASINGMODE_EASEIN = 0;
  33142. EasingFunction._EASINGMODE_EASEOUT = 1;
  33143. EasingFunction._EASINGMODE_EASEINOUT = 2;
  33144. BABYLON.EasingFunction = EasingFunction;
  33145. var CircleEase = (function (_super) {
  33146. __extends(CircleEase, _super);
  33147. function CircleEase() {
  33148. return _super !== null && _super.apply(this, arguments) || this;
  33149. }
  33150. CircleEase.prototype.easeInCore = function (gradient) {
  33151. gradient = Math.max(0, Math.min(1, gradient));
  33152. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  33153. };
  33154. return CircleEase;
  33155. }(EasingFunction));
  33156. BABYLON.CircleEase = CircleEase;
  33157. var BackEase = (function (_super) {
  33158. __extends(BackEase, _super);
  33159. function BackEase(amplitude) {
  33160. if (amplitude === void 0) { amplitude = 1; }
  33161. var _this = _super.call(this) || this;
  33162. _this.amplitude = amplitude;
  33163. return _this;
  33164. }
  33165. BackEase.prototype.easeInCore = function (gradient) {
  33166. var num = Math.max(0, this.amplitude);
  33167. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  33168. };
  33169. return BackEase;
  33170. }(EasingFunction));
  33171. BABYLON.BackEase = BackEase;
  33172. var BounceEase = (function (_super) {
  33173. __extends(BounceEase, _super);
  33174. function BounceEase(bounces, bounciness) {
  33175. if (bounces === void 0) { bounces = 3; }
  33176. if (bounciness === void 0) { bounciness = 2; }
  33177. var _this = _super.call(this) || this;
  33178. _this.bounces = bounces;
  33179. _this.bounciness = bounciness;
  33180. return _this;
  33181. }
  33182. BounceEase.prototype.easeInCore = function (gradient) {
  33183. var y = Math.max(0.0, this.bounces);
  33184. var bounciness = this.bounciness;
  33185. if (bounciness <= 1.0) {
  33186. bounciness = 1.001;
  33187. }
  33188. var num9 = Math.pow(bounciness, y);
  33189. var num5 = 1.0 - bounciness;
  33190. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  33191. var num15 = gradient * num4;
  33192. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  33193. var num3 = Math.floor(num65);
  33194. var num13 = num3 + 1.0;
  33195. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  33196. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  33197. var num7 = (num8 + num12) * 0.5;
  33198. var num6 = gradient - num7;
  33199. var num2 = num7 - num8;
  33200. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  33201. };
  33202. return BounceEase;
  33203. }(EasingFunction));
  33204. BABYLON.BounceEase = BounceEase;
  33205. var CubicEase = (function (_super) {
  33206. __extends(CubicEase, _super);
  33207. function CubicEase() {
  33208. return _super !== null && _super.apply(this, arguments) || this;
  33209. }
  33210. CubicEase.prototype.easeInCore = function (gradient) {
  33211. return (gradient * gradient * gradient);
  33212. };
  33213. return CubicEase;
  33214. }(EasingFunction));
  33215. BABYLON.CubicEase = CubicEase;
  33216. var ElasticEase = (function (_super) {
  33217. __extends(ElasticEase, _super);
  33218. function ElasticEase(oscillations, springiness) {
  33219. if (oscillations === void 0) { oscillations = 3; }
  33220. if (springiness === void 0) { springiness = 3; }
  33221. var _this = _super.call(this) || this;
  33222. _this.oscillations = oscillations;
  33223. _this.springiness = springiness;
  33224. return _this;
  33225. }
  33226. ElasticEase.prototype.easeInCore = function (gradient) {
  33227. var num2;
  33228. var num3 = Math.max(0.0, this.oscillations);
  33229. var num = Math.max(0.0, this.springiness);
  33230. if (num == 0) {
  33231. num2 = gradient;
  33232. }
  33233. else {
  33234. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  33235. }
  33236. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  33237. };
  33238. return ElasticEase;
  33239. }(EasingFunction));
  33240. BABYLON.ElasticEase = ElasticEase;
  33241. var ExponentialEase = (function (_super) {
  33242. __extends(ExponentialEase, _super);
  33243. function ExponentialEase(exponent) {
  33244. if (exponent === void 0) { exponent = 2; }
  33245. var _this = _super.call(this) || this;
  33246. _this.exponent = exponent;
  33247. return _this;
  33248. }
  33249. ExponentialEase.prototype.easeInCore = function (gradient) {
  33250. if (this.exponent <= 0) {
  33251. return gradient;
  33252. }
  33253. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  33254. };
  33255. return ExponentialEase;
  33256. }(EasingFunction));
  33257. BABYLON.ExponentialEase = ExponentialEase;
  33258. var PowerEase = (function (_super) {
  33259. __extends(PowerEase, _super);
  33260. function PowerEase(power) {
  33261. if (power === void 0) { power = 2; }
  33262. var _this = _super.call(this) || this;
  33263. _this.power = power;
  33264. return _this;
  33265. }
  33266. PowerEase.prototype.easeInCore = function (gradient) {
  33267. var y = Math.max(0.0, this.power);
  33268. return Math.pow(gradient, y);
  33269. };
  33270. return PowerEase;
  33271. }(EasingFunction));
  33272. BABYLON.PowerEase = PowerEase;
  33273. var QuadraticEase = (function (_super) {
  33274. __extends(QuadraticEase, _super);
  33275. function QuadraticEase() {
  33276. return _super !== null && _super.apply(this, arguments) || this;
  33277. }
  33278. QuadraticEase.prototype.easeInCore = function (gradient) {
  33279. return (gradient * gradient);
  33280. };
  33281. return QuadraticEase;
  33282. }(EasingFunction));
  33283. BABYLON.QuadraticEase = QuadraticEase;
  33284. var QuarticEase = (function (_super) {
  33285. __extends(QuarticEase, _super);
  33286. function QuarticEase() {
  33287. return _super !== null && _super.apply(this, arguments) || this;
  33288. }
  33289. QuarticEase.prototype.easeInCore = function (gradient) {
  33290. return (gradient * gradient * gradient * gradient);
  33291. };
  33292. return QuarticEase;
  33293. }(EasingFunction));
  33294. BABYLON.QuarticEase = QuarticEase;
  33295. var QuinticEase = (function (_super) {
  33296. __extends(QuinticEase, _super);
  33297. function QuinticEase() {
  33298. return _super !== null && _super.apply(this, arguments) || this;
  33299. }
  33300. QuinticEase.prototype.easeInCore = function (gradient) {
  33301. return (gradient * gradient * gradient * gradient * gradient);
  33302. };
  33303. return QuinticEase;
  33304. }(EasingFunction));
  33305. BABYLON.QuinticEase = QuinticEase;
  33306. var SineEase = (function (_super) {
  33307. __extends(SineEase, _super);
  33308. function SineEase() {
  33309. return _super !== null && _super.apply(this, arguments) || this;
  33310. }
  33311. SineEase.prototype.easeInCore = function (gradient) {
  33312. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  33313. };
  33314. return SineEase;
  33315. }(EasingFunction));
  33316. BABYLON.SineEase = SineEase;
  33317. var BezierCurveEase = (function (_super) {
  33318. __extends(BezierCurveEase, _super);
  33319. function BezierCurveEase(x1, y1, x2, y2) {
  33320. if (x1 === void 0) { x1 = 0; }
  33321. if (y1 === void 0) { y1 = 0; }
  33322. if (x2 === void 0) { x2 = 1; }
  33323. if (y2 === void 0) { y2 = 1; }
  33324. var _this = _super.call(this) || this;
  33325. _this.x1 = x1;
  33326. _this.y1 = y1;
  33327. _this.x2 = x2;
  33328. _this.y2 = y2;
  33329. return _this;
  33330. }
  33331. BezierCurveEase.prototype.easeInCore = function (gradient) {
  33332. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  33333. };
  33334. return BezierCurveEase;
  33335. }(EasingFunction));
  33336. BABYLON.BezierCurveEase = BezierCurveEase;
  33337. })(BABYLON || (BABYLON = {}));
  33338. //# sourceMappingURL=babylon.easing.js.map
  33339. var BABYLON;
  33340. (function (BABYLON) {
  33341. var Condition = (function () {
  33342. function Condition(actionManager) {
  33343. this._actionManager = actionManager;
  33344. }
  33345. Condition.prototype.isValid = function () {
  33346. return true;
  33347. };
  33348. Condition.prototype._getProperty = function (propertyPath) {
  33349. return this._actionManager._getProperty(propertyPath);
  33350. };
  33351. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  33352. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33353. };
  33354. Condition.prototype.serialize = function () {
  33355. };
  33356. Condition.prototype._serialize = function (serializedCondition) {
  33357. return {
  33358. type: 2,
  33359. children: [],
  33360. name: serializedCondition.name,
  33361. properties: serializedCondition.properties
  33362. };
  33363. };
  33364. return Condition;
  33365. }());
  33366. BABYLON.Condition = Condition;
  33367. var ValueCondition = (function (_super) {
  33368. __extends(ValueCondition, _super);
  33369. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  33370. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  33371. var _this = _super.call(this, actionManager) || this;
  33372. _this.propertyPath = propertyPath;
  33373. _this.value = value;
  33374. _this.operator = operator;
  33375. _this._target = target;
  33376. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  33377. _this._property = _this._getProperty(_this.propertyPath);
  33378. return _this;
  33379. }
  33380. Object.defineProperty(ValueCondition, "IsEqual", {
  33381. get: function () {
  33382. return ValueCondition._IsEqual;
  33383. },
  33384. enumerable: true,
  33385. configurable: true
  33386. });
  33387. Object.defineProperty(ValueCondition, "IsDifferent", {
  33388. get: function () {
  33389. return ValueCondition._IsDifferent;
  33390. },
  33391. enumerable: true,
  33392. configurable: true
  33393. });
  33394. Object.defineProperty(ValueCondition, "IsGreater", {
  33395. get: function () {
  33396. return ValueCondition._IsGreater;
  33397. },
  33398. enumerable: true,
  33399. configurable: true
  33400. });
  33401. Object.defineProperty(ValueCondition, "IsLesser", {
  33402. get: function () {
  33403. return ValueCondition._IsLesser;
  33404. },
  33405. enumerable: true,
  33406. configurable: true
  33407. });
  33408. // Methods
  33409. ValueCondition.prototype.isValid = function () {
  33410. switch (this.operator) {
  33411. case ValueCondition.IsGreater:
  33412. return this._effectiveTarget[this._property] > this.value;
  33413. case ValueCondition.IsLesser:
  33414. return this._effectiveTarget[this._property] < this.value;
  33415. case ValueCondition.IsEqual:
  33416. case ValueCondition.IsDifferent:
  33417. var check;
  33418. if (this.value.equals) {
  33419. check = this.value.equals(this._effectiveTarget[this._property]);
  33420. }
  33421. else {
  33422. check = this.value === this._effectiveTarget[this._property];
  33423. }
  33424. return this.operator === ValueCondition.IsEqual ? check : !check;
  33425. }
  33426. return false;
  33427. };
  33428. ValueCondition.prototype.serialize = function () {
  33429. return this._serialize({
  33430. name: "ValueCondition",
  33431. properties: [
  33432. BABYLON.Action._GetTargetProperty(this._target),
  33433. { name: "propertyPath", value: this.propertyPath },
  33434. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33435. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  33436. ]
  33437. });
  33438. };
  33439. ValueCondition.GetOperatorName = function (operator) {
  33440. switch (operator) {
  33441. case ValueCondition._IsEqual: return "IsEqual";
  33442. case ValueCondition._IsDifferent: return "IsDifferent";
  33443. case ValueCondition._IsGreater: return "IsGreater";
  33444. case ValueCondition._IsLesser: return "IsLesser";
  33445. default: return "";
  33446. }
  33447. };
  33448. return ValueCondition;
  33449. }(Condition));
  33450. // Statics
  33451. ValueCondition._IsEqual = 0;
  33452. ValueCondition._IsDifferent = 1;
  33453. ValueCondition._IsGreater = 2;
  33454. ValueCondition._IsLesser = 3;
  33455. BABYLON.ValueCondition = ValueCondition;
  33456. var PredicateCondition = (function (_super) {
  33457. __extends(PredicateCondition, _super);
  33458. function PredicateCondition(actionManager, predicate) {
  33459. var _this = _super.call(this, actionManager) || this;
  33460. _this.predicate = predicate;
  33461. return _this;
  33462. }
  33463. PredicateCondition.prototype.isValid = function () {
  33464. return this.predicate();
  33465. };
  33466. return PredicateCondition;
  33467. }(Condition));
  33468. BABYLON.PredicateCondition = PredicateCondition;
  33469. var StateCondition = (function (_super) {
  33470. __extends(StateCondition, _super);
  33471. function StateCondition(actionManager, target, value) {
  33472. var _this = _super.call(this, actionManager) || this;
  33473. _this.value = value;
  33474. _this._target = target;
  33475. return _this;
  33476. }
  33477. // Methods
  33478. StateCondition.prototype.isValid = function () {
  33479. return this._target.state === this.value;
  33480. };
  33481. StateCondition.prototype.serialize = function () {
  33482. return this._serialize({
  33483. name: "StateCondition",
  33484. properties: [
  33485. BABYLON.Action._GetTargetProperty(this._target),
  33486. { name: "value", value: this.value }
  33487. ]
  33488. });
  33489. };
  33490. return StateCondition;
  33491. }(Condition));
  33492. BABYLON.StateCondition = StateCondition;
  33493. })(BABYLON || (BABYLON = {}));
  33494. //# sourceMappingURL=babylon.condition.js.map
  33495. var BABYLON;
  33496. (function (BABYLON) {
  33497. var Action = (function () {
  33498. function Action(triggerOptions, condition) {
  33499. this.triggerOptions = triggerOptions;
  33500. if (triggerOptions.parameter) {
  33501. this.trigger = triggerOptions.trigger;
  33502. this._triggerParameter = triggerOptions.parameter;
  33503. }
  33504. else {
  33505. this.trigger = triggerOptions;
  33506. }
  33507. this._nextActiveAction = this;
  33508. this._condition = condition;
  33509. }
  33510. // Methods
  33511. Action.prototype._prepare = function () {
  33512. };
  33513. Action.prototype.getTriggerParameter = function () {
  33514. return this._triggerParameter;
  33515. };
  33516. Action.prototype._executeCurrent = function (evt) {
  33517. if (this._nextActiveAction._condition) {
  33518. var condition = this._nextActiveAction._condition;
  33519. var currentRenderId = this._actionManager.getScene().getRenderId();
  33520. // We cache the current evaluation for the current frame
  33521. if (condition._evaluationId === currentRenderId) {
  33522. if (!condition._currentResult) {
  33523. return;
  33524. }
  33525. }
  33526. else {
  33527. condition._evaluationId = currentRenderId;
  33528. if (!condition.isValid()) {
  33529. condition._currentResult = false;
  33530. return;
  33531. }
  33532. condition._currentResult = true;
  33533. }
  33534. }
  33535. this._nextActiveAction.execute(evt);
  33536. this.skipToNextActiveAction();
  33537. };
  33538. Action.prototype.execute = function (evt) {
  33539. };
  33540. Action.prototype.skipToNextActiveAction = function () {
  33541. if (this._nextActiveAction._child) {
  33542. if (!this._nextActiveAction._child._actionManager) {
  33543. this._nextActiveAction._child._actionManager = this._actionManager;
  33544. }
  33545. this._nextActiveAction = this._nextActiveAction._child;
  33546. }
  33547. else {
  33548. this._nextActiveAction = this;
  33549. }
  33550. };
  33551. Action.prototype.then = function (action) {
  33552. this._child = action;
  33553. action._actionManager = this._actionManager;
  33554. action._prepare();
  33555. return action;
  33556. };
  33557. Action.prototype._getProperty = function (propertyPath) {
  33558. return this._actionManager._getProperty(propertyPath);
  33559. };
  33560. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  33561. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33562. };
  33563. Action.prototype.serialize = function (parent) {
  33564. };
  33565. // Called by BABYLON.Action objects in serialize(...). Internal use
  33566. Action.prototype._serialize = function (serializedAction, parent) {
  33567. var serializationObject = {
  33568. type: 1,
  33569. children: [],
  33570. name: serializedAction.name,
  33571. properties: serializedAction.properties || []
  33572. };
  33573. // Serialize child
  33574. if (this._child) {
  33575. this._child.serialize(serializationObject);
  33576. }
  33577. // Check if "this" has a condition
  33578. if (this._condition) {
  33579. var serializedCondition = this._condition.serialize();
  33580. serializedCondition.children.push(serializationObject);
  33581. if (parent) {
  33582. parent.children.push(serializedCondition);
  33583. }
  33584. return serializedCondition;
  33585. }
  33586. if (parent) {
  33587. parent.children.push(serializationObject);
  33588. }
  33589. return serializationObject;
  33590. };
  33591. return Action;
  33592. }());
  33593. Action._SerializeValueAsString = function (value) {
  33594. if (typeof value === "number") {
  33595. return value.toString();
  33596. }
  33597. if (typeof value === "boolean") {
  33598. return value ? "true" : "false";
  33599. }
  33600. if (value instanceof BABYLON.Vector2) {
  33601. return value.x + ", " + value.y;
  33602. }
  33603. if (value instanceof BABYLON.Vector3) {
  33604. return value.x + ", " + value.y + ", " + value.z;
  33605. }
  33606. if (value instanceof BABYLON.Color3) {
  33607. return value.r + ", " + value.g + ", " + value.b;
  33608. }
  33609. if (value instanceof BABYLON.Color4) {
  33610. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  33611. }
  33612. return value; // string
  33613. };
  33614. Action._GetTargetProperty = function (target) {
  33615. return {
  33616. name: "target",
  33617. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  33618. : target instanceof BABYLON.Light ? "LightProperties"
  33619. : target instanceof BABYLON.Camera ? "CameraProperties"
  33620. : "SceneProperties",
  33621. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  33622. };
  33623. };
  33624. BABYLON.Action = Action;
  33625. })(BABYLON || (BABYLON = {}));
  33626. //# sourceMappingURL=babylon.action.js.map
  33627. var BABYLON;
  33628. (function (BABYLON) {
  33629. /**
  33630. * ActionEvent is the event beint sent when an action is triggered.
  33631. */
  33632. var ActionEvent = (function () {
  33633. /**
  33634. * @constructor
  33635. * @param source The mesh or sprite that triggered the action.
  33636. * @param pointerX The X mouse cursor position at the time of the event
  33637. * @param pointerY The Y mouse cursor position at the time of the event
  33638. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  33639. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  33640. */
  33641. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  33642. this.source = source;
  33643. this.pointerX = pointerX;
  33644. this.pointerY = pointerY;
  33645. this.meshUnderPointer = meshUnderPointer;
  33646. this.sourceEvent = sourceEvent;
  33647. this.additionalData = additionalData;
  33648. }
  33649. /**
  33650. * Helper function to auto-create an ActionEvent from a source mesh.
  33651. * @param source The source mesh that triggered the event
  33652. * @param evt {Event} The original (browser) event
  33653. */
  33654. ActionEvent.CreateNew = function (source, evt, additionalData) {
  33655. var scene = source.getScene();
  33656. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33657. };
  33658. /**
  33659. * Helper function to auto-create an ActionEvent from a source mesh.
  33660. * @param source The source sprite that triggered the event
  33661. * @param scene Scene associated with the sprite
  33662. * @param evt {Event} The original (browser) event
  33663. */
  33664. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  33665. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33666. };
  33667. /**
  33668. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  33669. * @param scene the scene where the event occurred
  33670. * @param evt {Event} The original (browser) event
  33671. */
  33672. ActionEvent.CreateNewFromScene = function (scene, evt) {
  33673. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  33674. };
  33675. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  33676. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  33677. };
  33678. return ActionEvent;
  33679. }());
  33680. BABYLON.ActionEvent = ActionEvent;
  33681. /**
  33682. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  33683. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  33684. */
  33685. var ActionManager = (function () {
  33686. function ActionManager(scene) {
  33687. // Members
  33688. this.actions = new Array();
  33689. this.hoverCursor = '';
  33690. this._scene = scene;
  33691. scene._actionManagers.push(this);
  33692. }
  33693. Object.defineProperty(ActionManager, "NothingTrigger", {
  33694. get: function () {
  33695. return ActionManager._NothingTrigger;
  33696. },
  33697. enumerable: true,
  33698. configurable: true
  33699. });
  33700. Object.defineProperty(ActionManager, "OnPickTrigger", {
  33701. get: function () {
  33702. return ActionManager._OnPickTrigger;
  33703. },
  33704. enumerable: true,
  33705. configurable: true
  33706. });
  33707. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  33708. get: function () {
  33709. return ActionManager._OnLeftPickTrigger;
  33710. },
  33711. enumerable: true,
  33712. configurable: true
  33713. });
  33714. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  33715. get: function () {
  33716. return ActionManager._OnRightPickTrigger;
  33717. },
  33718. enumerable: true,
  33719. configurable: true
  33720. });
  33721. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  33722. get: function () {
  33723. return ActionManager._OnCenterPickTrigger;
  33724. },
  33725. enumerable: true,
  33726. configurable: true
  33727. });
  33728. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  33729. get: function () {
  33730. return ActionManager._OnPickDownTrigger;
  33731. },
  33732. enumerable: true,
  33733. configurable: true
  33734. });
  33735. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  33736. get: function () {
  33737. return ActionManager._OnDoublePickTrigger;
  33738. },
  33739. enumerable: true,
  33740. configurable: true
  33741. });
  33742. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  33743. get: function () {
  33744. return ActionManager._OnPickUpTrigger;
  33745. },
  33746. enumerable: true,
  33747. configurable: true
  33748. });
  33749. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  33750. /// This trigger will only be raised if you also declared a OnPickDown
  33751. get: function () {
  33752. return ActionManager._OnPickOutTrigger;
  33753. },
  33754. enumerable: true,
  33755. configurable: true
  33756. });
  33757. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  33758. get: function () {
  33759. return ActionManager._OnLongPressTrigger;
  33760. },
  33761. enumerable: true,
  33762. configurable: true
  33763. });
  33764. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  33765. get: function () {
  33766. return ActionManager._OnPointerOverTrigger;
  33767. },
  33768. enumerable: true,
  33769. configurable: true
  33770. });
  33771. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  33772. get: function () {
  33773. return ActionManager._OnPointerOutTrigger;
  33774. },
  33775. enumerable: true,
  33776. configurable: true
  33777. });
  33778. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  33779. get: function () {
  33780. return ActionManager._OnEveryFrameTrigger;
  33781. },
  33782. enumerable: true,
  33783. configurable: true
  33784. });
  33785. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  33786. get: function () {
  33787. return ActionManager._OnIntersectionEnterTrigger;
  33788. },
  33789. enumerable: true,
  33790. configurable: true
  33791. });
  33792. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  33793. get: function () {
  33794. return ActionManager._OnIntersectionExitTrigger;
  33795. },
  33796. enumerable: true,
  33797. configurable: true
  33798. });
  33799. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  33800. get: function () {
  33801. return ActionManager._OnKeyDownTrigger;
  33802. },
  33803. enumerable: true,
  33804. configurable: true
  33805. });
  33806. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  33807. get: function () {
  33808. return ActionManager._OnKeyUpTrigger;
  33809. },
  33810. enumerable: true,
  33811. configurable: true
  33812. });
  33813. // Methods
  33814. ActionManager.prototype.dispose = function () {
  33815. var index = this._scene._actionManagers.indexOf(this);
  33816. for (var i = 0; i < this.actions.length; i++) {
  33817. var action = this.actions[i];
  33818. ActionManager.Triggers[action.trigger]--;
  33819. if (ActionManager.Triggers[action.trigger] === 0) {
  33820. delete ActionManager.Triggers[action.trigger];
  33821. }
  33822. }
  33823. if (index > -1) {
  33824. this._scene._actionManagers.splice(index, 1);
  33825. }
  33826. };
  33827. ActionManager.prototype.getScene = function () {
  33828. return this._scene;
  33829. };
  33830. /**
  33831. * Does this action manager handles actions of any of the given triggers
  33832. * @param {number[]} triggers - the triggers to be tested
  33833. * @return {boolean} whether one (or more) of the triggers is handeled
  33834. */
  33835. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  33836. for (var index = 0; index < this.actions.length; index++) {
  33837. var action = this.actions[index];
  33838. if (triggers.indexOf(action.trigger) > -1) {
  33839. return true;
  33840. }
  33841. }
  33842. return false;
  33843. };
  33844. /**
  33845. * Does this action manager handles actions of a given trigger
  33846. * @param {number} trigger - the trigger to be tested
  33847. * @return {boolean} whether the trigger is handeled
  33848. */
  33849. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  33850. for (var index = 0; index < this.actions.length; index++) {
  33851. var action = this.actions[index];
  33852. if (action.trigger === trigger) {
  33853. return true;
  33854. }
  33855. }
  33856. return false;
  33857. };
  33858. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  33859. /**
  33860. * Does this action manager has pointer triggers
  33861. * @return {boolean} whether or not it has pointer triggers
  33862. */
  33863. get: function () {
  33864. for (var index = 0; index < this.actions.length; index++) {
  33865. var action = this.actions[index];
  33866. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  33867. return true;
  33868. }
  33869. }
  33870. return false;
  33871. },
  33872. enumerable: true,
  33873. configurable: true
  33874. });
  33875. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  33876. /**
  33877. * Does this action manager has pick triggers
  33878. * @return {boolean} whether or not it has pick triggers
  33879. */
  33880. get: function () {
  33881. for (var index = 0; index < this.actions.length; index++) {
  33882. var action = this.actions[index];
  33883. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  33884. return true;
  33885. }
  33886. }
  33887. return false;
  33888. },
  33889. enumerable: true,
  33890. configurable: true
  33891. });
  33892. Object.defineProperty(ActionManager, "HasTriggers", {
  33893. /**
  33894. * Does exist one action manager with at least one trigger
  33895. * @return {boolean} whether or not it exists one action manager with one trigger
  33896. **/
  33897. get: function () {
  33898. for (var t in ActionManager.Triggers) {
  33899. if (ActionManager.Triggers.hasOwnProperty(t)) {
  33900. return true;
  33901. }
  33902. }
  33903. return false;
  33904. },
  33905. enumerable: true,
  33906. configurable: true
  33907. });
  33908. Object.defineProperty(ActionManager, "HasPickTriggers", {
  33909. /**
  33910. * Does exist one action manager with at least one pick trigger
  33911. * @return {boolean} whether or not it exists one action manager with one pick trigger
  33912. **/
  33913. get: function () {
  33914. for (var t in ActionManager.Triggers) {
  33915. if (ActionManager.Triggers.hasOwnProperty(t)) {
  33916. var t_int = parseInt(t);
  33917. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  33918. return true;
  33919. }
  33920. }
  33921. }
  33922. return false;
  33923. },
  33924. enumerable: true,
  33925. configurable: true
  33926. });
  33927. /**
  33928. * Does exist one action manager that handles actions of a given trigger
  33929. * @param {number} trigger - the trigger to be tested
  33930. * @return {boolean} whether the trigger is handeled by at least one action manager
  33931. **/
  33932. ActionManager.HasSpecificTrigger = function (trigger) {
  33933. for (var t in ActionManager.Triggers) {
  33934. if (ActionManager.Triggers.hasOwnProperty(t)) {
  33935. var t_int = parseInt(t);
  33936. if (t_int === trigger) {
  33937. return true;
  33938. }
  33939. }
  33940. }
  33941. return false;
  33942. };
  33943. /**
  33944. * Registers an action to this action manager
  33945. * @param {BABYLON.Action} action - the action to be registered
  33946. * @return {BABYLON.Action} the action amended (prepared) after registration
  33947. */
  33948. ActionManager.prototype.registerAction = function (action) {
  33949. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  33950. if (this.getScene().actionManager !== this) {
  33951. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  33952. return null;
  33953. }
  33954. }
  33955. this.actions.push(action);
  33956. if (ActionManager.Triggers[action.trigger]) {
  33957. ActionManager.Triggers[action.trigger]++;
  33958. }
  33959. else {
  33960. ActionManager.Triggers[action.trigger] = 1;
  33961. }
  33962. action._actionManager = this;
  33963. action._prepare();
  33964. return action;
  33965. };
  33966. /**
  33967. * Process a specific trigger
  33968. * @param {number} trigger - the trigger to process
  33969. * @param evt {BABYLON.ActionEvent} the event details to be processed
  33970. */
  33971. ActionManager.prototype.processTrigger = function (trigger, evt) {
  33972. for (var index = 0; index < this.actions.length; index++) {
  33973. var action = this.actions[index];
  33974. if (action.trigger === trigger) {
  33975. if (trigger === ActionManager.OnKeyUpTrigger
  33976. || trigger === ActionManager.OnKeyDownTrigger) {
  33977. var parameter = action.getTriggerParameter();
  33978. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  33979. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  33980. var actualkey = String.fromCharCode(unicode).toLowerCase();
  33981. if (actualkey !== parameter.toLowerCase()) {
  33982. continue;
  33983. }
  33984. }
  33985. }
  33986. action._executeCurrent(evt);
  33987. }
  33988. }
  33989. };
  33990. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  33991. var properties = propertyPath.split(".");
  33992. for (var index = 0; index < properties.length - 1; index++) {
  33993. target = target[properties[index]];
  33994. }
  33995. return target;
  33996. };
  33997. ActionManager.prototype._getProperty = function (propertyPath) {
  33998. var properties = propertyPath.split(".");
  33999. return properties[properties.length - 1];
  34000. };
  34001. ActionManager.prototype.serialize = function (name) {
  34002. var root = {
  34003. children: [],
  34004. name: name,
  34005. type: 3,
  34006. properties: [] // Empty for root but required
  34007. };
  34008. for (var i = 0; i < this.actions.length; i++) {
  34009. var triggerObject = {
  34010. type: 0,
  34011. children: [],
  34012. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  34013. properties: []
  34014. };
  34015. var triggerOptions = this.actions[i].triggerOptions;
  34016. if (triggerOptions && typeof triggerOptions !== "number") {
  34017. if (triggerOptions.parameter instanceof BABYLON.Node) {
  34018. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  34019. }
  34020. else {
  34021. var parameter = {};
  34022. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  34023. if (triggerOptions.parameter.mesh) {
  34024. parameter._meshId = triggerOptions.parameter.mesh.id;
  34025. }
  34026. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  34027. }
  34028. }
  34029. // Serialize child action, recursively
  34030. this.actions[i].serialize(triggerObject);
  34031. // Add serialized trigger
  34032. root.children.push(triggerObject);
  34033. }
  34034. return root;
  34035. };
  34036. ActionManager.Parse = function (parsedActions, object, scene) {
  34037. var actionManager = new BABYLON.ActionManager(scene);
  34038. if (object === null)
  34039. scene.actionManager = actionManager;
  34040. else
  34041. object.actionManager = actionManager;
  34042. // instanciate a new object
  34043. var instanciate = function (name, params) {
  34044. var newInstance = Object.create(BABYLON[name].prototype);
  34045. newInstance.constructor.apply(newInstance, params);
  34046. return newInstance;
  34047. };
  34048. var parseParameter = function (name, value, target, propertyPath) {
  34049. if (propertyPath === null) {
  34050. // String, boolean or float
  34051. var floatValue = parseFloat(value);
  34052. if (value === "true" || value === "false")
  34053. return value === "true";
  34054. else
  34055. return isNaN(floatValue) ? value : floatValue;
  34056. }
  34057. var effectiveTarget = propertyPath.split(".");
  34058. var values = value.split(",");
  34059. // Get effective Target
  34060. for (var i = 0; i < effectiveTarget.length; i++) {
  34061. target = target[effectiveTarget[i]];
  34062. }
  34063. // Return appropriate value with its type
  34064. if (typeof (target) === "boolean")
  34065. return values[0] === "true";
  34066. if (typeof (target) === "string")
  34067. return values[0];
  34068. // Parameters with multiple values such as Vector3 etc.
  34069. var split = new Array();
  34070. for (var i = 0; i < values.length; i++)
  34071. split.push(parseFloat(values[i]));
  34072. if (target instanceof BABYLON.Vector3)
  34073. return BABYLON.Vector3.FromArray(split);
  34074. if (target instanceof BABYLON.Vector4)
  34075. return BABYLON.Vector4.FromArray(split);
  34076. if (target instanceof BABYLON.Color3)
  34077. return BABYLON.Color3.FromArray(split);
  34078. if (target instanceof BABYLON.Color4)
  34079. return BABYLON.Color4.FromArray(split);
  34080. return parseFloat(values[0]);
  34081. };
  34082. // traverse graph per trigger
  34083. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  34084. if (combineArray === void 0) { combineArray = null; }
  34085. if (parsedAction.detached)
  34086. return;
  34087. var parameters = new Array();
  34088. var target = null;
  34089. var propertyPath = null;
  34090. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  34091. // Parameters
  34092. if (parsedAction.type === 2)
  34093. parameters.push(actionManager);
  34094. else
  34095. parameters.push(trigger);
  34096. if (combine) {
  34097. var actions = new Array();
  34098. for (var j = 0; j < parsedAction.combine.length; j++) {
  34099. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  34100. }
  34101. parameters.push(actions);
  34102. }
  34103. else {
  34104. for (var i = 0; i < parsedAction.properties.length; i++) {
  34105. var value = parsedAction.properties[i].value;
  34106. var name = parsedAction.properties[i].name;
  34107. var targetType = parsedAction.properties[i].targetType;
  34108. if (name === "target")
  34109. if (targetType !== null && targetType === "SceneProperties")
  34110. value = target = scene;
  34111. else
  34112. value = target = scene.getNodeByName(value);
  34113. else if (name === "parent")
  34114. value = scene.getNodeByName(value);
  34115. else if (name === "sound")
  34116. value = scene.getSoundByName(value);
  34117. else if (name !== "propertyPath") {
  34118. if (parsedAction.type === 2 && name === "operator")
  34119. value = BABYLON.ValueCondition[value];
  34120. else
  34121. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  34122. }
  34123. else {
  34124. propertyPath = value;
  34125. }
  34126. parameters.push(value);
  34127. }
  34128. }
  34129. if (combineArray === null) {
  34130. parameters.push(condition);
  34131. }
  34132. else {
  34133. parameters.push(null);
  34134. }
  34135. // If interpolate value action
  34136. if (parsedAction.name === "InterpolateValueAction") {
  34137. var param = parameters[parameters.length - 2];
  34138. parameters[parameters.length - 1] = param;
  34139. parameters[parameters.length - 2] = condition;
  34140. }
  34141. // Action or condition(s) and not CombineAction
  34142. var newAction = instanciate(parsedAction.name, parameters);
  34143. if (newAction instanceof BABYLON.Condition && condition !== null) {
  34144. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  34145. if (action)
  34146. action.then(nothing);
  34147. else
  34148. actionManager.registerAction(nothing);
  34149. action = nothing;
  34150. }
  34151. if (combineArray === null) {
  34152. if (newAction instanceof BABYLON.Condition) {
  34153. condition = newAction;
  34154. newAction = action;
  34155. }
  34156. else {
  34157. condition = null;
  34158. if (action)
  34159. action.then(newAction);
  34160. else
  34161. actionManager.registerAction(newAction);
  34162. }
  34163. }
  34164. else {
  34165. combineArray.push(newAction);
  34166. }
  34167. for (var i = 0; i < parsedAction.children.length; i++)
  34168. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  34169. };
  34170. // triggers
  34171. for (var i = 0; i < parsedActions.children.length; i++) {
  34172. var triggerParams;
  34173. var trigger = parsedActions.children[i];
  34174. if (trigger.properties.length > 0) {
  34175. var param = trigger.properties[0].value;
  34176. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  34177. if (value._meshId) {
  34178. value.mesh = scene.getMeshByID(value._meshId);
  34179. }
  34180. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  34181. }
  34182. else
  34183. triggerParams = BABYLON.ActionManager[trigger.name];
  34184. for (var j = 0; j < trigger.children.length; j++) {
  34185. if (!trigger.detached)
  34186. traverse(trigger.children[j], triggerParams, null, null);
  34187. }
  34188. }
  34189. };
  34190. ActionManager.GetTriggerName = function (trigger) {
  34191. switch (trigger) {
  34192. case 0: return "NothingTrigger";
  34193. case 1: return "OnPickTrigger";
  34194. case 2: return "OnLeftPickTrigger";
  34195. case 3: return "OnRightPickTrigger";
  34196. case 4: return "OnCenterPickTrigger";
  34197. case 5: return "OnPickDownTrigger";
  34198. case 6: return "OnPickUpTrigger";
  34199. case 7: return "OnLongPressTrigger";
  34200. case 8: return "OnPointerOverTrigger";
  34201. case 9: return "OnPointerOutTrigger";
  34202. case 10: return "OnEveryFrameTrigger";
  34203. case 11: return "OnIntersectionEnterTrigger";
  34204. case 12: return "OnIntersectionExitTrigger";
  34205. case 13: return "OnKeyDownTrigger";
  34206. case 14: return "OnKeyUpTrigger";
  34207. case 15: return "OnPickOutTrigger";
  34208. default: return "";
  34209. }
  34210. };
  34211. return ActionManager;
  34212. }());
  34213. // Statics
  34214. ActionManager._NothingTrigger = 0;
  34215. ActionManager._OnPickTrigger = 1;
  34216. ActionManager._OnLeftPickTrigger = 2;
  34217. ActionManager._OnRightPickTrigger = 3;
  34218. ActionManager._OnCenterPickTrigger = 4;
  34219. ActionManager._OnPickDownTrigger = 5;
  34220. ActionManager._OnDoublePickTrigger = 6;
  34221. ActionManager._OnPickUpTrigger = 7;
  34222. ActionManager._OnLongPressTrigger = 8;
  34223. ActionManager._OnPointerOverTrigger = 9;
  34224. ActionManager._OnPointerOutTrigger = 10;
  34225. ActionManager._OnEveryFrameTrigger = 11;
  34226. ActionManager._OnIntersectionEnterTrigger = 12;
  34227. ActionManager._OnIntersectionExitTrigger = 13;
  34228. ActionManager._OnKeyDownTrigger = 14;
  34229. ActionManager._OnKeyUpTrigger = 15;
  34230. ActionManager._OnPickOutTrigger = 16;
  34231. ActionManager.Triggers = {};
  34232. BABYLON.ActionManager = ActionManager;
  34233. })(BABYLON || (BABYLON = {}));
  34234. //# sourceMappingURL=babylon.actionManager.js.map
  34235. var BABYLON;
  34236. (function (BABYLON) {
  34237. var InterpolateValueAction = (function (_super) {
  34238. __extends(InterpolateValueAction, _super);
  34239. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  34240. if (duration === void 0) { duration = 1000; }
  34241. var _this = _super.call(this, triggerOptions, condition) || this;
  34242. _this.propertyPath = propertyPath;
  34243. _this.value = value;
  34244. _this.duration = duration;
  34245. _this.stopOtherAnimations = stopOtherAnimations;
  34246. _this.onInterpolationDone = onInterpolationDone;
  34247. _this._target = _this._effectiveTarget = target;
  34248. return _this;
  34249. }
  34250. InterpolateValueAction.prototype._prepare = function () {
  34251. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34252. this._property = this._getProperty(this.propertyPath);
  34253. };
  34254. InterpolateValueAction.prototype.execute = function () {
  34255. var scene = this._actionManager.getScene();
  34256. var keys = [
  34257. {
  34258. frame: 0,
  34259. value: this._effectiveTarget[this._property]
  34260. }, {
  34261. frame: 100,
  34262. value: this.value
  34263. }
  34264. ];
  34265. var dataType;
  34266. if (typeof this.value === "number") {
  34267. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  34268. }
  34269. else if (this.value instanceof BABYLON.Color3) {
  34270. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  34271. }
  34272. else if (this.value instanceof BABYLON.Vector3) {
  34273. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  34274. }
  34275. else if (this.value instanceof BABYLON.Matrix) {
  34276. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  34277. }
  34278. else if (this.value instanceof BABYLON.Quaternion) {
  34279. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  34280. }
  34281. else {
  34282. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  34283. return;
  34284. }
  34285. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  34286. animation.setKeys(keys);
  34287. if (this.stopOtherAnimations) {
  34288. scene.stopAnimation(this._effectiveTarget);
  34289. }
  34290. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  34291. };
  34292. InterpolateValueAction.prototype.serialize = function (parent) {
  34293. return _super.prototype._serialize.call(this, {
  34294. name: "InterpolateValueAction",
  34295. properties: [
  34296. BABYLON.Action._GetTargetProperty(this._target),
  34297. { name: "propertyPath", value: this.propertyPath },
  34298. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34299. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  34300. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  34301. ]
  34302. }, parent);
  34303. };
  34304. return InterpolateValueAction;
  34305. }(BABYLON.Action));
  34306. BABYLON.InterpolateValueAction = InterpolateValueAction;
  34307. })(BABYLON || (BABYLON = {}));
  34308. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  34309. var BABYLON;
  34310. (function (BABYLON) {
  34311. var SwitchBooleanAction = (function (_super) {
  34312. __extends(SwitchBooleanAction, _super);
  34313. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  34314. var _this = _super.call(this, triggerOptions, condition) || this;
  34315. _this.propertyPath = propertyPath;
  34316. _this._target = _this._effectiveTarget = target;
  34317. return _this;
  34318. }
  34319. SwitchBooleanAction.prototype._prepare = function () {
  34320. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34321. this._property = this._getProperty(this.propertyPath);
  34322. };
  34323. SwitchBooleanAction.prototype.execute = function () {
  34324. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  34325. };
  34326. SwitchBooleanAction.prototype.serialize = function (parent) {
  34327. return _super.prototype._serialize.call(this, {
  34328. name: "SwitchBooleanAction",
  34329. properties: [
  34330. BABYLON.Action._GetTargetProperty(this._target),
  34331. { name: "propertyPath", value: this.propertyPath }
  34332. ]
  34333. }, parent);
  34334. };
  34335. return SwitchBooleanAction;
  34336. }(BABYLON.Action));
  34337. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  34338. var SetStateAction = (function (_super) {
  34339. __extends(SetStateAction, _super);
  34340. function SetStateAction(triggerOptions, target, value, condition) {
  34341. var _this = _super.call(this, triggerOptions, condition) || this;
  34342. _this.value = value;
  34343. _this._target = target;
  34344. return _this;
  34345. }
  34346. SetStateAction.prototype.execute = function () {
  34347. this._target.state = this.value;
  34348. };
  34349. SetStateAction.prototype.serialize = function (parent) {
  34350. return _super.prototype._serialize.call(this, {
  34351. name: "SetStateAction",
  34352. properties: [
  34353. BABYLON.Action._GetTargetProperty(this._target),
  34354. { name: "value", value: this.value }
  34355. ]
  34356. }, parent);
  34357. };
  34358. return SetStateAction;
  34359. }(BABYLON.Action));
  34360. BABYLON.SetStateAction = SetStateAction;
  34361. var SetValueAction = (function (_super) {
  34362. __extends(SetValueAction, _super);
  34363. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  34364. var _this = _super.call(this, triggerOptions, condition) || this;
  34365. _this.propertyPath = propertyPath;
  34366. _this.value = value;
  34367. _this._target = _this._effectiveTarget = target;
  34368. return _this;
  34369. }
  34370. SetValueAction.prototype._prepare = function () {
  34371. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34372. this._property = this._getProperty(this.propertyPath);
  34373. };
  34374. SetValueAction.prototype.execute = function () {
  34375. this._effectiveTarget[this._property] = this.value;
  34376. if (this._target.markAsDirty) {
  34377. this._target.markAsDirty(this._property);
  34378. }
  34379. };
  34380. SetValueAction.prototype.serialize = function (parent) {
  34381. return _super.prototype._serialize.call(this, {
  34382. name: "SetValueAction",
  34383. properties: [
  34384. BABYLON.Action._GetTargetProperty(this._target),
  34385. { name: "propertyPath", value: this.propertyPath },
  34386. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34387. ]
  34388. }, parent);
  34389. };
  34390. return SetValueAction;
  34391. }(BABYLON.Action));
  34392. BABYLON.SetValueAction = SetValueAction;
  34393. var IncrementValueAction = (function (_super) {
  34394. __extends(IncrementValueAction, _super);
  34395. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  34396. var _this = _super.call(this, triggerOptions, condition) || this;
  34397. _this.propertyPath = propertyPath;
  34398. _this.value = value;
  34399. _this._target = _this._effectiveTarget = target;
  34400. return _this;
  34401. }
  34402. IncrementValueAction.prototype._prepare = function () {
  34403. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34404. this._property = this._getProperty(this.propertyPath);
  34405. if (typeof this._effectiveTarget[this._property] !== "number") {
  34406. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  34407. }
  34408. };
  34409. IncrementValueAction.prototype.execute = function () {
  34410. this._effectiveTarget[this._property] += this.value;
  34411. if (this._target.markAsDirty) {
  34412. this._target.markAsDirty(this._property);
  34413. }
  34414. };
  34415. IncrementValueAction.prototype.serialize = function (parent) {
  34416. return _super.prototype._serialize.call(this, {
  34417. name: "IncrementValueAction",
  34418. properties: [
  34419. BABYLON.Action._GetTargetProperty(this._target),
  34420. { name: "propertyPath", value: this.propertyPath },
  34421. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34422. ]
  34423. }, parent);
  34424. };
  34425. return IncrementValueAction;
  34426. }(BABYLON.Action));
  34427. BABYLON.IncrementValueAction = IncrementValueAction;
  34428. var PlayAnimationAction = (function (_super) {
  34429. __extends(PlayAnimationAction, _super);
  34430. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  34431. var _this = _super.call(this, triggerOptions, condition) || this;
  34432. _this.from = from;
  34433. _this.to = to;
  34434. _this.loop = loop;
  34435. _this._target = target;
  34436. return _this;
  34437. }
  34438. PlayAnimationAction.prototype._prepare = function () {
  34439. };
  34440. PlayAnimationAction.prototype.execute = function () {
  34441. var scene = this._actionManager.getScene();
  34442. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  34443. };
  34444. PlayAnimationAction.prototype.serialize = function (parent) {
  34445. return _super.prototype._serialize.call(this, {
  34446. name: "PlayAnimationAction",
  34447. properties: [
  34448. BABYLON.Action._GetTargetProperty(this._target),
  34449. { name: "from", value: String(this.from) },
  34450. { name: "to", value: String(this.to) },
  34451. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  34452. ]
  34453. }, parent);
  34454. };
  34455. return PlayAnimationAction;
  34456. }(BABYLON.Action));
  34457. BABYLON.PlayAnimationAction = PlayAnimationAction;
  34458. var StopAnimationAction = (function (_super) {
  34459. __extends(StopAnimationAction, _super);
  34460. function StopAnimationAction(triggerOptions, target, condition) {
  34461. var _this = _super.call(this, triggerOptions, condition) || this;
  34462. _this._target = target;
  34463. return _this;
  34464. }
  34465. StopAnimationAction.prototype._prepare = function () {
  34466. };
  34467. StopAnimationAction.prototype.execute = function () {
  34468. var scene = this._actionManager.getScene();
  34469. scene.stopAnimation(this._target);
  34470. };
  34471. StopAnimationAction.prototype.serialize = function (parent) {
  34472. return _super.prototype._serialize.call(this, {
  34473. name: "StopAnimationAction",
  34474. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  34475. }, parent);
  34476. };
  34477. return StopAnimationAction;
  34478. }(BABYLON.Action));
  34479. BABYLON.StopAnimationAction = StopAnimationAction;
  34480. var DoNothingAction = (function (_super) {
  34481. __extends(DoNothingAction, _super);
  34482. function DoNothingAction(triggerOptions, condition) {
  34483. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  34484. return _super.call(this, triggerOptions, condition) || this;
  34485. }
  34486. DoNothingAction.prototype.execute = function () {
  34487. };
  34488. DoNothingAction.prototype.serialize = function (parent) {
  34489. return _super.prototype._serialize.call(this, {
  34490. name: "DoNothingAction",
  34491. properties: []
  34492. }, parent);
  34493. };
  34494. return DoNothingAction;
  34495. }(BABYLON.Action));
  34496. BABYLON.DoNothingAction = DoNothingAction;
  34497. var CombineAction = (function (_super) {
  34498. __extends(CombineAction, _super);
  34499. function CombineAction(triggerOptions, children, condition) {
  34500. var _this = _super.call(this, triggerOptions, condition) || this;
  34501. _this.children = children;
  34502. return _this;
  34503. }
  34504. CombineAction.prototype._prepare = function () {
  34505. for (var index = 0; index < this.children.length; index++) {
  34506. this.children[index]._actionManager = this._actionManager;
  34507. this.children[index]._prepare();
  34508. }
  34509. };
  34510. CombineAction.prototype.execute = function (evt) {
  34511. for (var index = 0; index < this.children.length; index++) {
  34512. this.children[index].execute(evt);
  34513. }
  34514. };
  34515. CombineAction.prototype.serialize = function (parent) {
  34516. var serializationObject = _super.prototype._serialize.call(this, {
  34517. name: "CombineAction",
  34518. properties: [],
  34519. combine: []
  34520. }, parent);
  34521. for (var i = 0; i < this.children.length; i++) {
  34522. serializationObject.combine.push(this.children[i].serialize(null));
  34523. }
  34524. return serializationObject;
  34525. };
  34526. return CombineAction;
  34527. }(BABYLON.Action));
  34528. BABYLON.CombineAction = CombineAction;
  34529. var ExecuteCodeAction = (function (_super) {
  34530. __extends(ExecuteCodeAction, _super);
  34531. function ExecuteCodeAction(triggerOptions, func, condition) {
  34532. var _this = _super.call(this, triggerOptions, condition) || this;
  34533. _this.func = func;
  34534. return _this;
  34535. }
  34536. ExecuteCodeAction.prototype.execute = function (evt) {
  34537. this.func(evt);
  34538. };
  34539. return ExecuteCodeAction;
  34540. }(BABYLON.Action));
  34541. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  34542. var SetParentAction = (function (_super) {
  34543. __extends(SetParentAction, _super);
  34544. function SetParentAction(triggerOptions, target, parent, condition) {
  34545. var _this = _super.call(this, triggerOptions, condition) || this;
  34546. _this._target = target;
  34547. _this._parent = parent;
  34548. return _this;
  34549. }
  34550. SetParentAction.prototype._prepare = function () {
  34551. };
  34552. SetParentAction.prototype.execute = function () {
  34553. if (this._target.parent === this._parent) {
  34554. return;
  34555. }
  34556. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  34557. invertParentWorldMatrix.invert();
  34558. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  34559. this._target.parent = this._parent;
  34560. };
  34561. SetParentAction.prototype.serialize = function (parent) {
  34562. return _super.prototype._serialize.call(this, {
  34563. name: "SetParentAction",
  34564. properties: [
  34565. BABYLON.Action._GetTargetProperty(this._target),
  34566. BABYLON.Action._GetTargetProperty(this._parent),
  34567. ]
  34568. }, parent);
  34569. };
  34570. return SetParentAction;
  34571. }(BABYLON.Action));
  34572. BABYLON.SetParentAction = SetParentAction;
  34573. var PlaySoundAction = (function (_super) {
  34574. __extends(PlaySoundAction, _super);
  34575. function PlaySoundAction(triggerOptions, sound, condition) {
  34576. var _this = _super.call(this, triggerOptions, condition) || this;
  34577. _this._sound = sound;
  34578. return _this;
  34579. }
  34580. PlaySoundAction.prototype._prepare = function () {
  34581. };
  34582. PlaySoundAction.prototype.execute = function () {
  34583. if (this._sound !== undefined)
  34584. this._sound.play();
  34585. };
  34586. PlaySoundAction.prototype.serialize = function (parent) {
  34587. return _super.prototype._serialize.call(this, {
  34588. name: "PlaySoundAction",
  34589. properties: [{ name: "sound", value: this._sound.name }]
  34590. }, parent);
  34591. };
  34592. return PlaySoundAction;
  34593. }(BABYLON.Action));
  34594. BABYLON.PlaySoundAction = PlaySoundAction;
  34595. var StopSoundAction = (function (_super) {
  34596. __extends(StopSoundAction, _super);
  34597. function StopSoundAction(triggerOptions, sound, condition) {
  34598. var _this = _super.call(this, triggerOptions, condition) || this;
  34599. _this._sound = sound;
  34600. return _this;
  34601. }
  34602. StopSoundAction.prototype._prepare = function () {
  34603. };
  34604. StopSoundAction.prototype.execute = function () {
  34605. if (this._sound !== undefined)
  34606. this._sound.stop();
  34607. };
  34608. StopSoundAction.prototype.serialize = function (parent) {
  34609. return _super.prototype._serialize.call(this, {
  34610. name: "StopSoundAction",
  34611. properties: [{ name: "sound", value: this._sound.name }]
  34612. }, parent);
  34613. };
  34614. return StopSoundAction;
  34615. }(BABYLON.Action));
  34616. BABYLON.StopSoundAction = StopSoundAction;
  34617. })(BABYLON || (BABYLON = {}));
  34618. //# sourceMappingURL=babylon.directActions.js.map
  34619. var BABYLON;
  34620. (function (BABYLON) {
  34621. var SpriteManager = (function () {
  34622. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  34623. if (epsilon === void 0) { epsilon = 0.01; }
  34624. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  34625. this.name = name;
  34626. this.sprites = new Array();
  34627. this.renderingGroupId = 0;
  34628. this.layerMask = 0x0FFFFFFF;
  34629. this.fogEnabled = true;
  34630. this.isPickable = false;
  34631. /**
  34632. * An event triggered when the manager is disposed.
  34633. * @type {BABYLON.Observable}
  34634. */
  34635. this.onDisposeObservable = new BABYLON.Observable();
  34636. this._vertexBuffers = {};
  34637. this._capacity = capacity;
  34638. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  34639. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34640. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  34641. if (cellSize.width && cellSize.height) {
  34642. this.cellWidth = cellSize.width;
  34643. this.cellHeight = cellSize.height;
  34644. }
  34645. else if (cellSize !== undefined) {
  34646. this.cellWidth = cellSize;
  34647. this.cellHeight = cellSize;
  34648. }
  34649. else {
  34650. return;
  34651. }
  34652. this._epsilon = epsilon;
  34653. this._scene = scene;
  34654. this._scene.spriteManagers.push(this);
  34655. var indices = [];
  34656. var index = 0;
  34657. for (var count = 0; count < capacity; count++) {
  34658. indices.push(index);
  34659. indices.push(index + 1);
  34660. indices.push(index + 2);
  34661. indices.push(index);
  34662. indices.push(index + 2);
  34663. indices.push(index + 3);
  34664. index += 4;
  34665. }
  34666. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  34667. // VBO
  34668. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  34669. this._vertexData = new Float32Array(capacity * 16 * 4);
  34670. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  34671. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  34672. var options = this._buffer.createVertexBuffer("options", 4, 4);
  34673. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  34674. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  34675. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  34676. this._vertexBuffers["options"] = options;
  34677. this._vertexBuffers["cellInfo"] = cellInfo;
  34678. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  34679. // Effects
  34680. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  34681. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  34682. }
  34683. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  34684. set: function (callback) {
  34685. if (this._onDisposeObserver) {
  34686. this.onDisposeObservable.remove(this._onDisposeObserver);
  34687. }
  34688. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34689. },
  34690. enumerable: true,
  34691. configurable: true
  34692. });
  34693. Object.defineProperty(SpriteManager.prototype, "texture", {
  34694. get: function () {
  34695. return this._spriteTexture;
  34696. },
  34697. set: function (value) {
  34698. this._spriteTexture = value;
  34699. },
  34700. enumerable: true,
  34701. configurable: true
  34702. });
  34703. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  34704. var arrayOffset = index * 16;
  34705. if (offsetX === 0)
  34706. offsetX = this._epsilon;
  34707. else if (offsetX === 1)
  34708. offsetX = 1 - this._epsilon;
  34709. if (offsetY === 0)
  34710. offsetY = this._epsilon;
  34711. else if (offsetY === 1)
  34712. offsetY = 1 - this._epsilon;
  34713. this._vertexData[arrayOffset] = sprite.position.x;
  34714. this._vertexData[arrayOffset + 1] = sprite.position.y;
  34715. this._vertexData[arrayOffset + 2] = sprite.position.z;
  34716. this._vertexData[arrayOffset + 3] = sprite.angle;
  34717. this._vertexData[arrayOffset + 4] = sprite.width;
  34718. this._vertexData[arrayOffset + 5] = sprite.height;
  34719. this._vertexData[arrayOffset + 6] = offsetX;
  34720. this._vertexData[arrayOffset + 7] = offsetY;
  34721. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  34722. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  34723. var offset = (sprite.cellIndex / rowSize) >> 0;
  34724. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  34725. this._vertexData[arrayOffset + 11] = offset;
  34726. // Color
  34727. this._vertexData[arrayOffset + 12] = sprite.color.r;
  34728. this._vertexData[arrayOffset + 13] = sprite.color.g;
  34729. this._vertexData[arrayOffset + 14] = sprite.color.b;
  34730. this._vertexData[arrayOffset + 15] = sprite.color.a;
  34731. };
  34732. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  34733. var count = Math.min(this._capacity, this.sprites.length);
  34734. var min = BABYLON.Vector3.Zero();
  34735. var max = BABYLON.Vector3.Zero();
  34736. var distance = Number.MAX_VALUE;
  34737. var currentSprite;
  34738. var cameraSpacePosition = BABYLON.Vector3.Zero();
  34739. var cameraView = camera.getViewMatrix();
  34740. for (var index = 0; index < count; index++) {
  34741. var sprite = this.sprites[index];
  34742. if (!sprite) {
  34743. continue;
  34744. }
  34745. if (predicate) {
  34746. if (!predicate(sprite)) {
  34747. continue;
  34748. }
  34749. }
  34750. else if (!sprite.isPickable) {
  34751. continue;
  34752. }
  34753. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  34754. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  34755. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  34756. if (ray.intersectsBoxMinMax(min, max)) {
  34757. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  34758. if (distance > currentDistance) {
  34759. distance = currentDistance;
  34760. currentSprite = sprite;
  34761. if (fastCheck) {
  34762. break;
  34763. }
  34764. }
  34765. }
  34766. }
  34767. if (currentSprite) {
  34768. var result = new BABYLON.PickingInfo();
  34769. result.hit = true;
  34770. result.pickedSprite = currentSprite;
  34771. result.distance = distance;
  34772. return result;
  34773. }
  34774. return null;
  34775. };
  34776. SpriteManager.prototype.render = function () {
  34777. // Check
  34778. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  34779. return;
  34780. var engine = this._scene.getEngine();
  34781. var baseSize = this._spriteTexture.getBaseSize();
  34782. // Sprites
  34783. var deltaTime = engine.getDeltaTime();
  34784. var max = Math.min(this._capacity, this.sprites.length);
  34785. var rowSize = baseSize.width / this.cellWidth;
  34786. var offset = 0;
  34787. for (var index = 0; index < max; index++) {
  34788. var sprite = this.sprites[index];
  34789. if (!sprite) {
  34790. continue;
  34791. }
  34792. sprite._animate(deltaTime);
  34793. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  34794. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  34795. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  34796. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  34797. }
  34798. this._buffer.update(this._vertexData);
  34799. // Render
  34800. var effect = this._effectBase;
  34801. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  34802. effect = this._effectFog;
  34803. }
  34804. engine.enableEffect(effect);
  34805. var viewMatrix = this._scene.getViewMatrix();
  34806. effect.setTexture("diffuseSampler", this._spriteTexture);
  34807. effect.setMatrix("view", viewMatrix);
  34808. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  34809. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  34810. // Fog
  34811. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  34812. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  34813. effect.setColor3("vFogColor", this._scene.fogColor);
  34814. }
  34815. // VBOs
  34816. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  34817. // Draw order
  34818. engine.setDepthFunctionToLessOrEqual();
  34819. effect.setBool("alphaTest", true);
  34820. engine.setColorWrite(false);
  34821. engine.draw(true, 0, max * 6);
  34822. engine.setColorWrite(true);
  34823. effect.setBool("alphaTest", false);
  34824. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  34825. engine.draw(true, 0, max * 6);
  34826. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  34827. };
  34828. SpriteManager.prototype.dispose = function () {
  34829. if (this._buffer) {
  34830. this._buffer.dispose();
  34831. this._buffer = null;
  34832. }
  34833. if (this._indexBuffer) {
  34834. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34835. this._indexBuffer = null;
  34836. }
  34837. if (this._spriteTexture) {
  34838. this._spriteTexture.dispose();
  34839. this._spriteTexture = null;
  34840. }
  34841. // Remove from scene
  34842. var index = this._scene.spriteManagers.indexOf(this);
  34843. this._scene.spriteManagers.splice(index, 1);
  34844. // Callback
  34845. this.onDisposeObservable.notifyObservers(this);
  34846. this.onDisposeObservable.clear();
  34847. };
  34848. return SpriteManager;
  34849. }());
  34850. BABYLON.SpriteManager = SpriteManager;
  34851. })(BABYLON || (BABYLON = {}));
  34852. //# sourceMappingURL=babylon.spriteManager.js.map
  34853. var BABYLON;
  34854. (function (BABYLON) {
  34855. var Sprite = (function () {
  34856. function Sprite(name, manager) {
  34857. this.name = name;
  34858. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  34859. this.width = 1.0;
  34860. this.height = 1.0;
  34861. this.angle = 0;
  34862. this.cellIndex = 0;
  34863. this.invertU = 0;
  34864. this.invertV = 0;
  34865. this.animations = new Array();
  34866. this.isPickable = false;
  34867. this._animationStarted = false;
  34868. this._loopAnimation = false;
  34869. this._fromIndex = 0;
  34870. this._toIndex = 0;
  34871. this._delay = 0;
  34872. this._direction = 1;
  34873. this._frameCount = 0;
  34874. this._time = 0;
  34875. this._manager = manager;
  34876. this._manager.sprites.push(this);
  34877. this.position = BABYLON.Vector3.Zero();
  34878. }
  34879. Object.defineProperty(Sprite.prototype, "size", {
  34880. get: function () {
  34881. return this.width;
  34882. },
  34883. set: function (value) {
  34884. this.width = value;
  34885. this.height = value;
  34886. },
  34887. enumerable: true,
  34888. configurable: true
  34889. });
  34890. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  34891. this._fromIndex = from;
  34892. this._toIndex = to;
  34893. this._loopAnimation = loop;
  34894. this._delay = delay;
  34895. this._animationStarted = true;
  34896. this._direction = from < to ? 1 : -1;
  34897. this.cellIndex = from;
  34898. this._time = 0;
  34899. this._onAnimationEnd = onAnimationEnd;
  34900. };
  34901. Sprite.prototype.stopAnimation = function () {
  34902. this._animationStarted = false;
  34903. };
  34904. Sprite.prototype._animate = function (deltaTime) {
  34905. if (!this._animationStarted)
  34906. return;
  34907. this._time += deltaTime;
  34908. if (this._time > this._delay) {
  34909. this._time = this._time % this._delay;
  34910. this.cellIndex += this._direction;
  34911. if (this.cellIndex === this._toIndex) {
  34912. if (this._loopAnimation) {
  34913. this.cellIndex = this._fromIndex;
  34914. }
  34915. else {
  34916. this._animationStarted = false;
  34917. if (this._onAnimationEnd) {
  34918. this._onAnimationEnd();
  34919. }
  34920. if (this.disposeWhenFinishedAnimating) {
  34921. this.dispose();
  34922. }
  34923. }
  34924. }
  34925. }
  34926. };
  34927. Sprite.prototype.dispose = function () {
  34928. for (var i = 0; i < this._manager.sprites.length; i++) {
  34929. if (this._manager.sprites[i] == this) {
  34930. this._manager.sprites.splice(i, 1);
  34931. }
  34932. }
  34933. };
  34934. return Sprite;
  34935. }());
  34936. BABYLON.Sprite = Sprite;
  34937. })(BABYLON || (BABYLON = {}));
  34938. //# sourceMappingURL=babylon.sprite.js.map
  34939. var BABYLON;
  34940. (function (BABYLON) {
  34941. var IntersectionInfo = (function () {
  34942. function IntersectionInfo(bu, bv, distance) {
  34943. this.bu = bu;
  34944. this.bv = bv;
  34945. this.distance = distance;
  34946. this.faceId = 0;
  34947. this.subMeshId = 0;
  34948. }
  34949. return IntersectionInfo;
  34950. }());
  34951. BABYLON.IntersectionInfo = IntersectionInfo;
  34952. var PickingInfo = (function () {
  34953. function PickingInfo() {
  34954. this.hit = false;
  34955. this.distance = 0;
  34956. this.pickedPoint = null;
  34957. this.pickedMesh = null;
  34958. this.bu = 0;
  34959. this.bv = 0;
  34960. this.faceId = -1;
  34961. this.subMeshId = 0;
  34962. this.pickedSprite = null;
  34963. }
  34964. // Methods
  34965. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  34966. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  34967. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  34968. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34969. return null;
  34970. }
  34971. var indices = this.pickedMesh.getIndices();
  34972. var result;
  34973. if (useVerticesNormals) {
  34974. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34975. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  34976. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  34977. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  34978. normal0 = normal0.scale(this.bu);
  34979. normal1 = normal1.scale(this.bv);
  34980. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  34981. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  34982. }
  34983. else {
  34984. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34985. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  34986. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  34987. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  34988. var p1p2 = vertex1.subtract(vertex2);
  34989. var p3p2 = vertex3.subtract(vertex2);
  34990. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  34991. }
  34992. if (useWorldCoordinates) {
  34993. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  34994. }
  34995. return BABYLON.Vector3.Normalize(result);
  34996. };
  34997. PickingInfo.prototype.getTextureCoordinates = function () {
  34998. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34999. return null;
  35000. }
  35001. var indices = this.pickedMesh.getIndices();
  35002. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35003. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  35004. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  35005. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  35006. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  35007. uv1 = uv1.scale(this.bu);
  35008. uv2 = uv2.scale(this.bv);
  35009. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  35010. };
  35011. return PickingInfo;
  35012. }());
  35013. BABYLON.PickingInfo = PickingInfo;
  35014. })(BABYLON || (BABYLON = {}));
  35015. //# sourceMappingURL=babylon.pickingInfo.js.map
  35016. var BABYLON;
  35017. (function (BABYLON) {
  35018. var Ray = (function () {
  35019. function Ray(origin, direction, length) {
  35020. if (length === void 0) { length = Number.MAX_VALUE; }
  35021. this.origin = origin;
  35022. this.direction = direction;
  35023. this.length = length;
  35024. }
  35025. // Methods
  35026. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  35027. var d = 0.0;
  35028. var maxValue = Number.MAX_VALUE;
  35029. var inv;
  35030. var min;
  35031. var max;
  35032. var temp;
  35033. if (Math.abs(this.direction.x) < 0.0000001) {
  35034. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  35035. return false;
  35036. }
  35037. }
  35038. else {
  35039. inv = 1.0 / this.direction.x;
  35040. min = (minimum.x - this.origin.x) * inv;
  35041. max = (maximum.x - this.origin.x) * inv;
  35042. if (max === -Infinity) {
  35043. max = Infinity;
  35044. }
  35045. if (min > max) {
  35046. temp = min;
  35047. min = max;
  35048. max = temp;
  35049. }
  35050. d = Math.max(min, d);
  35051. maxValue = Math.min(max, maxValue);
  35052. if (d > maxValue) {
  35053. return false;
  35054. }
  35055. }
  35056. if (Math.abs(this.direction.y) < 0.0000001) {
  35057. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  35058. return false;
  35059. }
  35060. }
  35061. else {
  35062. inv = 1.0 / this.direction.y;
  35063. min = (minimum.y - this.origin.y) * inv;
  35064. max = (maximum.y - this.origin.y) * inv;
  35065. if (max === -Infinity) {
  35066. max = Infinity;
  35067. }
  35068. if (min > max) {
  35069. temp = min;
  35070. min = max;
  35071. max = temp;
  35072. }
  35073. d = Math.max(min, d);
  35074. maxValue = Math.min(max, maxValue);
  35075. if (d > maxValue) {
  35076. return false;
  35077. }
  35078. }
  35079. if (Math.abs(this.direction.z) < 0.0000001) {
  35080. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  35081. return false;
  35082. }
  35083. }
  35084. else {
  35085. inv = 1.0 / this.direction.z;
  35086. min = (minimum.z - this.origin.z) * inv;
  35087. max = (maximum.z - this.origin.z) * inv;
  35088. if (max === -Infinity) {
  35089. max = Infinity;
  35090. }
  35091. if (min > max) {
  35092. temp = min;
  35093. min = max;
  35094. max = temp;
  35095. }
  35096. d = Math.max(min, d);
  35097. maxValue = Math.min(max, maxValue);
  35098. if (d > maxValue) {
  35099. return false;
  35100. }
  35101. }
  35102. return true;
  35103. };
  35104. Ray.prototype.intersectsBox = function (box) {
  35105. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  35106. };
  35107. Ray.prototype.intersectsSphere = function (sphere) {
  35108. var x = sphere.center.x - this.origin.x;
  35109. var y = sphere.center.y - this.origin.y;
  35110. var z = sphere.center.z - this.origin.z;
  35111. var pyth = (x * x) + (y * y) + (z * z);
  35112. var rr = sphere.radius * sphere.radius;
  35113. if (pyth <= rr) {
  35114. return true;
  35115. }
  35116. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  35117. if (dot < 0.0) {
  35118. return false;
  35119. }
  35120. var temp = pyth - (dot * dot);
  35121. return temp <= rr;
  35122. };
  35123. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  35124. if (!this._edge1) {
  35125. this._edge1 = BABYLON.Vector3.Zero();
  35126. this._edge2 = BABYLON.Vector3.Zero();
  35127. this._pvec = BABYLON.Vector3.Zero();
  35128. this._tvec = BABYLON.Vector3.Zero();
  35129. this._qvec = BABYLON.Vector3.Zero();
  35130. }
  35131. vertex1.subtractToRef(vertex0, this._edge1);
  35132. vertex2.subtractToRef(vertex0, this._edge2);
  35133. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  35134. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  35135. if (det === 0) {
  35136. return null;
  35137. }
  35138. var invdet = 1 / det;
  35139. this.origin.subtractToRef(vertex0, this._tvec);
  35140. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  35141. if (bu < 0 || bu > 1.0) {
  35142. return null;
  35143. }
  35144. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  35145. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  35146. if (bv < 0 || bu + bv > 1.0) {
  35147. return null;
  35148. }
  35149. //check if the distance is longer than the predefined length.
  35150. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  35151. if (distance > this.length) {
  35152. return null;
  35153. }
  35154. return new BABYLON.IntersectionInfo(bu, bv, distance);
  35155. };
  35156. Ray.prototype.intersectsPlane = function (plane) {
  35157. var distance;
  35158. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  35159. if (Math.abs(result1) < 9.99999997475243E-07) {
  35160. return null;
  35161. }
  35162. else {
  35163. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  35164. distance = (-plane.d - result2) / result1;
  35165. if (distance < 0.0) {
  35166. if (distance < -9.99999997475243E-07) {
  35167. return null;
  35168. }
  35169. else {
  35170. return 0;
  35171. }
  35172. }
  35173. return distance;
  35174. }
  35175. };
  35176. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  35177. var tm = BABYLON.Tmp.Matrix[0];
  35178. mesh.getWorldMatrix().invertToRef(tm);
  35179. if (this._tmpRay) {
  35180. Ray.TransformToRef(this, tm, this._tmpRay);
  35181. }
  35182. else {
  35183. this._tmpRay = Ray.Transform(this, tm);
  35184. }
  35185. return mesh.intersects(this._tmpRay, fastCheck);
  35186. };
  35187. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  35188. if (results) {
  35189. results.length = 0;
  35190. }
  35191. else {
  35192. results = [];
  35193. }
  35194. for (var i = 0; i < meshes.length; i++) {
  35195. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  35196. if (pickInfo.hit) {
  35197. results.push(pickInfo);
  35198. }
  35199. }
  35200. results.sort(this._comparePickingInfo);
  35201. return results;
  35202. };
  35203. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  35204. if (pickingInfoA.distance < pickingInfoB.distance) {
  35205. return -1;
  35206. }
  35207. else if (pickingInfoA.distance > pickingInfoB.distance) {
  35208. return 1;
  35209. }
  35210. else {
  35211. return 0;
  35212. }
  35213. };
  35214. /**
  35215. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  35216. * @param sega the first point of the segment to test the intersection against
  35217. * @param segb the second point of the segment to test the intersection against
  35218. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  35219. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  35220. */
  35221. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  35222. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  35223. var u = segb.subtract(sega);
  35224. var v = rsegb.subtract(this.origin);
  35225. var w = sega.subtract(this.origin);
  35226. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  35227. var b = BABYLON.Vector3.Dot(u, v);
  35228. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  35229. var d = BABYLON.Vector3.Dot(u, w);
  35230. var e = BABYLON.Vector3.Dot(v, w);
  35231. var D = a * c - b * b; // always >= 0
  35232. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  35233. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  35234. // compute the line parameters of the two closest points
  35235. if (D < Ray.smallnum) {
  35236. sN = 0.0; // force using point P0 on segment S1
  35237. sD = 1.0; // to prevent possible division by 0.0 later
  35238. tN = e;
  35239. tD = c;
  35240. }
  35241. else {
  35242. sN = (b * e - c * d);
  35243. tN = (a * e - b * d);
  35244. if (sN < 0.0) {
  35245. sN = 0.0;
  35246. tN = e;
  35247. tD = c;
  35248. }
  35249. else if (sN > sD) {
  35250. sN = sD;
  35251. tN = e + b;
  35252. tD = c;
  35253. }
  35254. }
  35255. if (tN < 0.0) {
  35256. tN = 0.0;
  35257. // recompute sc for this edge
  35258. if (-d < 0.0) {
  35259. sN = 0.0;
  35260. }
  35261. else if (-d > a)
  35262. sN = sD;
  35263. else {
  35264. sN = -d;
  35265. sD = a;
  35266. }
  35267. }
  35268. else if (tN > tD) {
  35269. tN = tD;
  35270. // recompute sc for this edge
  35271. if ((-d + b) < 0.0) {
  35272. sN = 0;
  35273. }
  35274. else if ((-d + b) > a) {
  35275. sN = sD;
  35276. }
  35277. else {
  35278. sN = (-d + b);
  35279. sD = a;
  35280. }
  35281. }
  35282. // finally do the division to get sc and tc
  35283. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  35284. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  35285. // get the difference of the two closest points
  35286. var qtc = v.multiplyByFloats(tc, tc, tc);
  35287. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  35288. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  35289. if (isIntersected) {
  35290. return qtc.length();
  35291. }
  35292. return -1;
  35293. };
  35294. // Statics
  35295. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  35296. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  35297. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  35298. var direction = end.subtract(start);
  35299. direction.normalize();
  35300. return new Ray(start, direction);
  35301. };
  35302. /**
  35303. * 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
  35304. * transformed to the given world matrix.
  35305. * @param origin The origin point
  35306. * @param end The end point
  35307. * @param world a matrix to transform the ray to. Default is the identity matrix.
  35308. */
  35309. Ray.CreateNewFromTo = function (origin, end, world) {
  35310. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  35311. var direction = end.subtract(origin);
  35312. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  35313. direction.normalize();
  35314. return Ray.Transform(new Ray(origin, direction, length), world);
  35315. };
  35316. Ray.Transform = function (ray, matrix) {
  35317. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  35318. Ray.TransformToRef(ray, matrix, result);
  35319. return result;
  35320. };
  35321. Ray.TransformToRef = function (ray, matrix, result) {
  35322. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  35323. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  35324. result.length = ray.length;
  35325. var dir = result.direction;
  35326. var len = dir.length();
  35327. if (!(len === 0 || len === 1)) {
  35328. var num = 1.0 / len;
  35329. dir.x *= num;
  35330. dir.y *= num;
  35331. dir.z *= num;
  35332. result.length *= len;
  35333. }
  35334. };
  35335. return Ray;
  35336. }());
  35337. Ray.smallnum = 0.00000001;
  35338. Ray.rayl = 10e8;
  35339. BABYLON.Ray = Ray;
  35340. })(BABYLON || (BABYLON = {}));
  35341. //# sourceMappingURL=babylon.ray.js.map
  35342. var BABYLON;
  35343. (function (BABYLON) {
  35344. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  35345. if (boxMin.x > sphereCenter.x + sphereRadius)
  35346. return false;
  35347. if (sphereCenter.x - sphereRadius > boxMax.x)
  35348. return false;
  35349. if (boxMin.y > sphereCenter.y + sphereRadius)
  35350. return false;
  35351. if (sphereCenter.y - sphereRadius > boxMax.y)
  35352. return false;
  35353. if (boxMin.z > sphereCenter.z + sphereRadius)
  35354. return false;
  35355. if (sphereCenter.z - sphereRadius > boxMax.z)
  35356. return false;
  35357. return true;
  35358. };
  35359. var getLowestRoot = (function () {
  35360. var result = { root: 0, found: false };
  35361. return function (a, b, c, maxR) {
  35362. result.root = 0;
  35363. result.found = false;
  35364. var determinant = b * b - 4.0 * a * c;
  35365. if (determinant < 0)
  35366. return result;
  35367. var sqrtD = Math.sqrt(determinant);
  35368. var r1 = (-b - sqrtD) / (2.0 * a);
  35369. var r2 = (-b + sqrtD) / (2.0 * a);
  35370. if (r1 > r2) {
  35371. var temp = r2;
  35372. r2 = r1;
  35373. r1 = temp;
  35374. }
  35375. if (r1 > 0 && r1 < maxR) {
  35376. result.root = r1;
  35377. result.found = true;
  35378. return result;
  35379. }
  35380. if (r2 > 0 && r2 < maxR) {
  35381. result.root = r2;
  35382. result.found = true;
  35383. return result;
  35384. }
  35385. return result;
  35386. };
  35387. })();
  35388. var Collider = (function () {
  35389. function Collider() {
  35390. this.radius = new BABYLON.Vector3(1, 1, 1);
  35391. this.retry = 0;
  35392. this.basePointWorld = BABYLON.Vector3.Zero();
  35393. this.velocityWorld = BABYLON.Vector3.Zero();
  35394. this.normalizedVelocity = BABYLON.Vector3.Zero();
  35395. this._collisionPoint = BABYLON.Vector3.Zero();
  35396. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  35397. this._tempVector = BABYLON.Vector3.Zero();
  35398. this._tempVector2 = BABYLON.Vector3.Zero();
  35399. this._tempVector3 = BABYLON.Vector3.Zero();
  35400. this._tempVector4 = BABYLON.Vector3.Zero();
  35401. this._edge = BABYLON.Vector3.Zero();
  35402. this._baseToVertex = BABYLON.Vector3.Zero();
  35403. this._destinationPoint = BABYLON.Vector3.Zero();
  35404. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  35405. this._displacementVector = BABYLON.Vector3.Zero();
  35406. this._collisionMask = -1;
  35407. }
  35408. Object.defineProperty(Collider.prototype, "collisionMask", {
  35409. get: function () {
  35410. return this._collisionMask;
  35411. },
  35412. set: function (mask) {
  35413. this._collisionMask = !isNaN(mask) ? mask : -1;
  35414. },
  35415. enumerable: true,
  35416. configurable: true
  35417. });
  35418. // Methods
  35419. Collider.prototype._initialize = function (source, dir, e) {
  35420. this.velocity = dir;
  35421. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  35422. this.basePoint = source;
  35423. source.multiplyToRef(this.radius, this.basePointWorld);
  35424. dir.multiplyToRef(this.radius, this.velocityWorld);
  35425. this.velocityWorldLength = this.velocityWorld.length();
  35426. this.epsilon = e;
  35427. this.collisionFound = false;
  35428. };
  35429. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  35430. pa.subtractToRef(point, this._tempVector);
  35431. pb.subtractToRef(point, this._tempVector2);
  35432. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  35433. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  35434. if (d < 0)
  35435. return false;
  35436. pc.subtractToRef(point, this._tempVector3);
  35437. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  35438. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  35439. if (d < 0)
  35440. return false;
  35441. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  35442. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  35443. return d >= 0;
  35444. };
  35445. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  35446. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  35447. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  35448. if (distance > this.velocityWorldLength + max + sphereRadius) {
  35449. return false;
  35450. }
  35451. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  35452. return false;
  35453. return true;
  35454. };
  35455. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  35456. var t0;
  35457. var embeddedInPlane = false;
  35458. //defensive programming, actually not needed.
  35459. if (!trianglePlaneArray) {
  35460. trianglePlaneArray = [];
  35461. }
  35462. if (!trianglePlaneArray[faceIndex]) {
  35463. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  35464. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  35465. }
  35466. var trianglePlane = trianglePlaneArray[faceIndex];
  35467. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  35468. return;
  35469. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  35470. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  35471. if (normalDotVelocity == 0) {
  35472. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  35473. return;
  35474. embeddedInPlane = true;
  35475. t0 = 0;
  35476. }
  35477. else {
  35478. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  35479. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  35480. if (t0 > t1) {
  35481. var temp = t1;
  35482. t1 = t0;
  35483. t0 = temp;
  35484. }
  35485. if (t0 > 1.0 || t1 < 0.0)
  35486. return;
  35487. if (t0 < 0)
  35488. t0 = 0;
  35489. if (t0 > 1.0)
  35490. t0 = 1.0;
  35491. }
  35492. this._collisionPoint.copyFromFloats(0, 0, 0);
  35493. var found = false;
  35494. var t = 1.0;
  35495. if (!embeddedInPlane) {
  35496. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  35497. this.velocity.scaleToRef(t0, this._tempVector);
  35498. this._planeIntersectionPoint.addInPlace(this._tempVector);
  35499. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  35500. found = true;
  35501. t = t0;
  35502. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  35503. }
  35504. }
  35505. if (!found) {
  35506. var velocitySquaredLength = this.velocity.lengthSquared();
  35507. var a = velocitySquaredLength;
  35508. this.basePoint.subtractToRef(p1, this._tempVector);
  35509. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  35510. var c = this._tempVector.lengthSquared() - 1.0;
  35511. var lowestRoot = getLowestRoot(a, b, c, t);
  35512. if (lowestRoot.found) {
  35513. t = lowestRoot.root;
  35514. found = true;
  35515. this._collisionPoint.copyFrom(p1);
  35516. }
  35517. this.basePoint.subtractToRef(p2, this._tempVector);
  35518. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  35519. c = this._tempVector.lengthSquared() - 1.0;
  35520. lowestRoot = getLowestRoot(a, b, c, t);
  35521. if (lowestRoot.found) {
  35522. t = lowestRoot.root;
  35523. found = true;
  35524. this._collisionPoint.copyFrom(p2);
  35525. }
  35526. this.basePoint.subtractToRef(p3, this._tempVector);
  35527. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  35528. c = this._tempVector.lengthSquared() - 1.0;
  35529. lowestRoot = getLowestRoot(a, b, c, t);
  35530. if (lowestRoot.found) {
  35531. t = lowestRoot.root;
  35532. found = true;
  35533. this._collisionPoint.copyFrom(p3);
  35534. }
  35535. p2.subtractToRef(p1, this._edge);
  35536. p1.subtractToRef(this.basePoint, this._baseToVertex);
  35537. var edgeSquaredLength = this._edge.lengthSquared();
  35538. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  35539. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  35540. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  35541. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  35542. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  35543. lowestRoot = getLowestRoot(a, b, c, t);
  35544. if (lowestRoot.found) {
  35545. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  35546. if (f >= 0.0 && f <= 1.0) {
  35547. t = lowestRoot.root;
  35548. found = true;
  35549. this._edge.scaleInPlace(f);
  35550. p1.addToRef(this._edge, this._collisionPoint);
  35551. }
  35552. }
  35553. p3.subtractToRef(p2, this._edge);
  35554. p2.subtractToRef(this.basePoint, this._baseToVertex);
  35555. edgeSquaredLength = this._edge.lengthSquared();
  35556. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  35557. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  35558. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  35559. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  35560. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  35561. lowestRoot = getLowestRoot(a, b, c, t);
  35562. if (lowestRoot.found) {
  35563. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  35564. if (f >= 0.0 && f <= 1.0) {
  35565. t = lowestRoot.root;
  35566. found = true;
  35567. this._edge.scaleInPlace(f);
  35568. p2.addToRef(this._edge, this._collisionPoint);
  35569. }
  35570. }
  35571. p1.subtractToRef(p3, this._edge);
  35572. p3.subtractToRef(this.basePoint, this._baseToVertex);
  35573. edgeSquaredLength = this._edge.lengthSquared();
  35574. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  35575. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  35576. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  35577. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  35578. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  35579. lowestRoot = getLowestRoot(a, b, c, t);
  35580. if (lowestRoot.found) {
  35581. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  35582. if (f >= 0.0 && f <= 1.0) {
  35583. t = lowestRoot.root;
  35584. found = true;
  35585. this._edge.scaleInPlace(f);
  35586. p3.addToRef(this._edge, this._collisionPoint);
  35587. }
  35588. }
  35589. }
  35590. if (found) {
  35591. var distToCollision = t * this.velocity.length();
  35592. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  35593. if (!this.intersectionPoint) {
  35594. this.intersectionPoint = this._collisionPoint.clone();
  35595. }
  35596. else {
  35597. this.intersectionPoint.copyFrom(this._collisionPoint);
  35598. }
  35599. this.nearestDistance = distToCollision;
  35600. this.collisionFound = true;
  35601. }
  35602. }
  35603. };
  35604. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  35605. for (var i = indexStart; i < indexEnd; i += 3) {
  35606. var p1 = pts[indices[i] - decal];
  35607. var p2 = pts[indices[i + 1] - decal];
  35608. var p3 = pts[indices[i + 2] - decal];
  35609. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  35610. }
  35611. };
  35612. Collider.prototype._getResponse = function (pos, vel) {
  35613. pos.addToRef(vel, this._destinationPoint);
  35614. vel.scaleInPlace((this.nearestDistance / vel.length()));
  35615. this.basePoint.addToRef(vel, pos);
  35616. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  35617. this._slidePlaneNormal.normalize();
  35618. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  35619. pos.addInPlace(this._displacementVector);
  35620. this.intersectionPoint.addInPlace(this._displacementVector);
  35621. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  35622. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  35623. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  35624. };
  35625. return Collider;
  35626. }());
  35627. BABYLON.Collider = Collider;
  35628. })(BABYLON || (BABYLON = {}));
  35629. //# sourceMappingURL=babylon.collider.js.map
  35630. var BABYLON;
  35631. (function (BABYLON) {
  35632. //WebWorker code will be inserted to this variable.
  35633. BABYLON.CollisionWorker = "";
  35634. var WorkerTaskType;
  35635. (function (WorkerTaskType) {
  35636. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  35637. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  35638. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  35639. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  35640. var WorkerReplyType;
  35641. (function (WorkerReplyType) {
  35642. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  35643. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  35644. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  35645. var CollisionCoordinatorWorker = (function () {
  35646. function CollisionCoordinatorWorker() {
  35647. var _this = this;
  35648. this._scaledPosition = BABYLON.Vector3.Zero();
  35649. this._scaledVelocity = BABYLON.Vector3.Zero();
  35650. this.onMeshUpdated = function (mesh) {
  35651. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  35652. };
  35653. this.onGeometryUpdated = function (geometry) {
  35654. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  35655. };
  35656. this._afterRender = function () {
  35657. if (!_this._init)
  35658. return;
  35659. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  35660. return;
  35661. }
  35662. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  35663. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  35664. if (_this._runningUpdated > 4) {
  35665. return;
  35666. }
  35667. ++_this._runningUpdated;
  35668. var payload = {
  35669. updatedMeshes: _this._addUpdateMeshesList,
  35670. updatedGeometries: _this._addUpdateGeometriesList,
  35671. removedGeometries: _this._toRemoveGeometryArray,
  35672. removedMeshes: _this._toRemoveMeshesArray
  35673. };
  35674. var message = {
  35675. payload: payload,
  35676. taskType: WorkerTaskType.UPDATE
  35677. };
  35678. var serializable = [];
  35679. for (var id in payload.updatedGeometries) {
  35680. if (payload.updatedGeometries.hasOwnProperty(id)) {
  35681. //prepare transferables
  35682. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  35683. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  35684. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  35685. }
  35686. }
  35687. _this._worker.postMessage(message, serializable);
  35688. _this._addUpdateMeshesList = {};
  35689. _this._addUpdateGeometriesList = {};
  35690. _this._toRemoveGeometryArray = [];
  35691. _this._toRemoveMeshesArray = [];
  35692. };
  35693. this._onMessageFromWorker = function (e) {
  35694. var returnData = e.data;
  35695. if (returnData.error != WorkerReplyType.SUCCESS) {
  35696. //TODO what errors can be returned from the worker?
  35697. BABYLON.Tools.Warn("error returned from worker!");
  35698. return;
  35699. }
  35700. switch (returnData.taskType) {
  35701. case WorkerTaskType.INIT:
  35702. _this._init = true;
  35703. //Update the worked with ALL of the scene's current state
  35704. _this._scene.meshes.forEach(function (mesh) {
  35705. _this.onMeshAdded(mesh);
  35706. });
  35707. _this._scene.getGeometries().forEach(function (geometry) {
  35708. _this.onGeometryAdded(geometry);
  35709. });
  35710. break;
  35711. case WorkerTaskType.UPDATE:
  35712. _this._runningUpdated--;
  35713. break;
  35714. case WorkerTaskType.COLLIDE:
  35715. _this._runningCollisionTask = false;
  35716. var returnPayload = returnData.payload;
  35717. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  35718. return;
  35719. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  35720. //cleanup
  35721. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  35722. break;
  35723. }
  35724. };
  35725. this._collisionsCallbackArray = [];
  35726. this._init = false;
  35727. this._runningUpdated = 0;
  35728. this._runningCollisionTask = false;
  35729. this._addUpdateMeshesList = {};
  35730. this._addUpdateGeometriesList = {};
  35731. this._toRemoveGeometryArray = [];
  35732. this._toRemoveMeshesArray = [];
  35733. }
  35734. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  35735. if (!this._init)
  35736. return;
  35737. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  35738. return;
  35739. position.divideToRef(collider.radius, this._scaledPosition);
  35740. velocity.divideToRef(collider.radius, this._scaledVelocity);
  35741. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  35742. var payload = {
  35743. collider: {
  35744. position: this._scaledPosition.asArray(),
  35745. velocity: this._scaledVelocity.asArray(),
  35746. radius: collider.radius.asArray()
  35747. },
  35748. collisionId: collisionIndex,
  35749. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  35750. maximumRetry: maximumRetry
  35751. };
  35752. var message = {
  35753. payload: payload,
  35754. taskType: WorkerTaskType.COLLIDE
  35755. };
  35756. this._worker.postMessage(message);
  35757. };
  35758. CollisionCoordinatorWorker.prototype.init = function (scene) {
  35759. this._scene = scene;
  35760. this._scene.registerAfterRender(this._afterRender);
  35761. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  35762. this._worker = new Worker(workerUrl);
  35763. this._worker.onmessage = this._onMessageFromWorker;
  35764. var message = {
  35765. payload: {},
  35766. taskType: WorkerTaskType.INIT
  35767. };
  35768. this._worker.postMessage(message);
  35769. };
  35770. CollisionCoordinatorWorker.prototype.destroy = function () {
  35771. this._scene.unregisterAfterRender(this._afterRender);
  35772. this._worker.terminate();
  35773. };
  35774. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  35775. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  35776. this.onMeshUpdated(mesh);
  35777. };
  35778. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  35779. this._toRemoveMeshesArray.push(mesh.uniqueId);
  35780. };
  35781. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  35782. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  35783. geometry.onGeometryUpdated = this.onGeometryUpdated;
  35784. this.onGeometryUpdated(geometry);
  35785. };
  35786. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  35787. this._toRemoveGeometryArray.push(geometry.id);
  35788. };
  35789. return CollisionCoordinatorWorker;
  35790. }());
  35791. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  35792. var submeshes = [];
  35793. if (mesh.subMeshes) {
  35794. submeshes = mesh.subMeshes.map(function (sm, idx) {
  35795. return {
  35796. position: idx,
  35797. verticesStart: sm.verticesStart,
  35798. verticesCount: sm.verticesCount,
  35799. indexStart: sm.indexStart,
  35800. indexCount: sm.indexCount,
  35801. hasMaterial: !!sm.getMaterial(),
  35802. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  35803. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  35804. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  35805. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  35806. };
  35807. });
  35808. }
  35809. var geometryId = null;
  35810. if (mesh instanceof BABYLON.Mesh) {
  35811. geometryId = mesh.geometry ? mesh.geometry.id : null;
  35812. }
  35813. else if (mesh instanceof BABYLON.InstancedMesh) {
  35814. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  35815. }
  35816. return {
  35817. uniqueId: mesh.uniqueId,
  35818. id: mesh.id,
  35819. name: mesh.name,
  35820. geometryId: geometryId,
  35821. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  35822. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  35823. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  35824. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  35825. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  35826. subMeshes: submeshes,
  35827. checkCollisions: mesh.checkCollisions
  35828. };
  35829. };
  35830. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  35831. return {
  35832. id: geometry.id,
  35833. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  35834. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  35835. indices: new Uint32Array(geometry.getIndices() || []),
  35836. };
  35837. };
  35838. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  35839. var CollisionCoordinatorLegacy = (function () {
  35840. function CollisionCoordinatorLegacy() {
  35841. this._scaledPosition = BABYLON.Vector3.Zero();
  35842. this._scaledVelocity = BABYLON.Vector3.Zero();
  35843. this._finalPosition = BABYLON.Vector3.Zero();
  35844. }
  35845. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  35846. position.divideToRef(collider.radius, this._scaledPosition);
  35847. velocity.divideToRef(collider.radius, this._scaledVelocity);
  35848. collider.collidedMesh = null;
  35849. collider.retry = 0;
  35850. collider.initialVelocity = this._scaledVelocity;
  35851. collider.initialPosition = this._scaledPosition;
  35852. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  35853. this._finalPosition.multiplyInPlace(collider.radius);
  35854. //run the callback
  35855. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  35856. };
  35857. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  35858. this._scene = scene;
  35859. };
  35860. CollisionCoordinatorLegacy.prototype.destroy = function () {
  35861. //Legacy need no destruction method.
  35862. };
  35863. //No update in legacy mode
  35864. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  35865. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  35866. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  35867. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  35868. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  35869. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  35870. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  35871. if (excludedMesh === void 0) { excludedMesh = null; }
  35872. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  35873. if (collider.retry >= maximumRetry) {
  35874. finalPosition.copyFrom(position);
  35875. return;
  35876. }
  35877. // Check if this is a mesh else camera or -1
  35878. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  35879. collider._initialize(position, velocity, closeDistance);
  35880. // Check all meshes
  35881. for (var index = 0; index < this._scene.meshes.length; index++) {
  35882. var mesh = this._scene.meshes[index];
  35883. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  35884. mesh._checkCollision(collider);
  35885. }
  35886. }
  35887. if (!collider.collisionFound) {
  35888. position.addToRef(velocity, finalPosition);
  35889. return;
  35890. }
  35891. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  35892. collider._getResponse(position, velocity);
  35893. }
  35894. if (velocity.length() <= closeDistance) {
  35895. finalPosition.copyFrom(position);
  35896. return;
  35897. }
  35898. collider.retry++;
  35899. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  35900. };
  35901. return CollisionCoordinatorLegacy;
  35902. }());
  35903. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  35904. })(BABYLON || (BABYLON = {}));
  35905. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  35906. var BABYLON;
  35907. (function (BABYLON) {
  35908. var Particle = (function () {
  35909. function Particle() {
  35910. this.position = BABYLON.Vector3.Zero();
  35911. this.direction = BABYLON.Vector3.Zero();
  35912. this.color = new BABYLON.Color4(0, 0, 0, 0);
  35913. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  35914. this.lifeTime = 1.0;
  35915. this.age = 0;
  35916. this.size = 0;
  35917. this.angle = 0;
  35918. this.angularSpeed = 0;
  35919. }
  35920. Particle.prototype.copyTo = function (other) {
  35921. other.position.copyFrom(this.position);
  35922. other.direction.copyFrom(this.direction);
  35923. other.color.copyFrom(this.color);
  35924. other.colorStep.copyFrom(this.colorStep);
  35925. other.lifeTime = this.lifeTime;
  35926. other.age = this.age;
  35927. other.size = this.size;
  35928. other.angle = this.angle;
  35929. other.angularSpeed = this.angularSpeed;
  35930. };
  35931. return Particle;
  35932. }());
  35933. BABYLON.Particle = Particle;
  35934. })(BABYLON || (BABYLON = {}));
  35935. //# sourceMappingURL=babylon.particle.js.map
  35936. var BABYLON;
  35937. (function (BABYLON) {
  35938. var randomNumber = function (min, max) {
  35939. if (min === max) {
  35940. return (min);
  35941. }
  35942. var random = Math.random();
  35943. return ((random * (max - min)) + min);
  35944. };
  35945. var ParticleSystem = (function () {
  35946. function ParticleSystem(name, capacity, scene, customEffect) {
  35947. var _this = this;
  35948. this.name = name;
  35949. // Members
  35950. this.animations = [];
  35951. this.renderingGroupId = 0;
  35952. this.emitter = null;
  35953. this.emitRate = 10;
  35954. this.manualEmitCount = -1;
  35955. this.updateSpeed = 0.01;
  35956. this.targetStopDuration = 0;
  35957. this.disposeOnStop = false;
  35958. this.minEmitPower = 1;
  35959. this.maxEmitPower = 1;
  35960. this.minLifeTime = 1;
  35961. this.maxLifeTime = 1;
  35962. this.minSize = 1;
  35963. this.maxSize = 1;
  35964. this.minAngularSpeed = 0;
  35965. this.maxAngularSpeed = 0;
  35966. this.layerMask = 0x0FFFFFFF;
  35967. this.customShader = null;
  35968. this.preventAutoStart = false;
  35969. /**
  35970. * An event triggered when the system is disposed.
  35971. * @type {BABYLON.Observable}
  35972. */
  35973. this.onDisposeObservable = new BABYLON.Observable();
  35974. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  35975. this.forceDepthWrite = false;
  35976. this.gravity = BABYLON.Vector3.Zero();
  35977. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  35978. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  35979. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  35980. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  35981. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  35982. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  35983. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  35984. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  35985. this.particles = new Array();
  35986. this._stockParticles = new Array();
  35987. this._newPartsExcess = 0;
  35988. this._vertexBuffers = {};
  35989. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  35990. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  35991. this._scaledDirection = BABYLON.Vector3.Zero();
  35992. this._scaledGravity = BABYLON.Vector3.Zero();
  35993. this._currentRenderId = -1;
  35994. this._started = false;
  35995. this._stopped = false;
  35996. this._actualFrame = 0;
  35997. this.id = name;
  35998. this._capacity = capacity;
  35999. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36000. this._customEffect = customEffect;
  36001. scene.particleSystems.push(this);
  36002. var indices = [];
  36003. var index = 0;
  36004. for (var count = 0; count < capacity; count++) {
  36005. indices.push(index);
  36006. indices.push(index + 1);
  36007. indices.push(index + 2);
  36008. indices.push(index);
  36009. indices.push(index + 2);
  36010. indices.push(index + 3);
  36011. index += 4;
  36012. }
  36013. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  36014. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  36015. this._vertexData = new Float32Array(capacity * 11 * 4);
  36016. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  36017. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  36018. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  36019. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  36020. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  36021. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  36022. this._vertexBuffers["options"] = options;
  36023. // Default behaviors
  36024. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  36025. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  36026. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  36027. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  36028. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  36029. };
  36030. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  36031. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  36032. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  36033. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  36034. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  36035. };
  36036. this.updateFunction = function (particles) {
  36037. for (var index = 0; index < particles.length; index++) {
  36038. var particle = particles[index];
  36039. particle.age += _this._scaledUpdateSpeed;
  36040. if (particle.age >= particle.lifeTime) {
  36041. _this.recycleParticle(particle);
  36042. index--;
  36043. continue;
  36044. }
  36045. else {
  36046. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  36047. particle.color.addInPlace(_this._scaledColorStep);
  36048. if (particle.color.a < 0)
  36049. particle.color.a = 0;
  36050. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  36051. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  36052. particle.position.addInPlace(_this._scaledDirection);
  36053. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  36054. particle.direction.addInPlace(_this._scaledGravity);
  36055. }
  36056. }
  36057. };
  36058. }
  36059. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  36060. set: function (callback) {
  36061. if (this._onDisposeObserver) {
  36062. this.onDisposeObservable.remove(this._onDisposeObserver);
  36063. }
  36064. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36065. },
  36066. enumerable: true,
  36067. configurable: true
  36068. });
  36069. ParticleSystem.prototype.recycleParticle = function (particle) {
  36070. var lastParticle = this.particles.pop();
  36071. if (lastParticle !== particle) {
  36072. lastParticle.copyTo(particle);
  36073. this._stockParticles.push(lastParticle);
  36074. }
  36075. };
  36076. ParticleSystem.prototype.getCapacity = function () {
  36077. return this._capacity;
  36078. };
  36079. ParticleSystem.prototype.isAlive = function () {
  36080. return this._alive;
  36081. };
  36082. ParticleSystem.prototype.isStarted = function () {
  36083. return this._started;
  36084. };
  36085. ParticleSystem.prototype.start = function () {
  36086. this._started = true;
  36087. this._stopped = false;
  36088. this._actualFrame = 0;
  36089. };
  36090. ParticleSystem.prototype.stop = function () {
  36091. this._stopped = true;
  36092. };
  36093. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  36094. var offset = index * 11;
  36095. this._vertexData[offset] = particle.position.x;
  36096. this._vertexData[offset + 1] = particle.position.y;
  36097. this._vertexData[offset + 2] = particle.position.z;
  36098. this._vertexData[offset + 3] = particle.color.r;
  36099. this._vertexData[offset + 4] = particle.color.g;
  36100. this._vertexData[offset + 5] = particle.color.b;
  36101. this._vertexData[offset + 6] = particle.color.a;
  36102. this._vertexData[offset + 7] = particle.angle;
  36103. this._vertexData[offset + 8] = particle.size;
  36104. this._vertexData[offset + 9] = offsetX;
  36105. this._vertexData[offset + 10] = offsetY;
  36106. };
  36107. ParticleSystem.prototype._update = function (newParticles) {
  36108. // Update current
  36109. this._alive = this.particles.length > 0;
  36110. this.updateFunction(this.particles);
  36111. // Add new ones
  36112. var worldMatrix;
  36113. if (this.emitter.position) {
  36114. worldMatrix = this.emitter.getWorldMatrix();
  36115. }
  36116. else {
  36117. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  36118. }
  36119. var particle;
  36120. for (var index = 0; index < newParticles; index++) {
  36121. if (this.particles.length === this._capacity) {
  36122. break;
  36123. }
  36124. if (this._stockParticles.length !== 0) {
  36125. particle = this._stockParticles.pop();
  36126. particle.age = 0;
  36127. }
  36128. else {
  36129. particle = new BABYLON.Particle();
  36130. }
  36131. this.particles.push(particle);
  36132. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  36133. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  36134. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  36135. particle.size = randomNumber(this.minSize, this.maxSize);
  36136. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  36137. this.startPositionFunction(worldMatrix, particle.position, particle);
  36138. var step = randomNumber(0, 1.0);
  36139. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  36140. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  36141. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  36142. }
  36143. };
  36144. ParticleSystem.prototype._getEffect = function () {
  36145. if (this._customEffect) {
  36146. return this._customEffect;
  36147. }
  36148. ;
  36149. var defines = [];
  36150. if (this._scene.clipPlane) {
  36151. defines.push("#define CLIPPLANE");
  36152. }
  36153. // Effect
  36154. var join = defines.join("\n");
  36155. if (this._cachedDefines !== join) {
  36156. this._cachedDefines = join;
  36157. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  36158. }
  36159. return this._effect;
  36160. };
  36161. ParticleSystem.prototype.animate = function () {
  36162. if (!this._started)
  36163. return;
  36164. var effect = this._getEffect();
  36165. // Check
  36166. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  36167. return;
  36168. if (this._currentRenderId === this._scene.getRenderId()) {
  36169. return;
  36170. }
  36171. this._currentRenderId = this._scene.getRenderId();
  36172. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  36173. // determine the number of particles we need to create
  36174. var newParticles;
  36175. if (this.manualEmitCount > -1) {
  36176. newParticles = this.manualEmitCount;
  36177. this._newPartsExcess = 0;
  36178. this.manualEmitCount = 0;
  36179. }
  36180. else {
  36181. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  36182. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  36183. }
  36184. if (this._newPartsExcess > 1.0) {
  36185. newParticles += this._newPartsExcess >> 0;
  36186. this._newPartsExcess -= this._newPartsExcess >> 0;
  36187. }
  36188. this._alive = false;
  36189. if (!this._stopped) {
  36190. this._actualFrame += this._scaledUpdateSpeed;
  36191. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  36192. this.stop();
  36193. }
  36194. else {
  36195. newParticles = 0;
  36196. }
  36197. this._update(newParticles);
  36198. // Stopped?
  36199. if (this._stopped) {
  36200. if (!this._alive) {
  36201. this._started = false;
  36202. if (this.disposeOnStop) {
  36203. this._scene._toBeDisposed.push(this);
  36204. }
  36205. }
  36206. }
  36207. // Update VBO
  36208. var offset = 0;
  36209. for (var index = 0; index < this.particles.length; index++) {
  36210. var particle = this.particles[index];
  36211. this._appendParticleVertex(offset++, particle, 0, 0);
  36212. this._appendParticleVertex(offset++, particle, 1, 0);
  36213. this._appendParticleVertex(offset++, particle, 1, 1);
  36214. this._appendParticleVertex(offset++, particle, 0, 1);
  36215. }
  36216. this._vertexBuffer.update(this._vertexData);
  36217. };
  36218. ParticleSystem.prototype.render = function () {
  36219. var effect = this._getEffect();
  36220. // Check
  36221. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  36222. return 0;
  36223. var engine = this._scene.getEngine();
  36224. // Render
  36225. engine.enableEffect(effect);
  36226. engine.setState(false);
  36227. var viewMatrix = this._scene.getViewMatrix();
  36228. effect.setTexture("diffuseSampler", this.particleTexture);
  36229. effect.setMatrix("view", viewMatrix);
  36230. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  36231. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  36232. if (this._scene.clipPlane) {
  36233. var clipPlane = this._scene.clipPlane;
  36234. var invView = viewMatrix.clone();
  36235. invView.invert();
  36236. effect.setMatrix("invView", invView);
  36237. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  36238. }
  36239. // VBOs
  36240. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36241. // Draw order
  36242. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  36243. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  36244. }
  36245. else {
  36246. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  36247. }
  36248. if (this.forceDepthWrite) {
  36249. engine.setDepthWrite(true);
  36250. }
  36251. engine.draw(true, 0, this.particles.length * 6);
  36252. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36253. return this.particles.length;
  36254. };
  36255. ParticleSystem.prototype.dispose = function () {
  36256. if (this._vertexBuffer) {
  36257. this._vertexBuffer.dispose();
  36258. this._vertexBuffer = null;
  36259. }
  36260. if (this._indexBuffer) {
  36261. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36262. this._indexBuffer = null;
  36263. }
  36264. if (this.particleTexture) {
  36265. this.particleTexture.dispose();
  36266. this.particleTexture = null;
  36267. }
  36268. // Remove from scene
  36269. var index = this._scene.particleSystems.indexOf(this);
  36270. this._scene.particleSystems.splice(index, 1);
  36271. // Callback
  36272. this.onDisposeObservable.notifyObservers(this);
  36273. this.onDisposeObservable.clear();
  36274. };
  36275. // Clone
  36276. ParticleSystem.prototype.clone = function (name, newEmitter) {
  36277. var custom = null;
  36278. var program = null;
  36279. if (this.customShader != null) {
  36280. program = this.customShader;
  36281. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  36282. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  36283. }
  36284. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  36285. result.customShader = program;
  36286. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  36287. if (newEmitter === undefined) {
  36288. newEmitter = this.emitter;
  36289. }
  36290. result.emitter = newEmitter;
  36291. if (this.particleTexture) {
  36292. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  36293. }
  36294. if (!this.preventAutoStart) {
  36295. result.start();
  36296. }
  36297. return result;
  36298. };
  36299. ParticleSystem.prototype.serialize = function () {
  36300. var serializationObject = {};
  36301. serializationObject.name = this.name;
  36302. serializationObject.id = this.id;
  36303. // Emitter
  36304. if (this.emitter.position) {
  36305. serializationObject.emitterId = this.emitter.id;
  36306. }
  36307. else {
  36308. serializationObject.emitter = this.emitter.asArray();
  36309. }
  36310. serializationObject.capacity = this.getCapacity();
  36311. if (this.particleTexture) {
  36312. serializationObject.textureName = this.particleTexture.name;
  36313. }
  36314. // Animations
  36315. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  36316. // Particle system
  36317. serializationObject.minAngularSpeed = this.minAngularSpeed;
  36318. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  36319. serializationObject.minSize = this.minSize;
  36320. serializationObject.maxSize = this.maxSize;
  36321. serializationObject.minEmitPower = this.minEmitPower;
  36322. serializationObject.maxEmitPower = this.maxEmitPower;
  36323. serializationObject.minLifeTime = this.minLifeTime;
  36324. serializationObject.maxLifeTime = this.maxLifeTime;
  36325. serializationObject.emitRate = this.emitRate;
  36326. serializationObject.minEmitBox = this.minEmitBox.asArray();
  36327. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  36328. serializationObject.gravity = this.gravity.asArray();
  36329. serializationObject.direction1 = this.direction1.asArray();
  36330. serializationObject.direction2 = this.direction2.asArray();
  36331. serializationObject.color1 = this.color1.asArray();
  36332. serializationObject.color2 = this.color2.asArray();
  36333. serializationObject.colorDead = this.colorDead.asArray();
  36334. serializationObject.updateSpeed = this.updateSpeed;
  36335. serializationObject.targetStopDuration = this.targetStopDuration;
  36336. serializationObject.textureMask = this.textureMask.asArray();
  36337. serializationObject.blendMode = this.blendMode;
  36338. serializationObject.customShader = this.customShader;
  36339. serializationObject.preventAutoStart = this.preventAutoStart;
  36340. return serializationObject;
  36341. };
  36342. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  36343. var name = parsedParticleSystem.name;
  36344. var custom = null;
  36345. var program = null;
  36346. if (parsedParticleSystem.customShader) {
  36347. program = parsedParticleSystem.customShader;
  36348. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  36349. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  36350. }
  36351. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  36352. particleSystem.customShader = program;
  36353. if (parsedParticleSystem.id) {
  36354. particleSystem.id = parsedParticleSystem.id;
  36355. }
  36356. // Auto start
  36357. if (parsedParticleSystem.preventAutoStart) {
  36358. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  36359. }
  36360. // Texture
  36361. if (parsedParticleSystem.textureName) {
  36362. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  36363. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  36364. }
  36365. // Emitter
  36366. if (parsedParticleSystem.emitterId) {
  36367. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  36368. }
  36369. else {
  36370. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  36371. }
  36372. // Animations
  36373. if (parsedParticleSystem.animations) {
  36374. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  36375. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  36376. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  36377. }
  36378. }
  36379. if (parsedParticleSystem.autoAnimate) {
  36380. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  36381. }
  36382. // Particle system
  36383. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  36384. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  36385. particleSystem.minSize = parsedParticleSystem.minSize;
  36386. particleSystem.maxSize = parsedParticleSystem.maxSize;
  36387. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  36388. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  36389. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  36390. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  36391. particleSystem.emitRate = parsedParticleSystem.emitRate;
  36392. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  36393. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  36394. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  36395. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  36396. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  36397. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  36398. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  36399. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  36400. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  36401. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  36402. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  36403. particleSystem.blendMode = parsedParticleSystem.blendMode;
  36404. if (!particleSystem.preventAutoStart) {
  36405. particleSystem.start();
  36406. }
  36407. return particleSystem;
  36408. };
  36409. return ParticleSystem;
  36410. }());
  36411. // Statics
  36412. ParticleSystem.BLENDMODE_ONEONE = 0;
  36413. ParticleSystem.BLENDMODE_STANDARD = 1;
  36414. BABYLON.ParticleSystem = ParticleSystem;
  36415. })(BABYLON || (BABYLON = {}));
  36416. //# sourceMappingURL=babylon.particleSystem.js.map
  36417. var BABYLON;
  36418. (function (BABYLON) {
  36419. var SolidParticle = (function () {
  36420. /**
  36421. * Creates a Solid Particle object.
  36422. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  36423. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  36424. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  36425. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  36426. * `shapeId` (integer) is the model shape identifier in the SPS.
  36427. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  36428. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  36429. */
  36430. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  36431. this.idx = 0; // particle global index
  36432. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  36433. this.position = BABYLON.Vector3.Zero(); // position
  36434. this.rotation = BABYLON.Vector3.Zero(); // rotation
  36435. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  36436. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  36437. this.velocity = BABYLON.Vector3.Zero(); // velocity
  36438. this.alive = true; // alive
  36439. this.isVisible = true; // visibility
  36440. this._pos = 0; // index of this particle in the global "positions" array
  36441. this.shapeId = 0; // model shape id
  36442. this.idxInShape = 0; // index of the particle in its shape id
  36443. this.idx = particleIndex;
  36444. this._pos = positionIndex;
  36445. this._model = model;
  36446. this.shapeId = shapeId;
  36447. this.idxInShape = idxInShape;
  36448. this._sps = sps;
  36449. if (modelBoundingInfo) {
  36450. this._modelBoundingInfo = modelBoundingInfo;
  36451. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  36452. }
  36453. }
  36454. Object.defineProperty(SolidParticle.prototype, "scale", {
  36455. /**
  36456. * legacy support, changed scale to scaling
  36457. */
  36458. get: function () {
  36459. return this.scaling;
  36460. },
  36461. set: function (scale) {
  36462. this.scaling = scale;
  36463. },
  36464. enumerable: true,
  36465. configurable: true
  36466. });
  36467. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  36468. /**
  36469. * legacy support, changed quaternion to rotationQuaternion
  36470. */
  36471. get: function () {
  36472. return this.rotationQuaternion;
  36473. },
  36474. set: function (q) {
  36475. this.rotationQuaternion = q;
  36476. },
  36477. enumerable: true,
  36478. configurable: true
  36479. });
  36480. /**
  36481. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  36482. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  36483. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  36484. */
  36485. SolidParticle.prototype.intersectsMesh = function (target) {
  36486. if (!this._boundingInfo || !target._boundingInfo) {
  36487. return false;
  36488. }
  36489. if (this._sps._bSphereOnly) {
  36490. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  36491. }
  36492. return this._boundingInfo.intersects(target._boundingInfo, false);
  36493. };
  36494. return SolidParticle;
  36495. }());
  36496. BABYLON.SolidParticle = SolidParticle;
  36497. var ModelShape = (function () {
  36498. /**
  36499. * 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.
  36500. * SPS internal tool, don't use it manually.
  36501. */
  36502. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  36503. this.shapeID = id;
  36504. this._shape = shape;
  36505. this._shapeUV = shapeUV;
  36506. this._positionFunction = posFunction;
  36507. this._vertexFunction = vtxFunction;
  36508. }
  36509. return ModelShape;
  36510. }());
  36511. BABYLON.ModelShape = ModelShape;
  36512. })(BABYLON || (BABYLON = {}));
  36513. //# sourceMappingURL=babylon.solidParticle.js.map
  36514. var BABYLON;
  36515. (function (BABYLON) {
  36516. /**
  36517. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  36518. */
  36519. var SolidParticleSystem = (function () {
  36520. /**
  36521. * Creates a SPS (Solid Particle System) object.
  36522. * `name` (String) is the SPS name, this will be the underlying mesh name.
  36523. * `scene` (Scene) is the scene in which the SPS is added.
  36524. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  36525. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  36526. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  36527. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  36528. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  36529. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  36530. */
  36531. function SolidParticleSystem(name, scene, options) {
  36532. // public members
  36533. /**
  36534. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  36535. * Example : var p = SPS.particles[i];
  36536. */
  36537. this.particles = new Array();
  36538. /**
  36539. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  36540. */
  36541. this.nbParticles = 0;
  36542. /**
  36543. * If the particles must ever face the camera (default false). Useful for planar particles.
  36544. */
  36545. this.billboard = false;
  36546. /**
  36547. * Recompute normals when adding a shape
  36548. */
  36549. this.recomputeNormals = true;
  36550. /**
  36551. * This a counter ofr your own usage. It's not set by any SPS functions.
  36552. */
  36553. this.counter = 0;
  36554. /**
  36555. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  36556. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  36557. */
  36558. this.vars = {};
  36559. this._positions = new Array();
  36560. this._indices = new Array();
  36561. this._normals = new Array();
  36562. this._colors = new Array();
  36563. this._uvs = new Array();
  36564. this._index = 0; // indices index
  36565. this._updatable = true;
  36566. this._pickable = false;
  36567. this._isVisibilityBoxLocked = false;
  36568. this._alwaysVisible = false;
  36569. this._shapeCounter = 0;
  36570. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  36571. this._color = new BABYLON.Color4(0, 0, 0, 0);
  36572. this._computeParticleColor = true;
  36573. this._computeParticleTexture = true;
  36574. this._computeParticleRotation = true;
  36575. this._computeParticleVertex = false;
  36576. this._computeBoundingBox = false;
  36577. this._cam_axisZ = BABYLON.Vector3.Zero();
  36578. this._cam_axisY = BABYLON.Vector3.Zero();
  36579. this._cam_axisX = BABYLON.Vector3.Zero();
  36580. this._axisX = BABYLON.Axis.X;
  36581. this._axisY = BABYLON.Axis.Y;
  36582. this._axisZ = BABYLON.Axis.Z;
  36583. this._camDir = BABYLON.Vector3.Zero();
  36584. this._rotMatrix = new BABYLON.Matrix();
  36585. this._invertMatrix = new BABYLON.Matrix();
  36586. this._rotated = BABYLON.Vector3.Zero();
  36587. this._quaternion = new BABYLON.Quaternion();
  36588. this._vertex = BABYLON.Vector3.Zero();
  36589. this._normal = BABYLON.Vector3.Zero();
  36590. this._yaw = 0.0;
  36591. this._pitch = 0.0;
  36592. this._roll = 0.0;
  36593. this._halfroll = 0.0;
  36594. this._halfpitch = 0.0;
  36595. this._halfyaw = 0.0;
  36596. this._sinRoll = 0.0;
  36597. this._cosRoll = 0.0;
  36598. this._sinPitch = 0.0;
  36599. this._cosPitch = 0.0;
  36600. this._sinYaw = 0.0;
  36601. this._cosYaw = 0.0;
  36602. this._w = 0.0;
  36603. this._mustUnrotateFixedNormals = false;
  36604. this._minimum = BABYLON.Tmp.Vector3[0];
  36605. this._maximum = BABYLON.Tmp.Vector3[1];
  36606. this._scale = BABYLON.Tmp.Vector3[2];
  36607. this._translation = BABYLON.Tmp.Vector3[3];
  36608. this._minBbox = BABYLON.Tmp.Vector3[4];
  36609. this._maxBbox = BABYLON.Tmp.Vector3[5];
  36610. this._particlesIntersect = false;
  36611. this._bSphereOnly = false;
  36612. this._bSphereRadiusFactor = 1.0;
  36613. this.name = name;
  36614. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36615. this._camera = scene.activeCamera;
  36616. this._pickable = options ? options.isPickable : false;
  36617. this._particlesIntersect = options ? options.particleIntersection : false;
  36618. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  36619. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  36620. if (options && options.updatable) {
  36621. this._updatable = options.updatable;
  36622. }
  36623. else {
  36624. this._updatable = true;
  36625. }
  36626. if (this._pickable) {
  36627. this.pickedParticles = [];
  36628. }
  36629. }
  36630. /**
  36631. * Builds the SPS underlying mesh. Returns a standard Mesh.
  36632. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  36633. */
  36634. SolidParticleSystem.prototype.buildMesh = function () {
  36635. if (this.nbParticles === 0) {
  36636. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  36637. this.addShape(triangle, 1);
  36638. triangle.dispose();
  36639. }
  36640. this._positions32 = new Float32Array(this._positions);
  36641. this._uvs32 = new Float32Array(this._uvs);
  36642. this._colors32 = new Float32Array(this._colors);
  36643. if (this.recomputeNormals) {
  36644. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  36645. }
  36646. this._normals32 = new Float32Array(this._normals);
  36647. this._fixedNormal32 = new Float32Array(this._normals);
  36648. if (this._mustUnrotateFixedNormals) {
  36649. this._unrotateFixedNormals();
  36650. }
  36651. var vertexData = new BABYLON.VertexData();
  36652. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  36653. vertexData.indices = this._indices;
  36654. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  36655. if (this._uvs32) {
  36656. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  36657. ;
  36658. }
  36659. if (this._colors32) {
  36660. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  36661. }
  36662. var mesh = new BABYLON.Mesh(this.name, this._scene);
  36663. vertexData.applyToMesh(mesh, this._updatable);
  36664. this.mesh = mesh;
  36665. this.mesh.isPickable = this._pickable;
  36666. // free memory
  36667. this._positions = null;
  36668. this._normals = null;
  36669. this._uvs = null;
  36670. this._colors = null;
  36671. if (!this._updatable) {
  36672. this.particles.length = 0;
  36673. }
  36674. return mesh;
  36675. };
  36676. /**
  36677. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  36678. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  36679. * Thus the particles generated from `digest()` have their property `position` set yet.
  36680. * `mesh` ( Mesh ) is the mesh to be digested
  36681. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  36682. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  36683. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  36684. */
  36685. SolidParticleSystem.prototype.digest = function (mesh, options) {
  36686. var size = (options && options.facetNb) || 1;
  36687. var number = (options && options.number);
  36688. var delta = (options && options.delta) || 0;
  36689. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36690. var meshInd = mesh.getIndices();
  36691. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36692. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36693. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36694. var f = 0; // facet counter
  36695. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  36696. // compute size from number
  36697. if (number) {
  36698. number = (number > totalFacets) ? totalFacets : number;
  36699. size = Math.round(totalFacets / number);
  36700. delta = 0;
  36701. }
  36702. else {
  36703. size = (size > totalFacets) ? totalFacets : size;
  36704. }
  36705. var facetPos = []; // submesh positions
  36706. var facetInd = []; // submesh indices
  36707. var facetUV = []; // submesh UV
  36708. var facetCol = []; // submesh colors
  36709. var barycenter = BABYLON.Tmp.Vector3[0];
  36710. var rand;
  36711. var sizeO = size;
  36712. while (f < totalFacets) {
  36713. size = sizeO + Math.floor((1 + delta) * Math.random());
  36714. if (f > totalFacets - size) {
  36715. size = totalFacets - f;
  36716. }
  36717. // reset temp arrays
  36718. facetPos.length = 0;
  36719. facetInd.length = 0;
  36720. facetUV.length = 0;
  36721. facetCol.length = 0;
  36722. // iterate over "size" facets
  36723. var fi = 0;
  36724. for (var j = f * 3; j < (f + size) * 3; j++) {
  36725. facetInd.push(fi);
  36726. var i = meshInd[j];
  36727. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  36728. if (meshUV) {
  36729. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  36730. }
  36731. if (meshCol) {
  36732. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  36733. }
  36734. fi++;
  36735. }
  36736. // create a model shape for each single particle
  36737. var idx = this.nbParticles;
  36738. var shape = this._posToShape(facetPos);
  36739. var shapeUV = this._uvsToShapeUV(facetUV);
  36740. // compute the barycenter of the shape
  36741. var v;
  36742. for (v = 0; v < shape.length; v++) {
  36743. barycenter.addInPlace(shape[v]);
  36744. }
  36745. barycenter.scaleInPlace(1 / shape.length);
  36746. // shift the shape from its barycenter to the origin
  36747. for (v = 0; v < shape.length; v++) {
  36748. shape[v].subtractInPlace(barycenter);
  36749. }
  36750. var bInfo;
  36751. if (this._particlesIntersect) {
  36752. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  36753. }
  36754. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  36755. // add the particle in the SPS
  36756. var currentPos = this._positions.length;
  36757. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  36758. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  36759. // initialize the particle position
  36760. this.particles[this.nbParticles].position.addInPlace(barycenter);
  36761. this._index += shape.length;
  36762. idx++;
  36763. this.nbParticles++;
  36764. this._shapeCounter++;
  36765. f += size;
  36766. }
  36767. return this;
  36768. };
  36769. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  36770. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  36771. var index = 0;
  36772. var idx = 0;
  36773. for (var p = 0; p < this.particles.length; p++) {
  36774. this._particle = this.particles[p];
  36775. this._shape = this._particle._model._shape;
  36776. if (this._particle.rotationQuaternion) {
  36777. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  36778. }
  36779. else {
  36780. this._yaw = this._particle.rotation.y;
  36781. this._pitch = this._particle.rotation.x;
  36782. this._roll = this._particle.rotation.z;
  36783. this._quaternionRotationYPR();
  36784. }
  36785. this._quaternionToRotationMatrix();
  36786. this._rotMatrix.invertToRef(this._invertMatrix);
  36787. for (var pt = 0; pt < this._shape.length; pt++) {
  36788. idx = index + pt * 3;
  36789. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  36790. this._fixedNormal32[idx] = this._normal.x;
  36791. this._fixedNormal32[idx + 1] = this._normal.y;
  36792. this._fixedNormal32[idx + 2] = this._normal.z;
  36793. }
  36794. index = idx + 3;
  36795. }
  36796. };
  36797. //reset copy
  36798. SolidParticleSystem.prototype._resetCopy = function () {
  36799. this._copy.position.x = 0;
  36800. this._copy.position.y = 0;
  36801. this._copy.position.z = 0;
  36802. this._copy.rotation.x = 0;
  36803. this._copy.rotation.y = 0;
  36804. this._copy.rotation.z = 0;
  36805. this._copy.rotationQuaternion = null;
  36806. this._copy.scaling.x = 1;
  36807. this._copy.scaling.y = 1;
  36808. this._copy.scaling.z = 1;
  36809. this._copy.uvs.x = 0;
  36810. this._copy.uvs.y = 0;
  36811. this._copy.uvs.z = 1;
  36812. this._copy.uvs.w = 1;
  36813. this._copy.color = null;
  36814. };
  36815. // _meshBuilder : inserts the shape model in the global SPS mesh
  36816. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  36817. var i;
  36818. var u = 0;
  36819. var c = 0;
  36820. var n = 0;
  36821. this._resetCopy();
  36822. if (options && options.positionFunction) {
  36823. options.positionFunction(this._copy, idx, idxInShape);
  36824. this._mustUnrotateFixedNormals = true;
  36825. }
  36826. if (this._copy.rotationQuaternion) {
  36827. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  36828. }
  36829. else {
  36830. this._yaw = this._copy.rotation.y;
  36831. this._pitch = this._copy.rotation.x;
  36832. this._roll = this._copy.rotation.z;
  36833. this._quaternionRotationYPR();
  36834. }
  36835. this._quaternionToRotationMatrix();
  36836. for (i = 0; i < shape.length; i++) {
  36837. this._vertex.x = shape[i].x;
  36838. this._vertex.y = shape[i].y;
  36839. this._vertex.z = shape[i].z;
  36840. if (options && options.vertexFunction) {
  36841. options.vertexFunction(this._copy, this._vertex, i);
  36842. }
  36843. this._vertex.x *= this._copy.scaling.x;
  36844. this._vertex.y *= this._copy.scaling.y;
  36845. this._vertex.z *= this._copy.scaling.z;
  36846. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36847. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  36848. if (meshUV) {
  36849. 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);
  36850. u += 2;
  36851. }
  36852. if (this._copy.color) {
  36853. this._color = this._copy.color;
  36854. }
  36855. else if (meshCol && meshCol[c] !== undefined) {
  36856. this._color.r = meshCol[c];
  36857. this._color.g = meshCol[c + 1];
  36858. this._color.b = meshCol[c + 2];
  36859. this._color.a = meshCol[c + 3];
  36860. }
  36861. else {
  36862. this._color.r = 1;
  36863. this._color.g = 1;
  36864. this._color.b = 1;
  36865. this._color.a = 1;
  36866. }
  36867. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  36868. c += 4;
  36869. if (!this.recomputeNormals && meshNor) {
  36870. this._normal.x = meshNor[n];
  36871. this._normal.y = meshNor[n + 1];
  36872. this._normal.z = meshNor[n + 2];
  36873. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  36874. normals.push(this._normal.x, this._normal.y, this._normal.z);
  36875. n += 3;
  36876. }
  36877. }
  36878. for (i = 0; i < meshInd.length; i++) {
  36879. indices.push(p + meshInd[i]);
  36880. }
  36881. if (this._pickable) {
  36882. var nbfaces = meshInd.length / 3;
  36883. for (i = 0; i < nbfaces; i++) {
  36884. this.pickedParticles.push({ idx: idx, faceId: i });
  36885. }
  36886. }
  36887. return this._copy;
  36888. };
  36889. // returns a shape array from positions array
  36890. SolidParticleSystem.prototype._posToShape = function (positions) {
  36891. var shape = [];
  36892. for (var i = 0; i < positions.length; i += 3) {
  36893. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  36894. }
  36895. return shape;
  36896. };
  36897. // returns a shapeUV array from a Vector4 uvs
  36898. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  36899. var shapeUV = [];
  36900. if (uvs) {
  36901. for (var i = 0; i < uvs.length; i++)
  36902. shapeUV.push(uvs[i]);
  36903. }
  36904. return shapeUV;
  36905. };
  36906. // adds a new particle object in the particles array
  36907. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  36908. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  36909. this.particles.push(sp);
  36910. return sp;
  36911. };
  36912. /**
  36913. * Adds some particles to the SPS from the model shape. Returns the shape id.
  36914. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  36915. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  36916. * `nb` (positive integer) the number of particles to be created from this model
  36917. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  36918. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  36919. */
  36920. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  36921. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36922. var meshInd = mesh.getIndices();
  36923. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36924. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36925. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36926. var bbInfo;
  36927. if (this._particlesIntersect) {
  36928. bbInfo = mesh.getBoundingInfo();
  36929. }
  36930. var shape = this._posToShape(meshPos);
  36931. var shapeUV = this._uvsToShapeUV(meshUV);
  36932. var posfunc = options ? options.positionFunction : null;
  36933. var vtxfunc = options ? options.vertexFunction : null;
  36934. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  36935. // particles
  36936. var sp;
  36937. var currentCopy;
  36938. var idx = this.nbParticles;
  36939. for (var i = 0; i < nb; i++) {
  36940. var currentPos = this._positions.length;
  36941. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  36942. if (this._updatable) {
  36943. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  36944. sp.position.copyFrom(currentCopy.position);
  36945. sp.rotation.copyFrom(currentCopy.rotation);
  36946. if (currentCopy.rotationQuaternion) {
  36947. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  36948. }
  36949. if (currentCopy.color) {
  36950. sp.color.copyFrom(currentCopy.color);
  36951. }
  36952. sp.scaling.copyFrom(currentCopy.scaling);
  36953. sp.uvs.copyFrom(currentCopy.uvs);
  36954. }
  36955. this._index += shape.length;
  36956. idx++;
  36957. }
  36958. this.nbParticles += nb;
  36959. this._shapeCounter++;
  36960. return this._shapeCounter - 1;
  36961. };
  36962. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  36963. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  36964. this._resetCopy();
  36965. if (particle._model._positionFunction) {
  36966. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  36967. }
  36968. if (this._copy.rotationQuaternion) {
  36969. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  36970. }
  36971. else {
  36972. this._yaw = this._copy.rotation.y;
  36973. this._pitch = this._copy.rotation.x;
  36974. this._roll = this._copy.rotation.z;
  36975. this._quaternionRotationYPR();
  36976. }
  36977. this._quaternionToRotationMatrix();
  36978. this._shape = particle._model._shape;
  36979. for (var pt = 0; pt < this._shape.length; pt++) {
  36980. this._vertex.x = this._shape[pt].x;
  36981. this._vertex.y = this._shape[pt].y;
  36982. this._vertex.z = this._shape[pt].z;
  36983. if (particle._model._vertexFunction) {
  36984. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  36985. }
  36986. this._vertex.x *= this._copy.scaling.x;
  36987. this._vertex.y *= this._copy.scaling.y;
  36988. this._vertex.z *= this._copy.scaling.z;
  36989. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  36990. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  36991. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  36992. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  36993. }
  36994. particle.position.x = 0.0;
  36995. particle.position.y = 0.0;
  36996. particle.position.z = 0.0;
  36997. particle.rotation.x = 0.0;
  36998. particle.rotation.y = 0.0;
  36999. particle.rotation.z = 0.0;
  37000. particle.rotationQuaternion = null;
  37001. particle.scaling.x = 1.0;
  37002. particle.scaling.y = 1.0;
  37003. particle.scaling.z = 1.0;
  37004. };
  37005. /**
  37006. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  37007. * Returns the SPS.
  37008. */
  37009. SolidParticleSystem.prototype.rebuildMesh = function () {
  37010. for (var p = 0; p < this.particles.length; p++) {
  37011. this._rebuildParticle(this.particles[p]);
  37012. }
  37013. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37014. return this;
  37015. };
  37016. /**
  37017. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  37018. * This method calls `updateParticle()` for each particle of the SPS.
  37019. * For an animated SPS, it is usually called within the render loop.
  37020. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  37021. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  37022. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  37023. * Returns the SPS.
  37024. */
  37025. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  37026. if (start === void 0) { start = 0; }
  37027. if (end === void 0) { end = this.nbParticles - 1; }
  37028. if (update === void 0) { update = true; }
  37029. if (!this._updatable) {
  37030. return;
  37031. }
  37032. // custom beforeUpdate
  37033. this.beforeUpdateParticles(start, end, update);
  37034. this._cam_axisX.x = 1.0;
  37035. this._cam_axisX.y = 0.0;
  37036. this._cam_axisX.z = 0.0;
  37037. this._cam_axisY.x = 0.0;
  37038. this._cam_axisY.y = 1.0;
  37039. this._cam_axisY.z = 0.0;
  37040. this._cam_axisZ.x = 0.0;
  37041. this._cam_axisZ.y = 0.0;
  37042. this._cam_axisZ.z = 1.0;
  37043. // if the particles will always face the camera
  37044. if (this.billboard) {
  37045. this.mesh.computeWorldMatrix(true);
  37046. // compute the camera position and un-rotate it by the current mesh rotation
  37047. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  37048. this._quaternionToRotationMatrix();
  37049. this._rotMatrix.invertToRef(this._invertMatrix);
  37050. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  37051. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  37052. this._cam_axisZ.normalize();
  37053. // same for camera up vector extracted from the cam view matrix
  37054. var view = this._camera.getViewMatrix(true);
  37055. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  37056. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  37057. this._cam_axisY.normalize();
  37058. this._cam_axisX.normalize();
  37059. }
  37060. }
  37061. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  37062. var idx = 0; // current position index in the global array positions32
  37063. var index = 0; // position start index in the global array positions32 of the current particle
  37064. var colidx = 0; // current color index in the global array colors32
  37065. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  37066. var uvidx = 0; // current uv index in the global array uvs32
  37067. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  37068. var pt = 0; // current index in the particle model shape
  37069. if (this.mesh.isFacetDataEnabled) {
  37070. this._computeBoundingBox = true;
  37071. }
  37072. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  37073. if (this._computeBoundingBox) {
  37074. if (start == 0 && end == this.nbParticles - 1) {
  37075. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  37076. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  37077. }
  37078. else {
  37079. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  37080. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  37081. }
  37082. }
  37083. // particle loop
  37084. index = this.particles[start]._pos;
  37085. var vpos = (index / 3) | 0;
  37086. colorIndex = vpos * 4;
  37087. uvIndex = vpos * 2;
  37088. for (var p = start; p <= end; p++) {
  37089. this._particle = this.particles[p];
  37090. this._shape = this._particle._model._shape;
  37091. this._shapeUV = this._particle._model._shapeUV;
  37092. // call to custom user function to update the particle properties
  37093. this.updateParticle(this._particle);
  37094. if (this._particle.isVisible) {
  37095. // particle rotation matrix
  37096. if (this.billboard) {
  37097. this._particle.rotation.x = 0.0;
  37098. this._particle.rotation.y = 0.0;
  37099. }
  37100. if (this._computeParticleRotation || this.billboard) {
  37101. if (this._particle.rotationQuaternion) {
  37102. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  37103. }
  37104. else {
  37105. this._yaw = this._particle.rotation.y;
  37106. this._pitch = this._particle.rotation.x;
  37107. this._roll = this._particle.rotation.z;
  37108. this._quaternionRotationYPR();
  37109. }
  37110. this._quaternionToRotationMatrix();
  37111. }
  37112. // particle vertex loop
  37113. for (pt = 0; pt < this._shape.length; pt++) {
  37114. idx = index + pt * 3;
  37115. colidx = colorIndex + pt * 4;
  37116. uvidx = uvIndex + pt * 2;
  37117. this._vertex.x = this._shape[pt].x;
  37118. this._vertex.y = this._shape[pt].y;
  37119. this._vertex.z = this._shape[pt].z;
  37120. if (this._computeParticleVertex) {
  37121. this.updateParticleVertex(this._particle, this._vertex, pt);
  37122. }
  37123. // positions
  37124. this._vertex.x *= this._particle.scaling.x;
  37125. this._vertex.y *= this._particle.scaling.y;
  37126. this._vertex.z *= this._particle.scaling.z;
  37127. 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];
  37128. 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;
  37129. 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;
  37130. 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;
  37131. 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;
  37132. 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;
  37133. 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;
  37134. if (this._computeBoundingBox) {
  37135. if (this._positions32[idx] < this._minimum.x) {
  37136. this._minimum.x = this._positions32[idx];
  37137. }
  37138. if (this._positions32[idx] > this._maximum.x) {
  37139. this._maximum.x = this._positions32[idx];
  37140. }
  37141. if (this._positions32[idx + 1] < this._minimum.y) {
  37142. this._minimum.y = this._positions32[idx + 1];
  37143. }
  37144. if (this._positions32[idx + 1] > this._maximum.y) {
  37145. this._maximum.y = this._positions32[idx + 1];
  37146. }
  37147. if (this._positions32[idx + 2] < this._minimum.z) {
  37148. this._minimum.z = this._positions32[idx + 2];
  37149. }
  37150. if (this._positions32[idx + 2] > this._maximum.z) {
  37151. this._maximum.z = this._positions32[idx + 2];
  37152. }
  37153. }
  37154. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  37155. if (!this._computeParticleVertex) {
  37156. this._normal.x = this._fixedNormal32[idx];
  37157. this._normal.y = this._fixedNormal32[idx + 1];
  37158. this._normal.z = this._fixedNormal32[idx + 2];
  37159. 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]);
  37160. 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]);
  37161. 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]);
  37162. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  37163. 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;
  37164. 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;
  37165. }
  37166. if (this._computeParticleColor) {
  37167. this._colors32[colidx] = this._particle.color.r;
  37168. this._colors32[colidx + 1] = this._particle.color.g;
  37169. this._colors32[colidx + 2] = this._particle.color.b;
  37170. this._colors32[colidx + 3] = this._particle.color.a;
  37171. }
  37172. if (this._computeParticleTexture) {
  37173. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37174. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37175. }
  37176. }
  37177. }
  37178. else {
  37179. for (pt = 0; pt < this._shape.length; pt++) {
  37180. idx = index + pt * 3;
  37181. colidx = colorIndex + pt * 4;
  37182. uvidx = uvIndex + pt * 2;
  37183. this._positions32[idx] = this._camera.position.x;
  37184. this._positions32[idx + 1] = this._camera.position.y;
  37185. this._positions32[idx + 2] = this._camera.position.z;
  37186. this._normals32[idx] = 0.0;
  37187. this._normals32[idx + 1] = 0.0;
  37188. this._normals32[idx + 2] = 0.0;
  37189. if (this._computeParticleColor) {
  37190. this._colors32[colidx] = this._particle.color.r;
  37191. this._colors32[colidx + 1] = this._particle.color.g;
  37192. this._colors32[colidx + 2] = this._particle.color.b;
  37193. this._colors32[colidx + 3] = this._particle.color.a;
  37194. }
  37195. if (this._computeParticleTexture) {
  37196. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  37197. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  37198. }
  37199. }
  37200. }
  37201. // if the particle intersections must be computed : update the bbInfo
  37202. if (this._particlesIntersect) {
  37203. var bInfo = this._particle._boundingInfo;
  37204. var bBox = bInfo.boundingBox;
  37205. var bSphere = bInfo.boundingSphere;
  37206. if (!this._bSphereOnly) {
  37207. // place, scale and rotate the particle bbox within the SPS local system, then update it
  37208. for (var b = 0; b < bBox.vectors.length; b++) {
  37209. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  37210. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  37211. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  37212. 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];
  37213. 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;
  37214. 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;
  37215. 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;
  37216. 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;
  37217. 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;
  37218. 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;
  37219. }
  37220. bBox._update(this.mesh._worldMatrix);
  37221. }
  37222. // place and scale the particle bouding sphere in the SPS local system, then update it
  37223. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  37224. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  37225. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  37226. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  37227. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  37228. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  37229. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  37230. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  37231. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  37232. 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));
  37233. bSphere._update(this.mesh._worldMatrix);
  37234. }
  37235. // increment indexes for the next particle
  37236. index = idx + 3;
  37237. colorIndex = colidx + 4;
  37238. uvIndex = uvidx + 2;
  37239. }
  37240. // if the VBO must be updated
  37241. if (update) {
  37242. if (this._computeParticleColor) {
  37243. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  37244. }
  37245. if (this._computeParticleTexture) {
  37246. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  37247. }
  37248. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  37249. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  37250. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  37251. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  37252. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  37253. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  37254. for (var i = 0; i < this._normals32.length; i++) {
  37255. this._fixedNormal32[i] = this._normals32[i];
  37256. }
  37257. }
  37258. if (!this.mesh.areNormalsFrozen) {
  37259. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  37260. }
  37261. }
  37262. }
  37263. if (this._computeBoundingBox) {
  37264. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  37265. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  37266. }
  37267. this.afterUpdateParticles(start, end, update);
  37268. return this;
  37269. };
  37270. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  37271. this._halfroll = this._roll * 0.5;
  37272. this._halfpitch = this._pitch * 0.5;
  37273. this._halfyaw = this._yaw * 0.5;
  37274. this._sinRoll = Math.sin(this._halfroll);
  37275. this._cosRoll = Math.cos(this._halfroll);
  37276. this._sinPitch = Math.sin(this._halfpitch);
  37277. this._cosPitch = Math.cos(this._halfpitch);
  37278. this._sinYaw = Math.sin(this._halfyaw);
  37279. this._cosYaw = Math.cos(this._halfyaw);
  37280. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  37281. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  37282. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  37283. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  37284. };
  37285. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  37286. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  37287. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  37288. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  37289. this._rotMatrix.m[3] = 0;
  37290. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  37291. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  37292. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  37293. this._rotMatrix.m[7] = 0;
  37294. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  37295. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  37296. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  37297. this._rotMatrix.m[11] = 0;
  37298. this._rotMatrix.m[12] = 0;
  37299. this._rotMatrix.m[13] = 0;
  37300. this._rotMatrix.m[14] = 0;
  37301. this._rotMatrix.m[15] = 1.0;
  37302. };
  37303. /**
  37304. * Disposes the SPS.
  37305. * Returns nothing.
  37306. */
  37307. SolidParticleSystem.prototype.dispose = function () {
  37308. this.mesh.dispose();
  37309. this.vars = null;
  37310. // drop references to internal big arrays for the GC
  37311. this._positions = null;
  37312. this._indices = null;
  37313. this._normals = null;
  37314. this._uvs = null;
  37315. this._colors = null;
  37316. this._positions32 = null;
  37317. this._normals32 = null;
  37318. this._fixedNormal32 = null;
  37319. this._uvs32 = null;
  37320. this._colors32 = null;
  37321. this.pickedParticles = null;
  37322. };
  37323. /**
  37324. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  37325. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37326. * Returns the SPS.
  37327. */
  37328. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  37329. if (!this._isVisibilityBoxLocked) {
  37330. this.mesh.refreshBoundingInfo();
  37331. }
  37332. return this;
  37333. };
  37334. /**
  37335. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  37336. * @param size the size (float) of the visibility box
  37337. * note : this doesn't lock the SPS mesh bounding box.
  37338. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37339. */
  37340. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  37341. var vis = size / 2;
  37342. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  37343. };
  37344. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  37345. // getter and setter
  37346. get: function () {
  37347. return this._alwaysVisible;
  37348. },
  37349. /**
  37350. * Sets the SPS as always visible or not
  37351. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37352. */
  37353. set: function (val) {
  37354. this._alwaysVisible = val;
  37355. this.mesh.alwaysSelectAsActiveMesh = val;
  37356. },
  37357. enumerable: true,
  37358. configurable: true
  37359. });
  37360. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  37361. get: function () {
  37362. return this._isVisibilityBoxLocked;
  37363. },
  37364. /**
  37365. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  37366. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  37367. */
  37368. set: function (val) {
  37369. this._isVisibilityBoxLocked = val;
  37370. this.mesh.getBoundingInfo().isLocked = val;
  37371. },
  37372. enumerable: true,
  37373. configurable: true
  37374. });
  37375. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  37376. // getters
  37377. get: function () {
  37378. return this._computeParticleRotation;
  37379. },
  37380. // Optimizer setters
  37381. /**
  37382. * Tells to `setParticles()` to compute the particle rotations or not.
  37383. * Default value : true. The SPS is faster when it's set to false.
  37384. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  37385. */
  37386. set: function (val) {
  37387. this._computeParticleRotation = val;
  37388. },
  37389. enumerable: true,
  37390. configurable: true
  37391. });
  37392. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  37393. get: function () {
  37394. return this._computeParticleColor;
  37395. },
  37396. /**
  37397. * Tells to `setParticles()` to compute the particle colors or not.
  37398. * Default value : true. The SPS is faster when it's set to false.
  37399. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  37400. */
  37401. set: function (val) {
  37402. this._computeParticleColor = val;
  37403. },
  37404. enumerable: true,
  37405. configurable: true
  37406. });
  37407. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  37408. get: function () {
  37409. return this._computeParticleTexture;
  37410. },
  37411. /**
  37412. * Tells to `setParticles()` to compute the particle textures or not.
  37413. * Default value : true. The SPS is faster when it's set to false.
  37414. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  37415. */
  37416. set: function (val) {
  37417. this._computeParticleTexture = val;
  37418. },
  37419. enumerable: true,
  37420. configurable: true
  37421. });
  37422. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  37423. get: function () {
  37424. return this._computeParticleVertex;
  37425. },
  37426. /**
  37427. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  37428. * Default value : false. The SPS is faster when it's set to false.
  37429. * Note : the particle custom vertex positions aren't stored values.
  37430. */
  37431. set: function (val) {
  37432. this._computeParticleVertex = val;
  37433. },
  37434. enumerable: true,
  37435. configurable: true
  37436. });
  37437. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  37438. get: function () {
  37439. return this._computeBoundingBox;
  37440. },
  37441. /**
  37442. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  37443. */
  37444. set: function (val) {
  37445. this._computeBoundingBox = val;
  37446. },
  37447. enumerable: true,
  37448. configurable: true
  37449. });
  37450. // =======================================================================
  37451. // Particle behavior logic
  37452. // these following methods may be overwritten by the user to fit his needs
  37453. /**
  37454. * This function does nothing. It may be overwritten to set all the particle first values.
  37455. * The SPS doesn't call this function, you may have to call it by your own.
  37456. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  37457. */
  37458. SolidParticleSystem.prototype.initParticles = function () {
  37459. };
  37460. /**
  37461. * This function does nothing. It may be overwritten to recycle a particle.
  37462. * The SPS doesn't call this function, you may have to call it by your own.
  37463. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  37464. */
  37465. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  37466. return particle;
  37467. };
  37468. /**
  37469. * Updates a particle : this function should be overwritten by the user.
  37470. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  37471. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  37472. * ex : just set a particle position or velocity and recycle conditions
  37473. */
  37474. SolidParticleSystem.prototype.updateParticle = function (particle) {
  37475. return particle;
  37476. };
  37477. /**
  37478. * Updates a vertex of a particle : it can be overwritten by the user.
  37479. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  37480. * @param particle the current particle
  37481. * @param vertex the current index of the current particle
  37482. * @param pt the index of the current vertex in the particle shape
  37483. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  37484. * ex : just set a vertex particle position
  37485. */
  37486. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  37487. return vertex;
  37488. };
  37489. /**
  37490. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  37491. * This does nothing and may be overwritten by the user.
  37492. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37493. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37494. * @param update the boolean update value actually passed to setParticles()
  37495. */
  37496. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  37497. };
  37498. /**
  37499. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  37500. * This will be passed three parameters.
  37501. * This does nothing and may be overwritten by the user.
  37502. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37503. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  37504. * @param update the boolean update value actually passed to setParticles()
  37505. */
  37506. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  37507. };
  37508. return SolidParticleSystem;
  37509. }());
  37510. BABYLON.SolidParticleSystem = SolidParticleSystem;
  37511. })(BABYLON || (BABYLON = {}));
  37512. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  37513. /// <reference path="babylon.mesh.ts" />
  37514. var BABYLON;
  37515. (function (BABYLON) {
  37516. var GroundMesh = (function (_super) {
  37517. __extends(GroundMesh, _super);
  37518. function GroundMesh(name, scene) {
  37519. var _this = _super.call(this, name, scene) || this;
  37520. _this.generateOctree = false;
  37521. _this._worldInverse = new BABYLON.Matrix();
  37522. return _this;
  37523. }
  37524. GroundMesh.prototype.getClassName = function () {
  37525. return "GroundMesh";
  37526. };
  37527. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  37528. get: function () {
  37529. return Math.min(this._subdivisionsX, this._subdivisionsY);
  37530. },
  37531. enumerable: true,
  37532. configurable: true
  37533. });
  37534. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  37535. get: function () {
  37536. return this._subdivisionsX;
  37537. },
  37538. enumerable: true,
  37539. configurable: true
  37540. });
  37541. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  37542. get: function () {
  37543. return this._subdivisionsY;
  37544. },
  37545. enumerable: true,
  37546. configurable: true
  37547. });
  37548. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  37549. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  37550. this._subdivisionsX = chunksCount;
  37551. this._subdivisionsY = chunksCount;
  37552. this.subdivide(chunksCount);
  37553. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  37554. };
  37555. /**
  37556. * Returns a height (y) value in the Worl system :
  37557. * the ground altitude at the coordinates (x, z) expressed in the World system.
  37558. * Returns the ground y position if (x, z) are outside the ground surface.
  37559. */
  37560. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  37561. var world = this.getWorldMatrix();
  37562. var invMat = BABYLON.Tmp.Matrix[5];
  37563. world.invertToRef(invMat);
  37564. var tmpVect = BABYLON.Tmp.Vector3[8];
  37565. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  37566. x = tmpVect.x;
  37567. z = tmpVect.z;
  37568. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37569. return this.position.y;
  37570. }
  37571. if (!this._heightQuads || this._heightQuads.length == 0) {
  37572. this._initHeightQuads();
  37573. this._computeHeightQuads();
  37574. }
  37575. var facet = this._getFacetAt(x, z);
  37576. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  37577. // return y in the World system
  37578. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  37579. return tmpVect.y;
  37580. };
  37581. /**
  37582. * Returns a normalized vector (Vector3) orthogonal to the ground
  37583. * at the ground coordinates (x, z) expressed in the World system.
  37584. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  37585. */
  37586. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  37587. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  37588. this.getNormalAtCoordinatesToRef(x, z, normal);
  37589. return normal;
  37590. };
  37591. /**
  37592. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  37593. * at the ground coordinates (x, z) expressed in the World system.
  37594. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  37595. * Returns the GroundMesh.
  37596. */
  37597. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  37598. var world = this.getWorldMatrix();
  37599. var tmpMat = BABYLON.Tmp.Matrix[5];
  37600. world.invertToRef(tmpMat);
  37601. var tmpVect = BABYLON.Tmp.Vector3[8];
  37602. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  37603. x = tmpVect.x;
  37604. z = tmpVect.z;
  37605. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37606. return this;
  37607. }
  37608. if (!this._heightQuads || this._heightQuads.length == 0) {
  37609. this._initHeightQuads();
  37610. this._computeHeightQuads();
  37611. }
  37612. var facet = this._getFacetAt(x, z);
  37613. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  37614. return this;
  37615. };
  37616. /**
  37617. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  37618. * if the ground has been updated.
  37619. * This can be used in the render loop.
  37620. * Returns the GroundMesh.
  37621. */
  37622. GroundMesh.prototype.updateCoordinateHeights = function () {
  37623. if (!this._heightQuads || this._heightQuads.length == 0) {
  37624. this._initHeightQuads();
  37625. }
  37626. this._computeHeightQuads();
  37627. return this;
  37628. };
  37629. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  37630. GroundMesh.prototype._getFacetAt = function (x, z) {
  37631. // retrieve col and row from x, z coordinates in the ground local system
  37632. var subdivisionsX = this._subdivisionsX;
  37633. var subdivisionsY = this._subdivisionsY;
  37634. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  37635. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  37636. var quad = this._heightQuads[row * this._subdivisionsX + col];
  37637. var facet;
  37638. if (z < quad.slope.x * x + quad.slope.y) {
  37639. facet = quad.facet1;
  37640. }
  37641. else {
  37642. facet = quad.facet2;
  37643. }
  37644. return facet;
  37645. };
  37646. // Creates and populates the heightMap array with "facet" elements :
  37647. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  37648. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37649. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37650. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37651. // Returns the GroundMesh.
  37652. GroundMesh.prototype._initHeightQuads = function () {
  37653. var subdivisionsX = this._subdivisionsX;
  37654. var subdivisionsY = this._subdivisionsY;
  37655. this._heightQuads = new Array();
  37656. for (var row = 0; row < subdivisionsY; row++) {
  37657. for (var col = 0; col < subdivisionsX; col++) {
  37658. 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) };
  37659. this._heightQuads[row * subdivisionsX + col] = quad;
  37660. }
  37661. }
  37662. return this;
  37663. };
  37664. // Compute each quad element values and update the the heightMap array :
  37665. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37666. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37667. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37668. // Returns the GroundMesh.
  37669. GroundMesh.prototype._computeHeightQuads = function () {
  37670. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37671. var v1 = BABYLON.Tmp.Vector3[3];
  37672. var v2 = BABYLON.Tmp.Vector3[2];
  37673. var v3 = BABYLON.Tmp.Vector3[1];
  37674. var v4 = BABYLON.Tmp.Vector3[0];
  37675. var v1v2 = BABYLON.Tmp.Vector3[4];
  37676. var v1v3 = BABYLON.Tmp.Vector3[5];
  37677. var v1v4 = BABYLON.Tmp.Vector3[6];
  37678. var norm1 = BABYLON.Tmp.Vector3[7];
  37679. var norm2 = BABYLON.Tmp.Vector3[8];
  37680. var i = 0;
  37681. var j = 0;
  37682. var k = 0;
  37683. var cd = 0; // 2D slope coefficient : z = cd * x + h
  37684. var h = 0;
  37685. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  37686. var d2 = 0;
  37687. var subdivisionsX = this._subdivisionsX;
  37688. var subdivisionsY = this._subdivisionsY;
  37689. for (var row = 0; row < subdivisionsY; row++) {
  37690. for (var col = 0; col < subdivisionsX; col++) {
  37691. i = col * 3;
  37692. j = row * (subdivisionsX + 1) * 3;
  37693. k = (row + 1) * (subdivisionsX + 1) * 3;
  37694. v1.x = positions[j + i];
  37695. v1.y = positions[j + i + 1];
  37696. v1.z = positions[j + i + 2];
  37697. v2.x = positions[j + i + 3];
  37698. v2.y = positions[j + i + 4];
  37699. v2.z = positions[j + i + 5];
  37700. v3.x = positions[k + i];
  37701. v3.y = positions[k + i + 1];
  37702. v3.z = positions[k + i + 2];
  37703. v4.x = positions[k + i + 3];
  37704. v4.y = positions[k + i + 4];
  37705. v4.z = positions[k + i + 5];
  37706. // 2D slope V1V4
  37707. cd = (v4.z - v1.z) / (v4.x - v1.x);
  37708. h = v1.z - cd * v1.x; // v1 belongs to the slope
  37709. // facet equations :
  37710. // we compute each facet normal vector
  37711. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  37712. // we compute the value d by applying the equation to v1 which belongs to the plane
  37713. // then we store the facet equation in a Vector4
  37714. v2.subtractToRef(v1, v1v2);
  37715. v3.subtractToRef(v1, v1v3);
  37716. v4.subtractToRef(v1, v1v4);
  37717. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  37718. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  37719. norm1.normalize();
  37720. norm2.normalize();
  37721. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  37722. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  37723. var quad = this._heightQuads[row * subdivisionsX + col];
  37724. quad.slope.copyFromFloats(cd, h);
  37725. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  37726. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  37727. }
  37728. }
  37729. return this;
  37730. };
  37731. GroundMesh.prototype.serialize = function (serializationObject) {
  37732. _super.prototype.serialize.call(this, serializationObject);
  37733. serializationObject.subdivisionsX = this._subdivisionsX;
  37734. serializationObject.subdivisionsY = this._subdivisionsY;
  37735. serializationObject.minX = this._minX;
  37736. serializationObject.maxX = this._maxX;
  37737. serializationObject.minZ = this._minZ;
  37738. serializationObject.maxZ = this._maxZ;
  37739. serializationObject.width = this._width;
  37740. serializationObject.height = this._height;
  37741. };
  37742. GroundMesh.Parse = function (parsedMesh, scene) {
  37743. var result = new GroundMesh(parsedMesh.name, scene);
  37744. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  37745. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  37746. result._minX = parsedMesh.minX;
  37747. result._maxX = parsedMesh.maxX;
  37748. result._minZ = parsedMesh.minZ;
  37749. result._maxZ = parsedMesh.maxZ;
  37750. result._width = parsedMesh.width;
  37751. result._height = parsedMesh.height;
  37752. return result;
  37753. };
  37754. return GroundMesh;
  37755. }(BABYLON.Mesh));
  37756. BABYLON.GroundMesh = GroundMesh;
  37757. })(BABYLON || (BABYLON = {}));
  37758. //# sourceMappingURL=babylon.groundMesh.js.map
  37759. var BABYLON;
  37760. (function (BABYLON) {
  37761. /**
  37762. * Creates an instance based on a source mesh.
  37763. */
  37764. var InstancedMesh = (function (_super) {
  37765. __extends(InstancedMesh, _super);
  37766. function InstancedMesh(name, source) {
  37767. var _this = _super.call(this, name, source.getScene()) || this;
  37768. source.instances.push(_this);
  37769. _this._sourceMesh = source;
  37770. _this.position.copyFrom(source.position);
  37771. _this.rotation.copyFrom(source.rotation);
  37772. _this.scaling.copyFrom(source.scaling);
  37773. if (source.rotationQuaternion) {
  37774. _this.rotationQuaternion = source.rotationQuaternion.clone();
  37775. }
  37776. _this.infiniteDistance = source.infiniteDistance;
  37777. _this.setPivotMatrix(source.getPivotMatrix());
  37778. _this.refreshBoundingInfo();
  37779. _this._syncSubMeshes();
  37780. return _this;
  37781. }
  37782. /**
  37783. * Returns the string "InstancedMesh".
  37784. */
  37785. InstancedMesh.prototype.getClassName = function () {
  37786. return "InstancedMesh";
  37787. };
  37788. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  37789. // Methods
  37790. get: function () {
  37791. return this._sourceMesh.receiveShadows;
  37792. },
  37793. enumerable: true,
  37794. configurable: true
  37795. });
  37796. Object.defineProperty(InstancedMesh.prototype, "material", {
  37797. get: function () {
  37798. return this._sourceMesh.material;
  37799. },
  37800. enumerable: true,
  37801. configurable: true
  37802. });
  37803. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  37804. get: function () {
  37805. return this._sourceMesh.visibility;
  37806. },
  37807. enumerable: true,
  37808. configurable: true
  37809. });
  37810. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  37811. get: function () {
  37812. return this._sourceMesh.skeleton;
  37813. },
  37814. enumerable: true,
  37815. configurable: true
  37816. });
  37817. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  37818. get: function () {
  37819. return this._sourceMesh.renderingGroupId;
  37820. },
  37821. enumerable: true,
  37822. configurable: true
  37823. });
  37824. /**
  37825. * Returns the total number of vertices (integer).
  37826. */
  37827. InstancedMesh.prototype.getTotalVertices = function () {
  37828. return this._sourceMesh.getTotalVertices();
  37829. };
  37830. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  37831. get: function () {
  37832. return this._sourceMesh;
  37833. },
  37834. enumerable: true,
  37835. configurable: true
  37836. });
  37837. /**
  37838. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  37839. */
  37840. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  37841. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  37842. };
  37843. /**
  37844. * Sets the vertex data of the mesh geometry for the requested `kind`.
  37845. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  37846. * The `data` are either a numeric array either a Float32Array.
  37847. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  37848. * 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).
  37849. * Note that a new underlying VertexBuffer object is created each call.
  37850. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  37851. *
  37852. * Possible `kind` values :
  37853. * - BABYLON.VertexBuffer.PositionKind
  37854. * - BABYLON.VertexBuffer.UVKind
  37855. * - BABYLON.VertexBuffer.UV2Kind
  37856. * - BABYLON.VertexBuffer.UV3Kind
  37857. * - BABYLON.VertexBuffer.UV4Kind
  37858. * - BABYLON.VertexBuffer.UV5Kind
  37859. * - BABYLON.VertexBuffer.UV6Kind
  37860. * - BABYLON.VertexBuffer.ColorKind
  37861. * - BABYLON.VertexBuffer.MatricesIndicesKind
  37862. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  37863. * - BABYLON.VertexBuffer.MatricesWeightsKind
  37864. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  37865. *
  37866. * Returns the Mesh.
  37867. */
  37868. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  37869. if (this.sourceMesh) {
  37870. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  37871. }
  37872. return this.sourceMesh;
  37873. };
  37874. /**
  37875. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  37876. * If the mesh has no geometry, it is simply returned as it is.
  37877. * The `data` are either a numeric array either a Float32Array.
  37878. * No new underlying VertexBuffer object is created.
  37879. * 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.
  37880. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  37881. *
  37882. * Possible `kind` values :
  37883. * - BABYLON.VertexBuffer.PositionKind
  37884. * - BABYLON.VertexBuffer.UVKind
  37885. * - BABYLON.VertexBuffer.UV2Kind
  37886. * - BABYLON.VertexBuffer.UV3Kind
  37887. * - BABYLON.VertexBuffer.UV4Kind
  37888. * - BABYLON.VertexBuffer.UV5Kind
  37889. * - BABYLON.VertexBuffer.UV6Kind
  37890. * - BABYLON.VertexBuffer.ColorKind
  37891. * - BABYLON.VertexBuffer.MatricesIndicesKind
  37892. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  37893. * - BABYLON.VertexBuffer.MatricesWeightsKind
  37894. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  37895. *
  37896. * Returns the Mesh.
  37897. */
  37898. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  37899. if (this.sourceMesh) {
  37900. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  37901. }
  37902. return this.sourceMesh;
  37903. };
  37904. /**
  37905. * Sets the mesh indices.
  37906. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  37907. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  37908. * This method creates a new index buffer each call.
  37909. * Returns the Mesh.
  37910. */
  37911. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  37912. if (this.sourceMesh) {
  37913. this.sourceMesh.setIndices(indices, totalVertices);
  37914. }
  37915. return this.sourceMesh;
  37916. };
  37917. /**
  37918. * Boolean : True if the mesh owns the requested kind of data.
  37919. */
  37920. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  37921. return this._sourceMesh.isVerticesDataPresent(kind);
  37922. };
  37923. /**
  37924. * Returns an array of indices (IndicesArray).
  37925. */
  37926. InstancedMesh.prototype.getIndices = function () {
  37927. return this._sourceMesh.getIndices();
  37928. };
  37929. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  37930. get: function () {
  37931. return this._sourceMesh._positions;
  37932. },
  37933. enumerable: true,
  37934. configurable: true
  37935. });
  37936. /**
  37937. * Sets a new updated BoundingInfo to the mesh.
  37938. * Returns the mesh.
  37939. */
  37940. InstancedMesh.prototype.refreshBoundingInfo = function () {
  37941. var meshBB = this._sourceMesh.getBoundingInfo();
  37942. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  37943. this._updateBoundingInfo();
  37944. return this;
  37945. };
  37946. InstancedMesh.prototype._preActivate = function () {
  37947. if (this._currentLOD) {
  37948. this._currentLOD._preActivate();
  37949. }
  37950. return this;
  37951. };
  37952. InstancedMesh.prototype._activate = function (renderId) {
  37953. if (this._currentLOD) {
  37954. this._currentLOD._registerInstanceForRenderId(this, renderId);
  37955. }
  37956. return this;
  37957. };
  37958. /**
  37959. * Returns the current associated LOD AbstractMesh.
  37960. */
  37961. InstancedMesh.prototype.getLOD = function (camera) {
  37962. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  37963. if (this._currentLOD === this.sourceMesh) {
  37964. return this;
  37965. }
  37966. return this._currentLOD;
  37967. };
  37968. InstancedMesh.prototype._syncSubMeshes = function () {
  37969. this.releaseSubMeshes();
  37970. if (this._sourceMesh.subMeshes) {
  37971. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  37972. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  37973. }
  37974. }
  37975. return this;
  37976. };
  37977. InstancedMesh.prototype._generatePointsArray = function () {
  37978. return this._sourceMesh._generatePointsArray();
  37979. };
  37980. /**
  37981. * Creates a new InstancedMesh from the current mesh.
  37982. * - name (string) : the cloned mesh name
  37983. * - newParent (optional Node) : the optional Node to parent the clone to.
  37984. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  37985. *
  37986. * Returns the clone.
  37987. */
  37988. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  37989. var result = this._sourceMesh.createInstance(name);
  37990. // Deep copy
  37991. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  37992. // Bounding info
  37993. this.refreshBoundingInfo();
  37994. // Parent
  37995. if (newParent) {
  37996. result.parent = newParent;
  37997. }
  37998. if (!doNotCloneChildren) {
  37999. // Children
  38000. for (var index = 0; index < this.getScene().meshes.length; index++) {
  38001. var mesh = this.getScene().meshes[index];
  38002. if (mesh.parent === this) {
  38003. mesh.clone(mesh.name, result);
  38004. }
  38005. }
  38006. }
  38007. result.computeWorldMatrix(true);
  38008. return result;
  38009. };
  38010. /**
  38011. * Disposes the InstancedMesh.
  38012. * Returns nothing.
  38013. */
  38014. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  38015. // Remove from mesh
  38016. var index = this._sourceMesh.instances.indexOf(this);
  38017. this._sourceMesh.instances.splice(index, 1);
  38018. _super.prototype.dispose.call(this, doNotRecurse);
  38019. };
  38020. return InstancedMesh;
  38021. }(BABYLON.AbstractMesh));
  38022. BABYLON.InstancedMesh = InstancedMesh;
  38023. })(BABYLON || (BABYLON = {}));
  38024. //# sourceMappingURL=babylon.instancedMesh.js.map
  38025. /// <reference path="babylon.mesh.ts" />
  38026. var BABYLON;
  38027. (function (BABYLON) {
  38028. var LinesMesh = (function (_super) {
  38029. __extends(LinesMesh, _super);
  38030. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  38031. if (parent === void 0) { parent = null; }
  38032. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  38033. _this.useVertexColor = useVertexColor;
  38034. _this.color = new BABYLON.Color3(1, 1, 1);
  38035. _this.alpha = 1;
  38036. if (source) {
  38037. _this.color = source.color.clone();
  38038. _this.alpha = source.alpha;
  38039. _this.useVertexColor = source.useVertexColor;
  38040. }
  38041. _this._intersectionThreshold = 0.1;
  38042. var options = {
  38043. attributes: [BABYLON.VertexBuffer.PositionKind],
  38044. uniforms: ["world", "viewProjection"],
  38045. needAlphaBlending: false,
  38046. };
  38047. if (!useVertexColor) {
  38048. options.uniforms.push("color");
  38049. options.needAlphaBlending = true;
  38050. }
  38051. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  38052. return _this;
  38053. }
  38054. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  38055. /**
  38056. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38057. * This margin is expressed in world space coordinates, so its value may vary.
  38058. * Default value is 0.1
  38059. * @returns the intersection Threshold value.
  38060. */
  38061. get: function () {
  38062. return this._intersectionThreshold;
  38063. },
  38064. /**
  38065. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38066. * This margin is expressed in world space coordinates, so its value may vary.
  38067. * @param value the new threshold to apply
  38068. */
  38069. set: function (value) {
  38070. if (this._intersectionThreshold === value) {
  38071. return;
  38072. }
  38073. this._intersectionThreshold = value;
  38074. if (this.geometry) {
  38075. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  38076. }
  38077. },
  38078. enumerable: true,
  38079. configurable: true
  38080. });
  38081. /**
  38082. * Returns the string "LineMesh"
  38083. */
  38084. LinesMesh.prototype.getClassName = function () {
  38085. return "LinesMesh";
  38086. };
  38087. Object.defineProperty(LinesMesh.prototype, "material", {
  38088. get: function () {
  38089. return this._colorShader;
  38090. },
  38091. enumerable: true,
  38092. configurable: true
  38093. });
  38094. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  38095. get: function () {
  38096. return false;
  38097. },
  38098. enumerable: true,
  38099. configurable: true
  38100. });
  38101. LinesMesh.prototype.createInstance = function (name) {
  38102. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  38103. return null;
  38104. };
  38105. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  38106. // VBOs
  38107. this._geometry._bind(this._colorShader.getEffect());
  38108. // Color
  38109. if (!this.useVertexColor) {
  38110. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  38111. }
  38112. return this;
  38113. };
  38114. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  38115. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  38116. return this;
  38117. }
  38118. var engine = this.getScene().getEngine();
  38119. // Draw order
  38120. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  38121. return this;
  38122. };
  38123. LinesMesh.prototype.dispose = function (doNotRecurse) {
  38124. this._colorShader.dispose();
  38125. _super.prototype.dispose.call(this, doNotRecurse);
  38126. };
  38127. /**
  38128. * Returns a new LineMesh object cloned from the current one.
  38129. */
  38130. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  38131. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  38132. };
  38133. return LinesMesh;
  38134. }(BABYLON.Mesh));
  38135. BABYLON.LinesMesh = LinesMesh;
  38136. })(BABYLON || (BABYLON = {}));
  38137. //# sourceMappingURL=babylon.linesMesh.js.map
  38138. var BABYLON;
  38139. (function (BABYLON) {
  38140. var ShaderMaterial = (function (_super) {
  38141. __extends(ShaderMaterial, _super);
  38142. function ShaderMaterial(name, scene, shaderPath, options) {
  38143. var _this = _super.call(this, name, scene) || this;
  38144. _this._textures = {};
  38145. _this._textureArrays = {};
  38146. _this._floats = {};
  38147. _this._floatsArrays = {};
  38148. _this._colors3 = {};
  38149. _this._colors4 = {};
  38150. _this._vectors2 = {};
  38151. _this._vectors3 = {};
  38152. _this._vectors4 = {};
  38153. _this._matrices = {};
  38154. _this._matrices3x3 = {};
  38155. _this._matrices2x2 = {};
  38156. _this._vectors3Arrays = {};
  38157. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  38158. _this._shaderPath = shaderPath;
  38159. options.needAlphaBlending = options.needAlphaBlending || false;
  38160. options.needAlphaTesting = options.needAlphaTesting || false;
  38161. options.attributes = options.attributes || ["position", "normal", "uv"];
  38162. options.uniforms = options.uniforms || ["worldViewProjection"];
  38163. options.uniformBuffers = options.uniformBuffers || [];
  38164. options.samplers = options.samplers || [];
  38165. options.defines = options.defines || [];
  38166. _this._options = options;
  38167. return _this;
  38168. }
  38169. ShaderMaterial.prototype.getClassName = function () {
  38170. return "ShaderMaterial";
  38171. };
  38172. ShaderMaterial.prototype.needAlphaBlending = function () {
  38173. return this._options.needAlphaBlending;
  38174. };
  38175. ShaderMaterial.prototype.needAlphaTesting = function () {
  38176. return this._options.needAlphaTesting;
  38177. };
  38178. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  38179. if (this._options.uniforms.indexOf(uniformName) === -1) {
  38180. this._options.uniforms.push(uniformName);
  38181. }
  38182. };
  38183. ShaderMaterial.prototype.setTexture = function (name, texture) {
  38184. if (this._options.samplers.indexOf(name) === -1) {
  38185. this._options.samplers.push(name);
  38186. }
  38187. this._textures[name] = texture;
  38188. return this;
  38189. };
  38190. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  38191. if (this._options.samplers.indexOf(name) === -1) {
  38192. this._options.samplers.push(name);
  38193. }
  38194. this._checkUniform(name);
  38195. this._textureArrays[name] = textures;
  38196. return this;
  38197. };
  38198. ShaderMaterial.prototype.setFloat = function (name, value) {
  38199. this._checkUniform(name);
  38200. this._floats[name] = value;
  38201. return this;
  38202. };
  38203. ShaderMaterial.prototype.setFloats = function (name, value) {
  38204. this._checkUniform(name);
  38205. this._floatsArrays[name] = value;
  38206. return this;
  38207. };
  38208. ShaderMaterial.prototype.setColor3 = function (name, value) {
  38209. this._checkUniform(name);
  38210. this._colors3[name] = value;
  38211. return this;
  38212. };
  38213. ShaderMaterial.prototype.setColor4 = function (name, value) {
  38214. this._checkUniform(name);
  38215. this._colors4[name] = value;
  38216. return this;
  38217. };
  38218. ShaderMaterial.prototype.setVector2 = function (name, value) {
  38219. this._checkUniform(name);
  38220. this._vectors2[name] = value;
  38221. return this;
  38222. };
  38223. ShaderMaterial.prototype.setVector3 = function (name, value) {
  38224. this._checkUniform(name);
  38225. this._vectors3[name] = value;
  38226. return this;
  38227. };
  38228. ShaderMaterial.prototype.setVector4 = function (name, value) {
  38229. this._checkUniform(name);
  38230. this._vectors4[name] = value;
  38231. return this;
  38232. };
  38233. ShaderMaterial.prototype.setMatrix = function (name, value) {
  38234. this._checkUniform(name);
  38235. this._matrices[name] = value;
  38236. return this;
  38237. };
  38238. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  38239. this._checkUniform(name);
  38240. this._matrices3x3[name] = value;
  38241. return this;
  38242. };
  38243. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  38244. this._checkUniform(name);
  38245. this._matrices2x2[name] = value;
  38246. return this;
  38247. };
  38248. ShaderMaterial.prototype.setArray3 = function (name, value) {
  38249. this._checkUniform(name);
  38250. this._vectors3Arrays[name] = value;
  38251. return this;
  38252. };
  38253. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  38254. if (!mesh) {
  38255. return true;
  38256. }
  38257. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  38258. return false;
  38259. }
  38260. return false;
  38261. };
  38262. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  38263. var scene = this.getScene();
  38264. var engine = scene.getEngine();
  38265. if (!this.checkReadyOnEveryCall) {
  38266. if (this._renderId === scene.getRenderId()) {
  38267. if (this._checkCache(scene, mesh, useInstances)) {
  38268. return true;
  38269. }
  38270. }
  38271. }
  38272. // Instances
  38273. var defines = [];
  38274. var attribs = [];
  38275. var fallbacks = new BABYLON.EffectFallbacks();
  38276. if (useInstances) {
  38277. defines.push("#define INSTANCES");
  38278. }
  38279. for (var index = 0; index < this._options.defines.length; index++) {
  38280. defines.push(this._options.defines[index]);
  38281. }
  38282. for (var index = 0; index < this._options.attributes.length; index++) {
  38283. attribs.push(this._options.attributes[index]);
  38284. }
  38285. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38286. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38287. defines.push("#define VERTEXCOLOR");
  38288. }
  38289. // Bones
  38290. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  38291. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38292. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38293. if (mesh.numBoneInfluencers > 4) {
  38294. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38295. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38296. }
  38297. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38298. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38299. fallbacks.addCPUSkinningFallback(0, mesh);
  38300. }
  38301. else {
  38302. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38303. }
  38304. // Textures
  38305. for (var name in this._textures) {
  38306. if (!this._textures[name].isReady()) {
  38307. return false;
  38308. }
  38309. }
  38310. // Alpha test
  38311. if (engine.getAlphaTesting()) {
  38312. defines.push("#define ALPHATEST");
  38313. }
  38314. var previousEffect = this._effect;
  38315. var join = defines.join("\n");
  38316. this._effect = engine.createEffect(this._shaderPath, {
  38317. attributes: attribs,
  38318. uniformsNames: this._options.uniforms,
  38319. uniformBuffersNames: this._options.uniformBuffers,
  38320. samplers: this._options.samplers,
  38321. defines: join,
  38322. fallbacks: fallbacks,
  38323. onCompiled: this.onCompiled,
  38324. onError: this.onError
  38325. }, engine);
  38326. if (!this._effect.isReady()) {
  38327. return false;
  38328. }
  38329. if (previousEffect !== this._effect) {
  38330. scene.resetCachedMaterial();
  38331. }
  38332. this._renderId = scene.getRenderId();
  38333. return true;
  38334. };
  38335. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38336. var scene = this.getScene();
  38337. if (this._options.uniforms.indexOf("world") !== -1) {
  38338. this._effect.setMatrix("world", world);
  38339. }
  38340. if (this._options.uniforms.indexOf("worldView") !== -1) {
  38341. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  38342. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  38343. }
  38344. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  38345. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  38346. }
  38347. };
  38348. ShaderMaterial.prototype.bind = function (world, mesh) {
  38349. // Std values
  38350. this.bindOnlyWorldMatrix(world);
  38351. if (this.getScene().getCachedMaterial() !== this) {
  38352. if (this._options.uniforms.indexOf("view") !== -1) {
  38353. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  38354. }
  38355. if (this._options.uniforms.indexOf("projection") !== -1) {
  38356. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  38357. }
  38358. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  38359. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  38360. }
  38361. // Bones
  38362. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  38363. var name;
  38364. // Texture
  38365. for (name in this._textures) {
  38366. this._effect.setTexture(name, this._textures[name]);
  38367. }
  38368. // Texture arrays
  38369. for (name in this._textureArrays) {
  38370. this._effect.setTextureArray(name, this._textureArrays[name]);
  38371. }
  38372. // Float
  38373. for (name in this._floats) {
  38374. this._effect.setFloat(name, this._floats[name]);
  38375. }
  38376. // Float s
  38377. for (name in this._floatsArrays) {
  38378. this._effect.setArray(name, this._floatsArrays[name]);
  38379. }
  38380. // Color3
  38381. for (name in this._colors3) {
  38382. this._effect.setColor3(name, this._colors3[name]);
  38383. }
  38384. // Color4
  38385. for (name in this._colors4) {
  38386. var color = this._colors4[name];
  38387. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  38388. }
  38389. // Vector2
  38390. for (name in this._vectors2) {
  38391. this._effect.setVector2(name, this._vectors2[name]);
  38392. }
  38393. // Vector3
  38394. for (name in this._vectors3) {
  38395. this._effect.setVector3(name, this._vectors3[name]);
  38396. }
  38397. // Vector4
  38398. for (name in this._vectors4) {
  38399. this._effect.setVector4(name, this._vectors4[name]);
  38400. }
  38401. // Matrix
  38402. for (name in this._matrices) {
  38403. this._effect.setMatrix(name, this._matrices[name]);
  38404. }
  38405. // Matrix 3x3
  38406. for (name in this._matrices3x3) {
  38407. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  38408. }
  38409. // Matrix 2x2
  38410. for (name in this._matrices2x2) {
  38411. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  38412. }
  38413. // Vector3Array
  38414. for (name in this._vectors3Arrays) {
  38415. this._effect.setArray3(name, this._vectors3Arrays[name]);
  38416. }
  38417. }
  38418. this._afterBind(mesh);
  38419. };
  38420. ShaderMaterial.prototype.clone = function (name) {
  38421. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  38422. return newShaderMaterial;
  38423. };
  38424. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  38425. if (forceDisposeTextures) {
  38426. var name;
  38427. for (name in this._textures) {
  38428. this._textures[name].dispose();
  38429. }
  38430. for (name in this._textureArrays) {
  38431. var array = this._textureArrays[name];
  38432. for (var index = 0; index < array.length; index++) {
  38433. array[index].dispose();
  38434. }
  38435. }
  38436. }
  38437. this._textures = {};
  38438. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  38439. };
  38440. ShaderMaterial.prototype.serialize = function () {
  38441. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38442. serializationObject.customType = "BABYLON.ShaderMaterial";
  38443. serializationObject.options = this._options;
  38444. serializationObject.shaderPath = this._shaderPath;
  38445. var name;
  38446. // Texture
  38447. serializationObject.textures = {};
  38448. for (name in this._textures) {
  38449. serializationObject.textures[name] = this._textures[name].serialize();
  38450. }
  38451. // Texture arrays
  38452. serializationObject.textureArrays = {};
  38453. for (name in this._textureArrays) {
  38454. serializationObject.textureArrays[name] = [];
  38455. var array = this._textureArrays[name];
  38456. for (var index = 0; index < array.length; index++) {
  38457. serializationObject.textureArrays[name].push(array[index].serialize());
  38458. }
  38459. }
  38460. // Float
  38461. serializationObject.floats = {};
  38462. for (name in this._floats) {
  38463. serializationObject.floats[name] = this._floats[name];
  38464. }
  38465. // Float s
  38466. serializationObject.floatArrays = {};
  38467. for (name in this._floatsArrays) {
  38468. serializationObject.floatArrays[name] = this._floatsArrays[name];
  38469. }
  38470. // Color3
  38471. serializationObject.colors3 = {};
  38472. for (name in this._colors3) {
  38473. serializationObject.colors3[name] = this._colors3[name].asArray();
  38474. }
  38475. // Color4
  38476. serializationObject.colors4 = {};
  38477. for (name in this._colors4) {
  38478. serializationObject.colors4[name] = this._colors4[name].asArray();
  38479. }
  38480. // Vector2
  38481. serializationObject.vectors2 = {};
  38482. for (name in this._vectors2) {
  38483. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  38484. }
  38485. // Vector3
  38486. serializationObject.vectors3 = {};
  38487. for (name in this._vectors3) {
  38488. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  38489. }
  38490. // Vector4
  38491. serializationObject.vectors4 = {};
  38492. for (name in this._vectors4) {
  38493. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  38494. }
  38495. // Matrix
  38496. serializationObject.matrices = {};
  38497. for (name in this._matrices) {
  38498. serializationObject.matrices[name] = this._matrices[name].asArray();
  38499. }
  38500. // Matrix 3x3
  38501. serializationObject.matrices3x3 = {};
  38502. for (name in this._matrices3x3) {
  38503. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  38504. }
  38505. // Matrix 2x2
  38506. serializationObject.matrices2x2 = {};
  38507. for (name in this._matrices2x2) {
  38508. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  38509. }
  38510. // Vector3Array
  38511. serializationObject.vectors3Arrays = {};
  38512. for (name in this._vectors3Arrays) {
  38513. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  38514. }
  38515. return serializationObject;
  38516. };
  38517. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  38518. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  38519. var name;
  38520. // Texture
  38521. for (name in source.textures) {
  38522. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  38523. }
  38524. // Texture arrays
  38525. for (name in source.textureArrays) {
  38526. var array = source.textureArrays[name];
  38527. var textureArray = new Array();
  38528. for (var index = 0; index < array.length; index++) {
  38529. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  38530. }
  38531. material.setTextureArray(name, textureArray);
  38532. }
  38533. // Float
  38534. for (name in source.floats) {
  38535. material.setFloat(name, source.floats[name]);
  38536. }
  38537. // Float s
  38538. for (name in source.floatsArrays) {
  38539. material.setFloats(name, source.floatsArrays[name]);
  38540. }
  38541. // Color3
  38542. for (name in source.colors3) {
  38543. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  38544. }
  38545. // Color4
  38546. for (name in source.colors4) {
  38547. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  38548. }
  38549. // Vector2
  38550. for (name in source.vectors2) {
  38551. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  38552. }
  38553. // Vector3
  38554. for (name in source.vectors3) {
  38555. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  38556. }
  38557. // Vector4
  38558. for (name in source.vectors4) {
  38559. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  38560. }
  38561. // Matrix
  38562. for (name in source.matrices) {
  38563. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  38564. }
  38565. // Matrix 3x3
  38566. for (name in source.matrices3x3) {
  38567. material.setMatrix3x3(name, source.matrices3x3[name]);
  38568. }
  38569. // Matrix 2x2
  38570. for (name in source.matrices2x2) {
  38571. material.setMatrix2x2(name, source.matrices2x2[name]);
  38572. }
  38573. // Vector3Array
  38574. for (name in source.vectors3Arrays) {
  38575. material.setArray3(name, source.vectors3Arrays[name]);
  38576. }
  38577. return material;
  38578. };
  38579. return ShaderMaterial;
  38580. }(BABYLON.Material));
  38581. BABYLON.ShaderMaterial = ShaderMaterial;
  38582. })(BABYLON || (BABYLON = {}));
  38583. //# sourceMappingURL=babylon.shaderMaterial.js.map
  38584. var BABYLON;
  38585. (function (BABYLON) {
  38586. var MeshBuilder = (function () {
  38587. function MeshBuilder() {
  38588. }
  38589. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  38590. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  38591. return BABYLON.Mesh.DOUBLESIDE;
  38592. }
  38593. if (orientation === undefined || orientation === null) {
  38594. return BABYLON.Mesh.FRONTSIDE;
  38595. }
  38596. return orientation;
  38597. };
  38598. /**
  38599. * Creates a box mesh.
  38600. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  38601. * The parameter `size` sets the size (float) of each box side (default 1).
  38602. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  38603. * 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).
  38604. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  38605. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38606. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38607. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38608. */
  38609. MeshBuilder.CreateBox = function (name, options, scene) {
  38610. var box = new BABYLON.Mesh(name, scene);
  38611. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38612. box.sideOrientation = options.sideOrientation;
  38613. var vertexData = BABYLON.VertexData.CreateBox(options);
  38614. vertexData.applyToMesh(box, options.updatable);
  38615. return box;
  38616. };
  38617. /**
  38618. * Creates a sphere mesh.
  38619. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  38620. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  38621. * 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`).
  38622. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  38623. * 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
  38624. * 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).
  38625. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38626. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38627. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38628. */
  38629. MeshBuilder.CreateSphere = function (name, options, scene) {
  38630. var sphere = new BABYLON.Mesh(name, scene);
  38631. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38632. sphere.sideOrientation = options.sideOrientation;
  38633. var vertexData = BABYLON.VertexData.CreateSphere(options);
  38634. vertexData.applyToMesh(sphere, options.updatable);
  38635. return sphere;
  38636. };
  38637. /**
  38638. * Creates a plane polygonal mesh. By default, this is a disc.
  38639. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  38640. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  38641. * 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.
  38642. * 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
  38643. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38644. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38645. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38646. */
  38647. MeshBuilder.CreateDisc = function (name, options, scene) {
  38648. var disc = new BABYLON.Mesh(name, scene);
  38649. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38650. disc.sideOrientation = options.sideOrientation;
  38651. var vertexData = BABYLON.VertexData.CreateDisc(options);
  38652. vertexData.applyToMesh(disc, options.updatable);
  38653. return disc;
  38654. };
  38655. /**
  38656. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  38657. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  38658. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  38659. * 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`).
  38660. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  38661. * 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.
  38662. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38663. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38664. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38665. */
  38666. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  38667. var sphere = new BABYLON.Mesh(name, scene);
  38668. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38669. sphere.sideOrientation = options.sideOrientation;
  38670. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  38671. vertexData.applyToMesh(sphere, options.updatable);
  38672. return sphere;
  38673. };
  38674. ;
  38675. /**
  38676. * Creates a ribbon mesh.
  38677. * 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.
  38678. *
  38679. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  38680. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  38681. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  38682. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  38683. * 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.
  38684. * 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.
  38685. * 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
  38686. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38687. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38688. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  38689. * 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.
  38690. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  38691. * 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
  38692. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  38693. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  38694. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38695. */
  38696. MeshBuilder.CreateRibbon = function (name, options, scene) {
  38697. var pathArray = options.pathArray;
  38698. var closeArray = options.closeArray;
  38699. var closePath = options.closePath;
  38700. var offset = options.offset;
  38701. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38702. var instance = options.instance;
  38703. var updatable = options.updatable;
  38704. if (instance) {
  38705. // positionFunction : ribbon case
  38706. // only pathArray and sideOrientation parameters are taken into account for positions update
  38707. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  38708. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  38709. var positionFunction = function (positions) {
  38710. var minlg = pathArray[0].length;
  38711. var i = 0;
  38712. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  38713. for (var si = 1; si <= ns; si++) {
  38714. for (var p = 0; p < pathArray.length; p++) {
  38715. var path = pathArray[p];
  38716. var l = path.length;
  38717. minlg = (minlg < l) ? minlg : l;
  38718. var j = 0;
  38719. while (j < minlg) {
  38720. positions[i] = path[j].x;
  38721. positions[i + 1] = path[j].y;
  38722. positions[i + 2] = path[j].z;
  38723. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  38724. BABYLON.Tmp.Vector3[0].x = path[j].x;
  38725. }
  38726. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  38727. BABYLON.Tmp.Vector3[1].x = path[j].x;
  38728. }
  38729. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  38730. BABYLON.Tmp.Vector3[0].y = path[j].y;
  38731. }
  38732. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  38733. BABYLON.Tmp.Vector3[1].y = path[j].y;
  38734. }
  38735. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  38736. BABYLON.Tmp.Vector3[0].z = path[j].z;
  38737. }
  38738. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  38739. BABYLON.Tmp.Vector3[1].z = path[j].z;
  38740. }
  38741. j++;
  38742. i += 3;
  38743. }
  38744. if (instance._closePath) {
  38745. positions[i] = path[0].x;
  38746. positions[i + 1] = path[0].y;
  38747. positions[i + 2] = path[0].z;
  38748. i += 3;
  38749. }
  38750. }
  38751. }
  38752. };
  38753. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38754. positionFunction(positions);
  38755. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  38756. instance._boundingInfo.update(instance._worldMatrix);
  38757. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  38758. if (options.colors) {
  38759. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  38760. for (var c = 0; c < options.colors.length; c++) {
  38761. colors[c * 4] = options.colors[c].r;
  38762. colors[c * 4 + 1] = options.colors[c].g;
  38763. colors[c * 4 + 2] = options.colors[c].b;
  38764. colors[c * 4 + 3] = options.colors[c].a;
  38765. }
  38766. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  38767. }
  38768. if (options.uvs) {
  38769. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38770. for (var i = 0; i < options.uvs.length; i++) {
  38771. uvs[i * 2] = options.uvs[i].x;
  38772. uvs[i * 2 + 1] = options.uvs[i].y;
  38773. }
  38774. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  38775. }
  38776. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  38777. var indices = instance.getIndices();
  38778. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38779. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  38780. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  38781. if (instance._closePath) {
  38782. var indexFirst = 0;
  38783. var indexLast = 0;
  38784. for (var p = 0; p < pathArray.length; p++) {
  38785. indexFirst = instance._idx[p] * 3;
  38786. if (p + 1 < pathArray.length) {
  38787. indexLast = (instance._idx[p + 1] - 1) * 3;
  38788. }
  38789. else {
  38790. indexLast = normals.length - 3;
  38791. }
  38792. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38793. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38794. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38795. normals[indexLast] = normals[indexFirst];
  38796. normals[indexLast + 1] = normals[indexFirst + 1];
  38797. normals[indexLast + 2] = normals[indexFirst + 2];
  38798. }
  38799. }
  38800. if (!(instance.areNormalsFrozen)) {
  38801. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  38802. }
  38803. }
  38804. return instance;
  38805. }
  38806. else {
  38807. var ribbon = new BABYLON.Mesh(name, scene);
  38808. ribbon.sideOrientation = sideOrientation;
  38809. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  38810. if (closePath) {
  38811. ribbon._idx = vertexData._idx;
  38812. }
  38813. ribbon._closePath = closePath;
  38814. ribbon._closeArray = closeArray;
  38815. vertexData.applyToMesh(ribbon, updatable);
  38816. return ribbon;
  38817. }
  38818. };
  38819. /**
  38820. * Creates a cylinder or a cone mesh.
  38821. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  38822. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  38823. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  38824. * 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.
  38825. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  38826. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  38827. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  38828. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  38829. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  38830. * 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).
  38831. * 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
  38832. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  38833. * 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
  38834. * 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.
  38835. * If `enclose` is false, a ring surface is one element.
  38836. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  38837. * 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
  38838. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38839. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38840. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38841. */
  38842. MeshBuilder.CreateCylinder = function (name, options, scene) {
  38843. var cylinder = new BABYLON.Mesh(name, scene);
  38844. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38845. cylinder.sideOrientation = options.sideOrientation;
  38846. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  38847. vertexData.applyToMesh(cylinder, options.updatable);
  38848. return cylinder;
  38849. };
  38850. /**
  38851. * Creates a torus mesh.
  38852. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  38853. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  38854. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  38855. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  38856. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38857. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38858. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38859. */
  38860. MeshBuilder.CreateTorus = function (name, options, scene) {
  38861. var torus = new BABYLON.Mesh(name, scene);
  38862. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38863. torus.sideOrientation = options.sideOrientation;
  38864. var vertexData = BABYLON.VertexData.CreateTorus(options);
  38865. vertexData.applyToMesh(torus, options.updatable);
  38866. return torus;
  38867. };
  38868. /**
  38869. * Creates a torus knot mesh.
  38870. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  38871. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  38872. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  38873. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  38874. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  38875. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38876. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  38877. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38878. */
  38879. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  38880. var torusKnot = new BABYLON.Mesh(name, scene);
  38881. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  38882. torusKnot.sideOrientation = options.sideOrientation;
  38883. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  38884. vertexData.applyToMesh(torusKnot, options.updatable);
  38885. return torusKnot;
  38886. };
  38887. /**
  38888. * Creates a line system mesh.
  38889. * A line system is a pool of many lines gathered in a single mesh.
  38890. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  38891. * 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.
  38892. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  38893. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  38894. * 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
  38895. * 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
  38896. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  38897. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38898. */
  38899. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  38900. var instance = options.instance;
  38901. var lines = options.lines;
  38902. if (instance) {
  38903. var positionFunction = function (positions) {
  38904. var i = 0;
  38905. for (var l = 0; l < lines.length; l++) {
  38906. var points = lines[l];
  38907. for (var p = 0; p < points.length; p++) {
  38908. positions[i] = points[p].x;
  38909. positions[i + 1] = points[p].y;
  38910. positions[i + 2] = points[p].z;
  38911. i += 3;
  38912. }
  38913. }
  38914. };
  38915. instance.updateMeshPositions(positionFunction, false);
  38916. return instance;
  38917. }
  38918. // line system creation
  38919. var lineSystem = new BABYLON.LinesMesh(name, scene);
  38920. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  38921. vertexData.applyToMesh(lineSystem, options.updatable);
  38922. return lineSystem;
  38923. };
  38924. /**
  38925. * Creates a line mesh.
  38926. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  38927. * 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.
  38928. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  38929. * The parameter `points` is an array successive Vector3.
  38930. * 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
  38931. * When updating an instance, remember that only point positions can change, not the number of points.
  38932. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38933. */
  38934. MeshBuilder.CreateLines = function (name, options, scene) {
  38935. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  38936. return lines;
  38937. };
  38938. /**
  38939. * Creates a dashed line mesh.
  38940. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  38941. * 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.
  38942. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  38943. * The parameter `points` is an array successive Vector3.
  38944. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  38945. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  38946. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  38947. * 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
  38948. * When updating an instance, remember that only point positions can change, not the number of points.
  38949. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  38950. */
  38951. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  38952. var points = options.points;
  38953. var instance = options.instance;
  38954. var gapSize = options.gapSize;
  38955. var dashNb = options.dashNb;
  38956. var dashSize = options.dashSize;
  38957. if (instance) {
  38958. var positionFunction = function (positions) {
  38959. var curvect = BABYLON.Vector3.Zero();
  38960. var nbSeg = positions.length / 6;
  38961. var lg = 0;
  38962. var nb = 0;
  38963. var shft = 0;
  38964. var dashshft = 0;
  38965. var curshft = 0;
  38966. var p = 0;
  38967. var i = 0;
  38968. var j = 0;
  38969. for (i = 0; i < points.length - 1; i++) {
  38970. points[i + 1].subtractToRef(points[i], curvect);
  38971. lg += curvect.length();
  38972. }
  38973. shft = lg / nbSeg;
  38974. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  38975. for (i = 0; i < points.length - 1; i++) {
  38976. points[i + 1].subtractToRef(points[i], curvect);
  38977. nb = Math.floor(curvect.length() / shft);
  38978. curvect.normalize();
  38979. j = 0;
  38980. while (j < nb && p < positions.length) {
  38981. curshft = shft * j;
  38982. positions[p] = points[i].x + curshft * curvect.x;
  38983. positions[p + 1] = points[i].y + curshft * curvect.y;
  38984. positions[p + 2] = points[i].z + curshft * curvect.z;
  38985. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  38986. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  38987. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  38988. p += 6;
  38989. j++;
  38990. }
  38991. }
  38992. while (p < positions.length) {
  38993. positions[p] = points[i].x;
  38994. positions[p + 1] = points[i].y;
  38995. positions[p + 2] = points[i].z;
  38996. p += 3;
  38997. }
  38998. };
  38999. instance.updateMeshPositions(positionFunction, false);
  39000. return instance;
  39001. }
  39002. // dashed lines creation
  39003. var dashedLines = new BABYLON.LinesMesh(name, scene);
  39004. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  39005. vertexData.applyToMesh(dashedLines, options.updatable);
  39006. dashedLines.dashSize = dashSize;
  39007. dashedLines.gapSize = gapSize;
  39008. return dashedLines;
  39009. };
  39010. /**
  39011. * Creates an extruded shape mesh.
  39012. * 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.
  39013. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  39014. *
  39015. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  39016. * 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
  39017. * extruded along the Z axis.
  39018. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  39019. * 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.
  39020. * The parameter `scale` (float, default 1) is the value to scale the shape.
  39021. * 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
  39022. * 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
  39023. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  39024. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39025. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39026. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39027. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39028. */
  39029. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  39030. var path = options.path;
  39031. var shape = options.shape;
  39032. var scale = options.scale || 1;
  39033. var rotation = options.rotation || 0;
  39034. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  39035. var updatable = options.updatable;
  39036. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39037. var instance = options.instance;
  39038. var invertUV = options.invertUV || false;
  39039. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  39040. };
  39041. /**
  39042. * Creates an custom extruded shape mesh.
  39043. * 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.
  39044. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  39045. *
  39046. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  39047. * 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
  39048. * extruded along the Z axis.
  39049. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  39050. * 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
  39051. * and the distance of this point from the begining of the path :
  39052. * ```javascript
  39053. * var rotationFunction = function(i, distance) {
  39054. * // do things
  39055. * return rotationValue; }
  39056. * ```
  39057. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  39058. * 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
  39059. * and the distance of this point from the begining of the path :
  39060. * ```javascript
  39061. * var scaleFunction = function(i, distance) {
  39062. * // do things
  39063. * return scaleValue;}
  39064. * ```
  39065. * It must returns a float value that will be the scale value applied to the shape on each path point.
  39066. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  39067. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  39068. * 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
  39069. * 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
  39070. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  39071. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39072. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39073. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39074. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39075. */
  39076. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  39077. var path = options.path;
  39078. var shape = options.shape;
  39079. var scaleFunction = options.scaleFunction || (function () { return 1; });
  39080. var rotationFunction = options.rotationFunction || (function () { return 0; });
  39081. var ribbonCloseArray = options.ribbonCloseArray || false;
  39082. var ribbonClosePath = options.ribbonClosePath || false;
  39083. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  39084. var updatable = options.updatable;
  39085. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39086. var instance = options.instance;
  39087. var invertUV = options.invertUV || false;
  39088. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  39089. };
  39090. /**
  39091. * Creates lathe mesh.
  39092. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  39093. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  39094. *
  39095. * 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
  39096. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  39097. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  39098. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  39099. * 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.
  39100. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  39101. * 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
  39102. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39103. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39104. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39105. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39106. */
  39107. MeshBuilder.CreateLathe = function (name, options, scene) {
  39108. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  39109. var closed = (options.closed === undefined) ? true : options.closed;
  39110. var shape = options.shape;
  39111. var radius = options.radius || 1;
  39112. var tessellation = options.tessellation || 64;
  39113. var updatable = options.updatable;
  39114. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39115. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  39116. var pi2 = Math.PI * 2;
  39117. var paths = new Array();
  39118. var invertUV = options.invertUV || false;
  39119. var i = 0;
  39120. var p = 0;
  39121. var step = pi2 / tessellation * arc;
  39122. var rotated;
  39123. var path = new Array();
  39124. ;
  39125. for (i = 0; i <= tessellation; i++) {
  39126. var path = [];
  39127. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  39128. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  39129. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  39130. }
  39131. for (p = 0; p < shape.length; p++) {
  39132. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  39133. path.push(rotated);
  39134. }
  39135. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  39136. 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));
  39137. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  39138. }
  39139. paths.push(path);
  39140. }
  39141. // lathe ribbon
  39142. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  39143. return lathe;
  39144. };
  39145. /**
  39146. * Creates a plane mesh.
  39147. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  39148. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  39149. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  39150. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  39151. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39152. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39153. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39154. */
  39155. MeshBuilder.CreatePlane = function (name, options, scene) {
  39156. var plane = new BABYLON.Mesh(name, scene);
  39157. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39158. plane.sideOrientation = options.sideOrientation;
  39159. var vertexData = BABYLON.VertexData.CreatePlane(options);
  39160. vertexData.applyToMesh(plane, options.updatable);
  39161. if (options.sourcePlane) {
  39162. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  39163. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  39164. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  39165. plane.rotate(vectorProduct, product);
  39166. }
  39167. return plane;
  39168. };
  39169. /**
  39170. * Creates a ground mesh.
  39171. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  39172. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  39173. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  39174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39175. */
  39176. MeshBuilder.CreateGround = function (name, options, scene) {
  39177. var ground = new BABYLON.GroundMesh(name, scene);
  39178. ground._setReady(false);
  39179. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  39180. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  39181. ground._width = options.width || 1;
  39182. ground._height = options.height || 1;
  39183. ground._maxX = ground._width / 2;
  39184. ground._maxZ = ground._height / 2;
  39185. ground._minX = -ground._maxX;
  39186. ground._minZ = -ground._maxZ;
  39187. var vertexData = BABYLON.VertexData.CreateGround(options);
  39188. vertexData.applyToMesh(ground, options.updatable);
  39189. ground._setReady(true);
  39190. return ground;
  39191. };
  39192. /**
  39193. * Creates a tiled ground mesh.
  39194. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  39195. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  39196. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  39197. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  39198. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  39199. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  39200. * numbers of subdivisions on the ground width and height of each tile.
  39201. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39202. */
  39203. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  39204. var tiledGround = new BABYLON.Mesh(name, scene);
  39205. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  39206. vertexData.applyToMesh(tiledGround, options.updatable);
  39207. return tiledGround;
  39208. };
  39209. /**
  39210. * Creates a ground mesh from a height map.
  39211. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  39212. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  39213. * The parameter `url` sets the URL of the height map image resource.
  39214. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  39215. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  39216. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  39217. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  39218. * 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.
  39219. * 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).
  39220. * This function is passed the newly built mesh :
  39221. * ```javascript
  39222. * function(mesh) { // do things
  39223. * return; }
  39224. * ```
  39225. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39226. */
  39227. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  39228. var width = options.width || 10.0;
  39229. var height = options.height || 10.0;
  39230. var subdivisions = options.subdivisions || 1 | 0;
  39231. var minHeight = options.minHeight || 0.0;
  39232. var maxHeight = options.maxHeight || 10.0;
  39233. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  39234. var updatable = options.updatable;
  39235. var onReady = options.onReady;
  39236. var ground = new BABYLON.GroundMesh(name, scene);
  39237. ground._subdivisionsX = subdivisions;
  39238. ground._subdivisionsY = subdivisions;
  39239. ground._width = width;
  39240. ground._height = height;
  39241. ground._maxX = ground._width / 2.0;
  39242. ground._maxZ = ground._height / 2.0;
  39243. ground._minX = -ground._maxX;
  39244. ground._minZ = -ground._maxZ;
  39245. ground._setReady(false);
  39246. var onload = function (img) {
  39247. // Getting height map data
  39248. var canvas = document.createElement("canvas");
  39249. var context = canvas.getContext("2d");
  39250. var bufferWidth = img.width;
  39251. var bufferHeight = img.height;
  39252. canvas.width = bufferWidth;
  39253. canvas.height = bufferHeight;
  39254. context.drawImage(img, 0, 0);
  39255. // Create VertexData from map data
  39256. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  39257. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  39258. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  39259. width: width, height: height,
  39260. subdivisions: subdivisions,
  39261. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  39262. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  39263. });
  39264. vertexData.applyToMesh(ground, updatable);
  39265. ground._setReady(true);
  39266. //execute ready callback, if set
  39267. if (onReady) {
  39268. onReady(ground);
  39269. }
  39270. };
  39271. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  39272. return ground;
  39273. };
  39274. /**
  39275. * Creates a tube mesh.
  39276. * 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.
  39277. *
  39278. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  39279. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  39280. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  39281. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  39282. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  39283. * 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.
  39284. * It must return a radius value (positive float) :
  39285. * ```javascript
  39286. * var radiusFunction = function(i, distance) {
  39287. * // do things
  39288. * return radius; }
  39289. * ```
  39290. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  39291. * 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
  39292. * 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
  39293. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39294. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39295. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  39296. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39297. */
  39298. MeshBuilder.CreateTube = function (name, options, scene) {
  39299. var path = options.path;
  39300. var radius = options.radius || 1.0;
  39301. var tessellation = options.tessellation || 64 | 0;
  39302. var radiusFunction = options.radiusFunction;
  39303. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  39304. var invertUV = options.invertUV || false;
  39305. var updatable = options.updatable;
  39306. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39307. var instance = options.instance;
  39308. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  39309. // tube geometry
  39310. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  39311. var tangents = path3D.getTangents();
  39312. var normals = path3D.getNormals();
  39313. var distances = path3D.getDistances();
  39314. var pi2 = Math.PI * 2;
  39315. var step = pi2 / tessellation * arc;
  39316. var returnRadius = function () { return radius; };
  39317. var radiusFunctionFinal = radiusFunction || returnRadius;
  39318. var circlePath;
  39319. var rad;
  39320. var normal;
  39321. var rotated;
  39322. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  39323. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  39324. for (var i = 0; i < path.length; i++) {
  39325. rad = radiusFunctionFinal(i, distances[i]); // current radius
  39326. circlePath = Array(); // current circle array
  39327. normal = normals[i]; // current normal
  39328. for (var t = 0; t < tessellation; t++) {
  39329. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  39330. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  39331. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  39332. rotated.scaleInPlace(rad).addInPlace(path[i]);
  39333. circlePath[t] = rotated;
  39334. }
  39335. circlePaths[index] = circlePath;
  39336. index++;
  39337. }
  39338. // cap
  39339. var capPath = function (nbPoints, pathIndex) {
  39340. var pointCap = Array();
  39341. for (var i = 0; i < nbPoints; i++) {
  39342. pointCap.push(path[pathIndex]);
  39343. }
  39344. return pointCap;
  39345. };
  39346. switch (cap) {
  39347. case BABYLON.Mesh.NO_CAP:
  39348. break;
  39349. case BABYLON.Mesh.CAP_START:
  39350. circlePaths[0] = capPath(tessellation, 0);
  39351. circlePaths[1] = circlePaths[2].slice(0);
  39352. break;
  39353. case BABYLON.Mesh.CAP_END:
  39354. circlePaths[index] = circlePaths[index - 1].slice(0);
  39355. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  39356. break;
  39357. case BABYLON.Mesh.CAP_ALL:
  39358. circlePaths[0] = capPath(tessellation, 0);
  39359. circlePaths[1] = circlePaths[2].slice(0);
  39360. circlePaths[index] = circlePaths[index - 1].slice(0);
  39361. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  39362. break;
  39363. default:
  39364. break;
  39365. }
  39366. return circlePaths;
  39367. };
  39368. var path3D;
  39369. var pathArray;
  39370. if (instance) {
  39371. var arc = options.arc || instance.arc;
  39372. path3D = (instance.path3D).update(path);
  39373. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  39374. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  39375. instance.path3D = path3D;
  39376. instance.pathArray = pathArray;
  39377. instance.arc = arc;
  39378. return instance;
  39379. }
  39380. // tube creation
  39381. path3D = new BABYLON.Path3D(path);
  39382. var newPathArray = new Array();
  39383. cap = (cap < 0 || cap > 3) ? 0 : cap;
  39384. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  39385. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  39386. tube.pathArray = pathArray;
  39387. tube.path3D = path3D;
  39388. tube.tessellation = tessellation;
  39389. tube.cap = cap;
  39390. tube.arc = options.arc;
  39391. return tube;
  39392. };
  39393. /**
  39394. * Creates a polyhedron mesh.
  39395. *
  39396. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  39397. * 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
  39398. * to choose the wanted type.
  39399. * The parameter `size` (positive float, default 1) sets the polygon size.
  39400. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  39401. * 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`.
  39402. * 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
  39403. * 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)`).
  39404. * 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
  39405. * 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.
  39406. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39407. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  39408. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  39409. */
  39410. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  39411. var polyhedron = new BABYLON.Mesh(name, scene);
  39412. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  39413. polyhedron.sideOrientation = options.sideOrientation;
  39414. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  39415. vertexData.applyToMesh(polyhedron, options.updatable);
  39416. return polyhedron;
  39417. };
  39418. /**
  39419. * Creates a decal mesh.
  39420. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  39421. * 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.
  39422. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  39423. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  39424. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  39425. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  39426. */
  39427. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  39428. var indices = sourceMesh.getIndices();
  39429. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39430. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39431. var position = options.position || BABYLON.Vector3.Zero();
  39432. var normal = options.normal || BABYLON.Vector3.Up();
  39433. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  39434. var angle = options.angle || 0;
  39435. // Getting correct rotation
  39436. if (!normal) {
  39437. var target = new BABYLON.Vector3(0, 0, 1);
  39438. var camera = sourceMesh.getScene().activeCamera;
  39439. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  39440. normal = camera.globalPosition.subtract(cameraWorldTarget);
  39441. }
  39442. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  39443. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  39444. var pitch = Math.atan2(normal.y, len);
  39445. // Matrix
  39446. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  39447. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  39448. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  39449. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  39450. var vertexData = new BABYLON.VertexData();
  39451. vertexData.indices = [];
  39452. vertexData.positions = [];
  39453. vertexData.normals = [];
  39454. vertexData.uvs = [];
  39455. var currentVertexDataIndex = 0;
  39456. var extractDecalVector3 = function (indexId) {
  39457. var vertexId = indices[indexId];
  39458. var result = new BABYLON.PositionNormalVertex();
  39459. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  39460. // Send vector to decal local world
  39461. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  39462. // Get normal
  39463. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  39464. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  39465. return result;
  39466. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  39467. var clip = function (vertices, axis) {
  39468. if (vertices.length === 0) {
  39469. return vertices;
  39470. }
  39471. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  39472. var clipVertices = function (v0, v1) {
  39473. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  39474. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  39475. };
  39476. var result = new Array();
  39477. for (var index = 0; index < vertices.length; index += 3) {
  39478. var v1Out;
  39479. var v2Out;
  39480. var v3Out;
  39481. var total = 0;
  39482. var nV1, nV2, nV3, nV4;
  39483. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  39484. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  39485. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  39486. v1Out = d1 > 0;
  39487. v2Out = d2 > 0;
  39488. v3Out = d3 > 0;
  39489. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  39490. switch (total) {
  39491. case 0:
  39492. result.push(vertices[index]);
  39493. result.push(vertices[index + 1]);
  39494. result.push(vertices[index + 2]);
  39495. break;
  39496. case 1:
  39497. if (v1Out) {
  39498. nV1 = vertices[index + 1];
  39499. nV2 = vertices[index + 2];
  39500. nV3 = clipVertices(vertices[index], nV1);
  39501. nV4 = clipVertices(vertices[index], nV2);
  39502. }
  39503. if (v2Out) {
  39504. nV1 = vertices[index];
  39505. nV2 = vertices[index + 2];
  39506. nV3 = clipVertices(vertices[index + 1], nV1);
  39507. nV4 = clipVertices(vertices[index + 1], nV2);
  39508. result.push(nV3);
  39509. result.push(nV2.clone());
  39510. result.push(nV1.clone());
  39511. result.push(nV2.clone());
  39512. result.push(nV3.clone());
  39513. result.push(nV4);
  39514. break;
  39515. }
  39516. if (v3Out) {
  39517. nV1 = vertices[index];
  39518. nV2 = vertices[index + 1];
  39519. nV3 = clipVertices(vertices[index + 2], nV1);
  39520. nV4 = clipVertices(vertices[index + 2], nV2);
  39521. }
  39522. result.push(nV1.clone());
  39523. result.push(nV2.clone());
  39524. result.push(nV3);
  39525. result.push(nV4);
  39526. result.push(nV3.clone());
  39527. result.push(nV2.clone());
  39528. break;
  39529. case 2:
  39530. if (!v1Out) {
  39531. nV1 = vertices[index].clone();
  39532. nV2 = clipVertices(nV1, vertices[index + 1]);
  39533. nV3 = clipVertices(nV1, vertices[index + 2]);
  39534. result.push(nV1);
  39535. result.push(nV2);
  39536. result.push(nV3);
  39537. }
  39538. if (!v2Out) {
  39539. nV1 = vertices[index + 1].clone();
  39540. nV2 = clipVertices(nV1, vertices[index + 2]);
  39541. nV3 = clipVertices(nV1, vertices[index]);
  39542. result.push(nV1);
  39543. result.push(nV2);
  39544. result.push(nV3);
  39545. }
  39546. if (!v3Out) {
  39547. nV1 = vertices[index + 2].clone();
  39548. nV2 = clipVertices(nV1, vertices[index]);
  39549. nV3 = clipVertices(nV1, vertices[index + 1]);
  39550. result.push(nV1);
  39551. result.push(nV2);
  39552. result.push(nV3);
  39553. }
  39554. break;
  39555. case 3:
  39556. break;
  39557. }
  39558. }
  39559. return result;
  39560. };
  39561. for (var index = 0; index < indices.length; index += 3) {
  39562. var faceVertices = new Array();
  39563. faceVertices.push(extractDecalVector3(index));
  39564. faceVertices.push(extractDecalVector3(index + 1));
  39565. faceVertices.push(extractDecalVector3(index + 2));
  39566. // Clip
  39567. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  39568. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  39569. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  39570. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  39571. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  39572. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  39573. if (faceVertices.length === 0) {
  39574. continue;
  39575. }
  39576. // Add UVs and get back to world
  39577. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  39578. var vertex = faceVertices[vIndex];
  39579. //TODO check for Int32Array | Uint32Array | Uint16Array
  39580. vertexData.indices.push(currentVertexDataIndex);
  39581. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  39582. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  39583. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  39584. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  39585. currentVertexDataIndex++;
  39586. }
  39587. }
  39588. // Return mesh
  39589. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  39590. vertexData.applyToMesh(decal);
  39591. decal.position = position.clone();
  39592. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  39593. return decal;
  39594. };
  39595. // Privates
  39596. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  39597. // extrusion geometry
  39598. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  39599. var tangents = path3D.getTangents();
  39600. var normals = path3D.getNormals();
  39601. var binormals = path3D.getBinormals();
  39602. var distances = path3D.getDistances();
  39603. var angle = 0;
  39604. var returnScale = function () { return scale; };
  39605. var returnRotation = function () { return rotation; };
  39606. var rotate = custom ? rotateFunction : returnRotation;
  39607. var scl = custom ? scaleFunction : returnScale;
  39608. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  39609. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  39610. for (var i = 0; i < curve.length; i++) {
  39611. var shapePath = new Array();
  39612. var angleStep = rotate(i, distances[i]);
  39613. var scaleRatio = scl(i, distances[i]);
  39614. for (var p = 0; p < shape.length; p++) {
  39615. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  39616. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  39617. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  39618. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  39619. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  39620. shapePath[p] = rotated;
  39621. }
  39622. shapePaths[index] = shapePath;
  39623. angle += angleStep;
  39624. index++;
  39625. }
  39626. // cap
  39627. var capPath = function (shapePath) {
  39628. var pointCap = Array();
  39629. var barycenter = BABYLON.Vector3.Zero();
  39630. var i;
  39631. for (i = 0; i < shapePath.length; i++) {
  39632. barycenter.addInPlace(shapePath[i]);
  39633. }
  39634. barycenter.scaleInPlace(1.0 / shapePath.length);
  39635. for (i = 0; i < shapePath.length; i++) {
  39636. pointCap.push(barycenter);
  39637. }
  39638. return pointCap;
  39639. };
  39640. switch (cap) {
  39641. case BABYLON.Mesh.NO_CAP:
  39642. break;
  39643. case BABYLON.Mesh.CAP_START:
  39644. shapePaths[0] = capPath(shapePaths[2]);
  39645. shapePaths[1] = shapePaths[2];
  39646. break;
  39647. case BABYLON.Mesh.CAP_END:
  39648. shapePaths[index] = shapePaths[index - 1];
  39649. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  39650. break;
  39651. case BABYLON.Mesh.CAP_ALL:
  39652. shapePaths[0] = capPath(shapePaths[2]);
  39653. shapePaths[1] = shapePaths[2];
  39654. shapePaths[index] = shapePaths[index - 1];
  39655. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  39656. break;
  39657. default:
  39658. break;
  39659. }
  39660. return shapePaths;
  39661. };
  39662. var path3D;
  39663. var pathArray;
  39664. if (instance) {
  39665. path3D = (instance.path3D).update(curve);
  39666. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  39667. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  39668. return instance;
  39669. }
  39670. // extruded shape creation
  39671. path3D = new BABYLON.Path3D(curve);
  39672. var newShapePaths = new Array();
  39673. cap = (cap < 0 || cap > 3) ? 0 : cap;
  39674. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  39675. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  39676. extrudedGeneric.pathArray = pathArray;
  39677. extrudedGeneric.path3D = path3D;
  39678. extrudedGeneric.cap = cap;
  39679. return extrudedGeneric;
  39680. };
  39681. return MeshBuilder;
  39682. }());
  39683. BABYLON.MeshBuilder = MeshBuilder;
  39684. })(BABYLON || (BABYLON = {}));
  39685. //# sourceMappingURL=babylon.meshBuilder.js.map
  39686. var BABYLON;
  39687. (function (BABYLON) {
  39688. var AudioEngine = (function () {
  39689. function AudioEngine() {
  39690. this._audioContext = null;
  39691. this._audioContextInitialized = false;
  39692. this.canUseWebAudio = false;
  39693. this.WarnedWebAudioUnsupported = false;
  39694. this.unlocked = false;
  39695. this.isMP3supported = false;
  39696. this.isOGGsupported = false;
  39697. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  39698. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  39699. this.canUseWebAudio = true;
  39700. }
  39701. var audioElem = document.createElement('audio');
  39702. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  39703. this.isMP3supported = true;
  39704. }
  39705. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  39706. this.isOGGsupported = true;
  39707. }
  39708. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  39709. this._unlockiOSaudio();
  39710. }
  39711. else {
  39712. this.unlocked = true;
  39713. }
  39714. }
  39715. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  39716. get: function () {
  39717. if (!this._audioContextInitialized) {
  39718. this._initializeAudioContext();
  39719. }
  39720. return this._audioContext;
  39721. },
  39722. enumerable: true,
  39723. configurable: true
  39724. });
  39725. AudioEngine.prototype._unlockiOSaudio = function () {
  39726. var _this = this;
  39727. var unlockaudio = function () {
  39728. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  39729. var source = _this.audioContext.createBufferSource();
  39730. source.buffer = buffer;
  39731. source.connect(_this.audioContext.destination);
  39732. source.start(0);
  39733. setTimeout(function () {
  39734. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  39735. _this.unlocked = true;
  39736. window.removeEventListener('touchend', unlockaudio, false);
  39737. if (_this.onAudioUnlocked) {
  39738. _this.onAudioUnlocked();
  39739. }
  39740. }
  39741. }, 0);
  39742. };
  39743. window.addEventListener('touchend', unlockaudio, false);
  39744. };
  39745. AudioEngine.prototype._initializeAudioContext = function () {
  39746. try {
  39747. if (this.canUseWebAudio) {
  39748. this._audioContext = new AudioContext();
  39749. // create a global volume gain node
  39750. this.masterGain = this._audioContext.createGain();
  39751. this.masterGain.gain.value = 1;
  39752. this.masterGain.connect(this._audioContext.destination);
  39753. this._audioContextInitialized = true;
  39754. }
  39755. }
  39756. catch (e) {
  39757. this.canUseWebAudio = false;
  39758. BABYLON.Tools.Error("Web Audio: " + e.message);
  39759. }
  39760. };
  39761. AudioEngine.prototype.dispose = function () {
  39762. if (this.canUseWebAudio && this._audioContextInitialized) {
  39763. if (this._connectedAnalyser) {
  39764. this._connectedAnalyser.stopDebugCanvas();
  39765. this._connectedAnalyser.dispose();
  39766. this.masterGain.disconnect();
  39767. this.masterGain.connect(this._audioContext.destination);
  39768. this._connectedAnalyser = null;
  39769. }
  39770. this.masterGain.gain.value = 1;
  39771. }
  39772. this.WarnedWebAudioUnsupported = false;
  39773. };
  39774. AudioEngine.prototype.getGlobalVolume = function () {
  39775. if (this.canUseWebAudio && this._audioContextInitialized) {
  39776. return this.masterGain.gain.value;
  39777. }
  39778. else {
  39779. return -1;
  39780. }
  39781. };
  39782. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  39783. if (this.canUseWebAudio && this._audioContextInitialized) {
  39784. this.masterGain.gain.value = newVolume;
  39785. }
  39786. };
  39787. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  39788. if (this._connectedAnalyser) {
  39789. this._connectedAnalyser.stopDebugCanvas();
  39790. }
  39791. if (this.canUseWebAudio && this._audioContextInitialized) {
  39792. this._connectedAnalyser = analyser;
  39793. this.masterGain.disconnect();
  39794. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  39795. }
  39796. };
  39797. return AudioEngine;
  39798. }());
  39799. BABYLON.AudioEngine = AudioEngine;
  39800. })(BABYLON || (BABYLON = {}));
  39801. //# sourceMappingURL=babylon.audioEngine.js.map
  39802. var BABYLON;
  39803. (function (BABYLON) {
  39804. var Sound = (function () {
  39805. /**
  39806. * Create a sound and attach it to a scene
  39807. * @param name Name of your sound
  39808. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  39809. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  39810. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  39811. */
  39812. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  39813. var _this = this;
  39814. this.autoplay = false;
  39815. this.loop = false;
  39816. this.useCustomAttenuation = false;
  39817. this.spatialSound = false;
  39818. this.refDistance = 1;
  39819. this.rolloffFactor = 1;
  39820. this.maxDistance = 100;
  39821. this.distanceModel = "linear";
  39822. this._panningModel = "equalpower";
  39823. this._playbackRate = 1;
  39824. this._streaming = false;
  39825. this._startTime = 0;
  39826. this._startOffset = 0;
  39827. this._position = BABYLON.Vector3.Zero();
  39828. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  39829. this._volume = 1;
  39830. this._isLoaded = false;
  39831. this._isReadyToPlay = false;
  39832. this.isPlaying = false;
  39833. this.isPaused = false;
  39834. this._isDirectional = false;
  39835. // Used if you'd like to create a directional sound.
  39836. // If not set, the sound will be omnidirectional
  39837. this._coneInnerAngle = 360;
  39838. this._coneOuterAngle = 360;
  39839. this._coneOuterGain = 0;
  39840. this._isOutputConnected = false;
  39841. this._urlType = "Unknown";
  39842. this.name = name;
  39843. this._scene = scene;
  39844. this._readyToPlayCallback = readyToPlayCallback;
  39845. // Default custom attenuation function is a linear attenuation
  39846. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  39847. if (currentDistance < maxDistance) {
  39848. return currentVolume * (1 - currentDistance / maxDistance);
  39849. }
  39850. else {
  39851. return 0;
  39852. }
  39853. };
  39854. if (options) {
  39855. this.autoplay = options.autoplay || false;
  39856. this.loop = options.loop || false;
  39857. // if volume === 0, we need another way to check this option
  39858. if (options.volume !== undefined) {
  39859. this._volume = options.volume;
  39860. }
  39861. this.spatialSound = options.spatialSound || false;
  39862. this.maxDistance = options.maxDistance || 100;
  39863. this.useCustomAttenuation = options.useCustomAttenuation || false;
  39864. this.rolloffFactor = options.rolloffFactor || 1;
  39865. this.refDistance = options.refDistance || 1;
  39866. this.distanceModel = options.distanceModel || "linear";
  39867. this._playbackRate = options.playbackRate || 1;
  39868. this._streaming = options.streaming || false;
  39869. }
  39870. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39871. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  39872. this._soundGain.gain.value = this._volume;
  39873. this._inputAudioNode = this._soundGain;
  39874. this._ouputAudioNode = this._soundGain;
  39875. if (this.spatialSound) {
  39876. this._createSpatialParameters();
  39877. }
  39878. this._scene.mainSoundTrack.AddSound(this);
  39879. var validParameter = true;
  39880. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  39881. if (urlOrArrayBuffer) {
  39882. if (typeof (urlOrArrayBuffer) === "string")
  39883. this._urlType = "String";
  39884. if (Array.isArray(urlOrArrayBuffer))
  39885. this._urlType = "Array";
  39886. if (urlOrArrayBuffer instanceof ArrayBuffer)
  39887. this._urlType = "ArrayBuffer";
  39888. var urls = [];
  39889. var codecSupportedFound = false;
  39890. switch (this._urlType) {
  39891. case "ArrayBuffer":
  39892. if (urlOrArrayBuffer.byteLength > 0) {
  39893. codecSupportedFound = true;
  39894. this._soundLoaded(urlOrArrayBuffer);
  39895. }
  39896. break;
  39897. case "String":
  39898. urls.push(urlOrArrayBuffer);
  39899. case "Array":
  39900. if (urls.length === 0)
  39901. urls = urlOrArrayBuffer;
  39902. // If we found a supported format, we load it immediately and stop the loop
  39903. for (var i = 0; i < urls.length; i++) {
  39904. var url = urls[i];
  39905. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  39906. codecSupportedFound = true;
  39907. }
  39908. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  39909. codecSupportedFound = true;
  39910. }
  39911. if (url.indexOf(".wav", url.length - 4) !== -1) {
  39912. codecSupportedFound = true;
  39913. }
  39914. if (codecSupportedFound) {
  39915. // Loading sound using XHR2
  39916. if (!this._streaming) {
  39917. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  39918. }
  39919. else {
  39920. this._htmlAudioElement = new Audio(url);
  39921. this._htmlAudioElement.controls = false;
  39922. this._htmlAudioElement.loop = this.loop;
  39923. this._htmlAudioElement.crossOrigin = "anonymous";
  39924. this._htmlAudioElement.preload = "auto";
  39925. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  39926. _this._isReadyToPlay = true;
  39927. if (_this.autoplay) {
  39928. _this.play();
  39929. }
  39930. if (_this._readyToPlayCallback) {
  39931. _this._readyToPlayCallback();
  39932. }
  39933. });
  39934. document.body.appendChild(this._htmlAudioElement);
  39935. }
  39936. break;
  39937. }
  39938. }
  39939. break;
  39940. default:
  39941. validParameter = false;
  39942. break;
  39943. }
  39944. if (!validParameter) {
  39945. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  39946. }
  39947. else {
  39948. if (!codecSupportedFound) {
  39949. this._isReadyToPlay = true;
  39950. // Simulating a ready to play event to avoid breaking code path
  39951. if (this._readyToPlayCallback) {
  39952. window.setTimeout(function () {
  39953. _this._readyToPlayCallback();
  39954. }, 1000);
  39955. }
  39956. }
  39957. }
  39958. }
  39959. }
  39960. else {
  39961. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  39962. this._scene.mainSoundTrack.AddSound(this);
  39963. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  39964. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  39965. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  39966. }
  39967. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  39968. if (this._readyToPlayCallback) {
  39969. window.setTimeout(function () {
  39970. _this._readyToPlayCallback();
  39971. }, 1000);
  39972. }
  39973. }
  39974. }
  39975. Sound.prototype.dispose = function () {
  39976. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  39977. if (this.isPlaying) {
  39978. this.stop();
  39979. }
  39980. this._isReadyToPlay = false;
  39981. if (this.soundTrackId === -1) {
  39982. this._scene.mainSoundTrack.RemoveSound(this);
  39983. }
  39984. else {
  39985. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  39986. }
  39987. if (this._soundGain) {
  39988. this._soundGain.disconnect();
  39989. this._soundGain = null;
  39990. }
  39991. if (this._soundPanner) {
  39992. this._soundPanner.disconnect();
  39993. this._soundPanner = null;
  39994. }
  39995. if (this._soundSource) {
  39996. this._soundSource.disconnect();
  39997. this._soundSource = null;
  39998. }
  39999. this._audioBuffer = null;
  40000. if (this._htmlAudioElement) {
  40001. this._htmlAudioElement.pause();
  40002. this._htmlAudioElement.src = "";
  40003. document.body.removeChild(this._htmlAudioElement);
  40004. }
  40005. if (this._connectedMesh) {
  40006. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  40007. this._connectedMesh = null;
  40008. }
  40009. }
  40010. };
  40011. Sound.prototype.isReady = function () {
  40012. return this._isReadyToPlay;
  40013. };
  40014. Sound.prototype._soundLoaded = function (audioData) {
  40015. var _this = this;
  40016. this._isLoaded = true;
  40017. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  40018. _this._audioBuffer = buffer;
  40019. _this._isReadyToPlay = true;
  40020. if (_this.autoplay) {
  40021. _this.play();
  40022. }
  40023. if (_this._readyToPlayCallback) {
  40024. _this._readyToPlayCallback();
  40025. }
  40026. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  40027. };
  40028. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  40029. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40030. this._audioBuffer = audioBuffer;
  40031. this._isReadyToPlay = true;
  40032. }
  40033. };
  40034. Sound.prototype.updateOptions = function (options) {
  40035. if (options) {
  40036. this.loop = options.loop || this.loop;
  40037. this.maxDistance = options.maxDistance || this.maxDistance;
  40038. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  40039. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  40040. this.refDistance = options.refDistance || this.refDistance;
  40041. this.distanceModel = options.distanceModel || this.distanceModel;
  40042. this._playbackRate = options.playbackRate || this._playbackRate;
  40043. this._updateSpatialParameters();
  40044. if (this.isPlaying) {
  40045. if (this._streaming) {
  40046. this._htmlAudioElement.playbackRate = this._playbackRate;
  40047. }
  40048. else {
  40049. this._soundSource.playbackRate.value = this._playbackRate;
  40050. }
  40051. }
  40052. }
  40053. };
  40054. Sound.prototype._createSpatialParameters = function () {
  40055. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40056. if (this._scene.headphone) {
  40057. this._panningModel = "HRTF";
  40058. }
  40059. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  40060. this._updateSpatialParameters();
  40061. this._soundPanner.connect(this._ouputAudioNode);
  40062. this._inputAudioNode = this._soundPanner;
  40063. }
  40064. };
  40065. Sound.prototype._updateSpatialParameters = function () {
  40066. if (this.spatialSound) {
  40067. if (this.useCustomAttenuation) {
  40068. // Tricks to disable in a way embedded Web Audio attenuation
  40069. this._soundPanner.distanceModel = "linear";
  40070. this._soundPanner.maxDistance = Number.MAX_VALUE;
  40071. this._soundPanner.refDistance = 1;
  40072. this._soundPanner.rolloffFactor = 1;
  40073. this._soundPanner.panningModel = this._panningModel;
  40074. }
  40075. else {
  40076. this._soundPanner.distanceModel = this.distanceModel;
  40077. this._soundPanner.maxDistance = this.maxDistance;
  40078. this._soundPanner.refDistance = this.refDistance;
  40079. this._soundPanner.rolloffFactor = this.rolloffFactor;
  40080. this._soundPanner.panningModel = this._panningModel;
  40081. }
  40082. }
  40083. };
  40084. Sound.prototype.switchPanningModelToHRTF = function () {
  40085. this._panningModel = "HRTF";
  40086. this._switchPanningModel();
  40087. };
  40088. Sound.prototype.switchPanningModelToEqualPower = function () {
  40089. this._panningModel = "equalpower";
  40090. this._switchPanningModel();
  40091. };
  40092. Sound.prototype._switchPanningModel = function () {
  40093. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  40094. this._soundPanner.panningModel = this._panningModel;
  40095. }
  40096. };
  40097. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  40098. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40099. if (this._isOutputConnected) {
  40100. this._ouputAudioNode.disconnect();
  40101. }
  40102. this._ouputAudioNode.connect(soundTrackAudioNode);
  40103. this._isOutputConnected = true;
  40104. }
  40105. };
  40106. /**
  40107. * Transform this sound into a directional source
  40108. * @param coneInnerAngle Size of the inner cone in degree
  40109. * @param coneOuterAngle Size of the outer cone in degree
  40110. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  40111. */
  40112. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  40113. if (coneOuterAngle < coneInnerAngle) {
  40114. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  40115. return;
  40116. }
  40117. this._coneInnerAngle = coneInnerAngle;
  40118. this._coneOuterAngle = coneOuterAngle;
  40119. this._coneOuterGain = coneOuterGain;
  40120. this._isDirectional = true;
  40121. if (this.isPlaying && this.loop) {
  40122. this.stop();
  40123. this.play();
  40124. }
  40125. };
  40126. Sound.prototype.setPosition = function (newPosition) {
  40127. this._position = newPosition;
  40128. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  40129. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  40130. }
  40131. };
  40132. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  40133. this._localDirection = newLocalDirection;
  40134. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  40135. this._updateDirection();
  40136. }
  40137. };
  40138. Sound.prototype._updateDirection = function () {
  40139. var mat = this._connectedMesh.getWorldMatrix();
  40140. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  40141. direction.normalize();
  40142. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  40143. };
  40144. Sound.prototype.updateDistanceFromListener = function () {
  40145. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  40146. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  40147. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  40148. }
  40149. };
  40150. Sound.prototype.setAttenuationFunction = function (callback) {
  40151. this._customAttenuationFunction = callback;
  40152. };
  40153. /**
  40154. * Play the sound
  40155. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  40156. * @param offset (optional) Start the sound setting it at a specific time
  40157. */
  40158. Sound.prototype.play = function (time, offset) {
  40159. var _this = this;
  40160. if (this._isReadyToPlay && this._scene.audioEnabled) {
  40161. try {
  40162. if (this._startOffset < 0) {
  40163. time = -this._startOffset;
  40164. this._startOffset = 0;
  40165. }
  40166. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  40167. if (!this._soundSource || !this._streamingSource) {
  40168. if (this.spatialSound) {
  40169. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  40170. if (this._isDirectional) {
  40171. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  40172. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  40173. this._soundPanner.coneOuterGain = this._coneOuterGain;
  40174. if (this._connectedMesh) {
  40175. this._updateDirection();
  40176. }
  40177. else {
  40178. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  40179. }
  40180. }
  40181. }
  40182. }
  40183. if (this._streaming) {
  40184. if (!this._streamingSource) {
  40185. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  40186. this._htmlAudioElement.onended = function () { _this._onended(); };
  40187. this._htmlAudioElement.playbackRate = this._playbackRate;
  40188. }
  40189. this._streamingSource.disconnect();
  40190. this._streamingSource.connect(this._inputAudioNode);
  40191. this._htmlAudioElement.play();
  40192. }
  40193. else {
  40194. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  40195. this._soundSource.buffer = this._audioBuffer;
  40196. this._soundSource.connect(this._inputAudioNode);
  40197. this._soundSource.loop = this.loop;
  40198. this._soundSource.playbackRate.value = this._playbackRate;
  40199. this._soundSource.onended = function () { _this._onended(); };
  40200. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  40201. }
  40202. this._startTime = startTime;
  40203. this.isPlaying = true;
  40204. this.isPaused = false;
  40205. }
  40206. catch (ex) {
  40207. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  40208. }
  40209. }
  40210. };
  40211. Sound.prototype._onended = function () {
  40212. this.isPlaying = false;
  40213. if (this.onended) {
  40214. this.onended();
  40215. }
  40216. };
  40217. /**
  40218. * Stop the sound
  40219. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  40220. */
  40221. Sound.prototype.stop = function (time) {
  40222. if (this.isPlaying) {
  40223. if (this._streaming) {
  40224. this._htmlAudioElement.pause();
  40225. // Test needed for Firefox or it will generate an Invalid State Error
  40226. if (this._htmlAudioElement.currentTime > 0) {
  40227. this._htmlAudioElement.currentTime = 0;
  40228. }
  40229. }
  40230. else {
  40231. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  40232. this._soundSource.stop(stopTime);
  40233. this._soundSource.onended = null;
  40234. if (!this.isPaused) {
  40235. this._startOffset = 0;
  40236. }
  40237. }
  40238. this.isPlaying = false;
  40239. }
  40240. };
  40241. Sound.prototype.pause = function () {
  40242. if (this.isPlaying) {
  40243. this.isPaused = true;
  40244. if (this._streaming) {
  40245. this._htmlAudioElement.pause();
  40246. }
  40247. else {
  40248. this.stop(0);
  40249. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  40250. }
  40251. }
  40252. };
  40253. Sound.prototype.setVolume = function (newVolume, time) {
  40254. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40255. if (time) {
  40256. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  40257. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  40258. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  40259. }
  40260. else {
  40261. this._soundGain.gain.value = newVolume;
  40262. }
  40263. }
  40264. this._volume = newVolume;
  40265. };
  40266. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  40267. this._playbackRate = newPlaybackRate;
  40268. if (this.isPlaying) {
  40269. if (this._streaming) {
  40270. this._htmlAudioElement.playbackRate = this._playbackRate;
  40271. }
  40272. else {
  40273. this._soundSource.playbackRate.value = this._playbackRate;
  40274. }
  40275. }
  40276. };
  40277. Sound.prototype.getVolume = function () {
  40278. return this._volume;
  40279. };
  40280. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  40281. var _this = this;
  40282. if (this._connectedMesh) {
  40283. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  40284. this._registerFunc = null;
  40285. }
  40286. this._connectedMesh = meshToConnectTo;
  40287. if (!this.spatialSound) {
  40288. this.spatialSound = true;
  40289. this._createSpatialParameters();
  40290. if (this.isPlaying && this.loop) {
  40291. this.stop();
  40292. this.play();
  40293. }
  40294. }
  40295. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  40296. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  40297. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  40298. };
  40299. Sound.prototype.detachFromMesh = function () {
  40300. if (this._connectedMesh) {
  40301. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  40302. this._registerFunc = null;
  40303. this._connectedMesh = null;
  40304. }
  40305. };
  40306. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  40307. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  40308. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  40309. this._updateDirection();
  40310. }
  40311. };
  40312. Sound.prototype.clone = function () {
  40313. var _this = this;
  40314. if (!this._streaming) {
  40315. var setBufferAndRun = function () {
  40316. if (_this._isReadyToPlay) {
  40317. clonedSound._audioBuffer = _this.getAudioBuffer();
  40318. clonedSound._isReadyToPlay = true;
  40319. if (clonedSound.autoplay) {
  40320. clonedSound.play();
  40321. }
  40322. }
  40323. else {
  40324. window.setTimeout(setBufferAndRun, 300);
  40325. }
  40326. };
  40327. var currentOptions = {
  40328. autoplay: this.autoplay, loop: this.loop,
  40329. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  40330. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  40331. refDistance: this.refDistance, distanceModel: this.distanceModel
  40332. };
  40333. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  40334. if (this.useCustomAttenuation) {
  40335. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  40336. }
  40337. clonedSound.setPosition(this._position);
  40338. clonedSound.setPlaybackRate(this._playbackRate);
  40339. setBufferAndRun();
  40340. return clonedSound;
  40341. }
  40342. else {
  40343. return null;
  40344. }
  40345. };
  40346. Sound.prototype.getAudioBuffer = function () {
  40347. return this._audioBuffer;
  40348. };
  40349. Sound.prototype.serialize = function () {
  40350. var serializationObject = {
  40351. name: this.name,
  40352. url: this.name,
  40353. autoplay: this.autoplay,
  40354. loop: this.loop,
  40355. volume: this._volume,
  40356. spatialSound: this.spatialSound,
  40357. maxDistance: this.maxDistance,
  40358. rolloffFactor: this.rolloffFactor,
  40359. refDistance: this.refDistance,
  40360. distanceModel: this.distanceModel,
  40361. playbackRate: this._playbackRate,
  40362. panningModel: this._panningModel,
  40363. soundTrackId: this.soundTrackId
  40364. };
  40365. if (this.spatialSound) {
  40366. if (this._connectedMesh)
  40367. serializationObject.connectedMeshId = this._connectedMesh.id;
  40368. serializationObject.position = this._position.asArray();
  40369. serializationObject.refDistance = this.refDistance;
  40370. serializationObject.distanceModel = this.distanceModel;
  40371. serializationObject.isDirectional = this._isDirectional;
  40372. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  40373. serializationObject.coneInnerAngle = this._coneInnerAngle;
  40374. serializationObject.coneOuterAngle = this._coneOuterAngle;
  40375. serializationObject.coneOuterGain = this._coneOuterGain;
  40376. }
  40377. return serializationObject;
  40378. };
  40379. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  40380. var soundName = parsedSound.name;
  40381. var soundUrl;
  40382. if (parsedSound.url) {
  40383. soundUrl = rootUrl + parsedSound.url;
  40384. }
  40385. else {
  40386. soundUrl = rootUrl + soundName;
  40387. }
  40388. var options = {
  40389. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  40390. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  40391. rolloffFactor: parsedSound.rolloffFactor,
  40392. refDistance: parsedSound.refDistance,
  40393. distanceModel: parsedSound.distanceModel,
  40394. playbackRate: parsedSound.playbackRate
  40395. };
  40396. var newSound;
  40397. if (!sourceSound) {
  40398. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  40399. scene._addPendingData(newSound);
  40400. }
  40401. else {
  40402. var setBufferAndRun = function () {
  40403. if (sourceSound._isReadyToPlay) {
  40404. newSound._audioBuffer = sourceSound.getAudioBuffer();
  40405. newSound._isReadyToPlay = true;
  40406. if (newSound.autoplay) {
  40407. newSound.play();
  40408. }
  40409. }
  40410. else {
  40411. window.setTimeout(setBufferAndRun, 300);
  40412. }
  40413. };
  40414. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  40415. setBufferAndRun();
  40416. }
  40417. if (parsedSound.position) {
  40418. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  40419. newSound.setPosition(soundPosition);
  40420. }
  40421. if (parsedSound.isDirectional) {
  40422. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  40423. if (parsedSound.localDirectionToMesh) {
  40424. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  40425. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  40426. }
  40427. }
  40428. if (parsedSound.connectedMeshId) {
  40429. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  40430. if (connectedMesh) {
  40431. newSound.attachToMesh(connectedMesh);
  40432. }
  40433. }
  40434. return newSound;
  40435. };
  40436. return Sound;
  40437. }());
  40438. BABYLON.Sound = Sound;
  40439. })(BABYLON || (BABYLON = {}));
  40440. //# sourceMappingURL=babylon.sound.js.map
  40441. var BABYLON;
  40442. (function (BABYLON) {
  40443. var SoundTrack = (function () {
  40444. function SoundTrack(scene, options) {
  40445. this.id = -1;
  40446. this._isMainTrack = false;
  40447. this._isInitialized = false;
  40448. this._scene = scene;
  40449. this.soundCollection = new Array();
  40450. this._options = options;
  40451. if (!this._isMainTrack) {
  40452. this._scene.soundTracks.push(this);
  40453. this.id = this._scene.soundTracks.length - 1;
  40454. }
  40455. }
  40456. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  40457. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40458. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  40459. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  40460. if (this._options) {
  40461. if (this._options.volume) {
  40462. this._outputAudioNode.gain.value = this._options.volume;
  40463. }
  40464. if (this._options.mainTrack) {
  40465. this._isMainTrack = this._options.mainTrack;
  40466. }
  40467. }
  40468. this._isInitialized = true;
  40469. }
  40470. };
  40471. SoundTrack.prototype.dispose = function () {
  40472. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40473. if (this._connectedAnalyser) {
  40474. this._connectedAnalyser.stopDebugCanvas();
  40475. }
  40476. while (this.soundCollection.length) {
  40477. this.soundCollection[0].dispose();
  40478. }
  40479. if (this._outputAudioNode) {
  40480. this._outputAudioNode.disconnect();
  40481. }
  40482. this._outputAudioNode = null;
  40483. }
  40484. };
  40485. SoundTrack.prototype.AddSound = function (sound) {
  40486. if (!this._isInitialized) {
  40487. this._initializeSoundTrackAudioGraph();
  40488. }
  40489. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40490. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  40491. }
  40492. if (sound.soundTrackId) {
  40493. if (sound.soundTrackId === -1) {
  40494. this._scene.mainSoundTrack.RemoveSound(sound);
  40495. }
  40496. else {
  40497. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  40498. }
  40499. }
  40500. this.soundCollection.push(sound);
  40501. sound.soundTrackId = this.id;
  40502. };
  40503. SoundTrack.prototype.RemoveSound = function (sound) {
  40504. var index = this.soundCollection.indexOf(sound);
  40505. if (index !== -1) {
  40506. this.soundCollection.splice(index, 1);
  40507. }
  40508. };
  40509. SoundTrack.prototype.setVolume = function (newVolume) {
  40510. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40511. this._outputAudioNode.gain.value = newVolume;
  40512. }
  40513. };
  40514. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  40515. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40516. for (var i = 0; i < this.soundCollection.length; i++) {
  40517. this.soundCollection[i].switchPanningModelToHRTF();
  40518. }
  40519. }
  40520. };
  40521. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  40522. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40523. for (var i = 0; i < this.soundCollection.length; i++) {
  40524. this.soundCollection[i].switchPanningModelToEqualPower();
  40525. }
  40526. }
  40527. };
  40528. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  40529. if (this._connectedAnalyser) {
  40530. this._connectedAnalyser.stopDebugCanvas();
  40531. }
  40532. this._connectedAnalyser = analyser;
  40533. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  40534. this._outputAudioNode.disconnect();
  40535. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  40536. }
  40537. };
  40538. return SoundTrack;
  40539. }());
  40540. BABYLON.SoundTrack = SoundTrack;
  40541. })(BABYLON || (BABYLON = {}));
  40542. //# sourceMappingURL=babylon.soundtrack.js.map
  40543. var BABYLON;
  40544. (function (BABYLON) {
  40545. var Analyser = (function () {
  40546. function Analyser(scene) {
  40547. this.SMOOTHING = 0.75;
  40548. this.FFT_SIZE = 512;
  40549. this.BARGRAPHAMPLITUDE = 256;
  40550. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  40551. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  40552. this._scene = scene;
  40553. this._audioEngine = BABYLON.Engine.audioEngine;
  40554. if (this._audioEngine.canUseWebAudio) {
  40555. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  40556. this._webAudioAnalyser.minDecibels = -140;
  40557. this._webAudioAnalyser.maxDecibels = 0;
  40558. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  40559. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  40560. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  40561. }
  40562. }
  40563. Analyser.prototype.getFrequencyBinCount = function () {
  40564. if (this._audioEngine.canUseWebAudio) {
  40565. return this._webAudioAnalyser.frequencyBinCount;
  40566. }
  40567. else {
  40568. return 0;
  40569. }
  40570. };
  40571. Analyser.prototype.getByteFrequencyData = function () {
  40572. if (this._audioEngine.canUseWebAudio) {
  40573. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40574. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40575. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  40576. }
  40577. return this._byteFreqs;
  40578. };
  40579. Analyser.prototype.getByteTimeDomainData = function () {
  40580. if (this._audioEngine.canUseWebAudio) {
  40581. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40582. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40583. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  40584. }
  40585. return this._byteTime;
  40586. };
  40587. Analyser.prototype.getFloatFrequencyData = function () {
  40588. if (this._audioEngine.canUseWebAudio) {
  40589. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  40590. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  40591. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  40592. }
  40593. return this._floatFreqs;
  40594. };
  40595. Analyser.prototype.drawDebugCanvas = function () {
  40596. var _this = this;
  40597. if (this._audioEngine.canUseWebAudio) {
  40598. if (!this._debugCanvas) {
  40599. this._debugCanvas = document.createElement("canvas");
  40600. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  40601. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  40602. this._debugCanvas.style.position = "absolute";
  40603. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  40604. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  40605. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  40606. document.body.appendChild(this._debugCanvas);
  40607. this._registerFunc = function () {
  40608. _this.drawDebugCanvas();
  40609. };
  40610. this._scene.registerBeforeRender(this._registerFunc);
  40611. }
  40612. if (this._registerFunc) {
  40613. var workingArray = this.getByteFrequencyData();
  40614. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  40615. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  40616. // Draw the frequency domain chart.
  40617. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  40618. var value = workingArray[i];
  40619. var percent = value / this.BARGRAPHAMPLITUDE;
  40620. var height = this.DEBUGCANVASSIZE.height * percent;
  40621. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  40622. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  40623. var hue = i / this.getFrequencyBinCount() * 360;
  40624. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  40625. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  40626. }
  40627. }
  40628. }
  40629. };
  40630. Analyser.prototype.stopDebugCanvas = function () {
  40631. if (this._debugCanvas) {
  40632. this._scene.unregisterBeforeRender(this._registerFunc);
  40633. this._registerFunc = null;
  40634. document.body.removeChild(this._debugCanvas);
  40635. this._debugCanvas = null;
  40636. this._debugCanvasContext = null;
  40637. }
  40638. };
  40639. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  40640. if (this._audioEngine.canUseWebAudio) {
  40641. inputAudioNode.connect(this._webAudioAnalyser);
  40642. this._webAudioAnalyser.connect(outputAudioNode);
  40643. }
  40644. };
  40645. Analyser.prototype.dispose = function () {
  40646. if (this._audioEngine.canUseWebAudio) {
  40647. this._webAudioAnalyser.disconnect();
  40648. }
  40649. };
  40650. return Analyser;
  40651. }());
  40652. BABYLON.Analyser = Analyser;
  40653. })(BABYLON || (BABYLON = {}));
  40654. //# sourceMappingURL=babylon.analyser.js.map
  40655. var BABYLON;
  40656. (function (BABYLON) {
  40657. var CubeTexture = (function (_super) {
  40658. __extends(CubeTexture, _super);
  40659. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format) {
  40660. if (onLoad === void 0) { onLoad = null; }
  40661. if (onError === void 0) { onError = null; }
  40662. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  40663. var _this = _super.call(this, scene) || this;
  40664. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  40665. _this.name = rootUrl;
  40666. _this.url = rootUrl;
  40667. _this._noMipmap = noMipmap;
  40668. _this.hasAlpha = false;
  40669. _this._format = format;
  40670. if (!rootUrl && !files) {
  40671. return _this;
  40672. }
  40673. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  40674. if (!files) {
  40675. if (!extensions) {
  40676. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  40677. }
  40678. files = [];
  40679. for (var index = 0; index < extensions.length; index++) {
  40680. files.push(rootUrl + extensions[index]);
  40681. }
  40682. _this._extensions = extensions;
  40683. }
  40684. _this._files = files;
  40685. if (!_this._texture) {
  40686. if (!scene.useDelayedTextureLoading) {
  40687. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format);
  40688. }
  40689. else {
  40690. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40691. }
  40692. }
  40693. else if (onLoad) {
  40694. if (_this._texture.isReady) {
  40695. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  40696. }
  40697. else {
  40698. _this._texture.onLoadedCallbacks.push(onLoad);
  40699. }
  40700. }
  40701. _this.isCube = true;
  40702. _this._textureMatrix = BABYLON.Matrix.Identity();
  40703. return _this;
  40704. }
  40705. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  40706. return new CubeTexture("", scene, null, noMipmap, files);
  40707. };
  40708. // Methods
  40709. CubeTexture.prototype.delayLoad = function () {
  40710. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  40711. return;
  40712. }
  40713. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40714. this._texture = this._getFromCache(this.url, this._noMipmap);
  40715. if (!this._texture) {
  40716. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  40717. }
  40718. };
  40719. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  40720. return this._textureMatrix;
  40721. };
  40722. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  40723. var texture = BABYLON.SerializationHelper.Parse(function () {
  40724. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  40725. }, parsedTexture, scene);
  40726. // Animations
  40727. if (parsedTexture.animations) {
  40728. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  40729. var parsedAnimation = parsedTexture.animations[animationIndex];
  40730. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  40731. }
  40732. }
  40733. return texture;
  40734. };
  40735. CubeTexture.prototype.clone = function () {
  40736. var _this = this;
  40737. return BABYLON.SerializationHelper.Clone(function () {
  40738. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  40739. }, this);
  40740. };
  40741. return CubeTexture;
  40742. }(BABYLON.BaseTexture));
  40743. BABYLON.CubeTexture = CubeTexture;
  40744. })(BABYLON || (BABYLON = {}));
  40745. //# sourceMappingURL=babylon.cubeTexture.js.map
  40746. var BABYLON;
  40747. (function (BABYLON) {
  40748. var RenderTargetTexture = (function (_super) {
  40749. __extends(RenderTargetTexture, _super);
  40750. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  40751. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  40752. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  40753. if (isCube === void 0) { isCube = false; }
  40754. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40755. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  40756. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  40757. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  40758. _this.isCube = isCube;
  40759. /**
  40760. * Use this list to define the list of mesh you want to render.
  40761. */
  40762. _this.renderList = new Array();
  40763. _this.renderParticles = true;
  40764. _this.renderSprites = false;
  40765. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  40766. // Events
  40767. /**
  40768. * An event triggered when the texture is unbind.
  40769. * @type {BABYLON.Observable}
  40770. */
  40771. _this.onAfterUnbindObservable = new BABYLON.Observable();
  40772. /**
  40773. * An event triggered before rendering the texture
  40774. * @type {BABYLON.Observable}
  40775. */
  40776. _this.onBeforeRenderObservable = new BABYLON.Observable();
  40777. /**
  40778. * An event triggered after rendering the texture
  40779. * @type {BABYLON.Observable}
  40780. */
  40781. _this.onAfterRenderObservable = new BABYLON.Observable();
  40782. /**
  40783. * An event triggered after the texture clear
  40784. * @type {BABYLON.Observable}
  40785. */
  40786. _this.onClearObservable = new BABYLON.Observable();
  40787. _this._currentRefreshId = -1;
  40788. _this._refreshRate = 1;
  40789. _this._samples = 1;
  40790. _this.name = name;
  40791. _this.isRenderTarget = true;
  40792. _this._size = size;
  40793. _this._generateMipMaps = generateMipMaps;
  40794. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  40795. _this._renderTargetOptions = {
  40796. generateMipMaps: generateMipMaps,
  40797. type: type,
  40798. samplingMode: samplingMode,
  40799. generateDepthBuffer: generateDepthBuffer,
  40800. generateStencilBuffer: generateStencilBuffer
  40801. };
  40802. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  40803. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40804. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40805. }
  40806. if (isCube) {
  40807. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  40808. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  40809. _this._textureMatrix = BABYLON.Matrix.Identity();
  40810. }
  40811. else {
  40812. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  40813. }
  40814. // Rendering groups
  40815. _this._renderingManager = new BABYLON.RenderingManager(scene);
  40816. return _this;
  40817. }
  40818. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  40819. get: function () {
  40820. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  40821. },
  40822. enumerable: true,
  40823. configurable: true
  40824. });
  40825. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  40826. get: function () {
  40827. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  40828. },
  40829. enumerable: true,
  40830. configurable: true
  40831. });
  40832. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  40833. get: function () {
  40834. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  40835. },
  40836. enumerable: true,
  40837. configurable: true
  40838. });
  40839. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  40840. set: function (callback) {
  40841. if (this._onAfterUnbindObserver) {
  40842. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  40843. }
  40844. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  40845. },
  40846. enumerable: true,
  40847. configurable: true
  40848. });
  40849. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  40850. set: function (callback) {
  40851. if (this._onBeforeRenderObserver) {
  40852. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  40853. }
  40854. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  40855. },
  40856. enumerable: true,
  40857. configurable: true
  40858. });
  40859. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  40860. set: function (callback) {
  40861. if (this._onAfterRenderObserver) {
  40862. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  40863. }
  40864. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  40865. },
  40866. enumerable: true,
  40867. configurable: true
  40868. });
  40869. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  40870. set: function (callback) {
  40871. if (this._onClearObserver) {
  40872. this.onClearObservable.remove(this._onClearObserver);
  40873. }
  40874. this._onClearObserver = this.onClearObservable.add(callback);
  40875. },
  40876. enumerable: true,
  40877. configurable: true
  40878. });
  40879. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  40880. get: function () {
  40881. return this._samples;
  40882. },
  40883. set: function (value) {
  40884. if (this._samples === value) {
  40885. return;
  40886. }
  40887. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  40888. },
  40889. enumerable: true,
  40890. configurable: true
  40891. });
  40892. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  40893. this._currentRefreshId = -1;
  40894. };
  40895. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  40896. get: function () {
  40897. return this._refreshRate;
  40898. },
  40899. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  40900. set: function (value) {
  40901. this._refreshRate = value;
  40902. this.resetRefreshCounter();
  40903. },
  40904. enumerable: true,
  40905. configurable: true
  40906. });
  40907. RenderTargetTexture.prototype._shouldRender = function () {
  40908. if (this._currentRefreshId === -1) {
  40909. this._currentRefreshId = 1;
  40910. return true;
  40911. }
  40912. if (this.refreshRate === this._currentRefreshId) {
  40913. this._currentRefreshId = 1;
  40914. return true;
  40915. }
  40916. this._currentRefreshId++;
  40917. return false;
  40918. };
  40919. RenderTargetTexture.prototype.isReady = function () {
  40920. if (!this.getScene().renderTargetsEnabled) {
  40921. return false;
  40922. }
  40923. return _super.prototype.isReady.call(this);
  40924. };
  40925. RenderTargetTexture.prototype.getRenderSize = function () {
  40926. return this._size;
  40927. };
  40928. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  40929. get: function () {
  40930. return true;
  40931. },
  40932. enumerable: true,
  40933. configurable: true
  40934. });
  40935. RenderTargetTexture.prototype.scale = function (ratio) {
  40936. var newSize = this._size * ratio;
  40937. this.resize(newSize);
  40938. };
  40939. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  40940. if (this.isCube) {
  40941. return this._textureMatrix;
  40942. }
  40943. return _super.prototype.getReflectionTextureMatrix.call(this);
  40944. };
  40945. RenderTargetTexture.prototype.resize = function (size) {
  40946. this.releaseInternalTexture();
  40947. if (this.isCube) {
  40948. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  40949. }
  40950. else {
  40951. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  40952. }
  40953. };
  40954. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  40955. var scene = this.getScene();
  40956. var engine = scene.getEngine();
  40957. if (this.useCameraPostProcesses !== undefined) {
  40958. useCameraPostProcess = this.useCameraPostProcesses;
  40959. }
  40960. if (this._waitingRenderList) {
  40961. this.renderList = [];
  40962. for (var index = 0; index < this._waitingRenderList.length; index++) {
  40963. var id = this._waitingRenderList[index];
  40964. this.renderList.push(scene.getMeshByID(id));
  40965. }
  40966. delete this._waitingRenderList;
  40967. }
  40968. // Is predicate defined?
  40969. if (this.renderListPredicate) {
  40970. this.renderList.splice(0); // Clear previous renderList
  40971. var sceneMeshes = this.getScene().meshes;
  40972. for (var index = 0; index < sceneMeshes.length; index++) {
  40973. var mesh = sceneMeshes[index];
  40974. if (this.renderListPredicate(mesh)) {
  40975. this.renderList.push(mesh);
  40976. }
  40977. }
  40978. }
  40979. if (this.renderList && this.renderList.length === 0) {
  40980. return;
  40981. }
  40982. // Set custom projection.
  40983. // Needs to be before binding to prevent changing the aspect ratio.
  40984. if (this.activeCamera) {
  40985. engine.setViewport(this.activeCamera.viewport);
  40986. if (this.activeCamera !== scene.activeCamera) {
  40987. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  40988. }
  40989. }
  40990. else {
  40991. engine.setViewport(scene.activeCamera.viewport);
  40992. }
  40993. // Prepare renderingManager
  40994. this._renderingManager.reset();
  40995. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  40996. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  40997. var sceneRenderId = scene.getRenderId();
  40998. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  40999. var mesh = currentRenderList[meshIndex];
  41000. if (mesh) {
  41001. if (!mesh.isReady()) {
  41002. // Reset _currentRefreshId
  41003. this.resetRefreshCounter();
  41004. continue;
  41005. }
  41006. mesh._preActivateForIntermediateRendering(sceneRenderId);
  41007. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  41008. mesh._activate(sceneRenderId);
  41009. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  41010. var subMesh = mesh.subMeshes[subIndex];
  41011. scene._activeIndices.addCount(subMesh.indexCount, false);
  41012. this._renderingManager.dispatch(subMesh);
  41013. }
  41014. }
  41015. }
  41016. }
  41017. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  41018. var particleSystem = scene.particleSystems[particleIndex];
  41019. if (!particleSystem.isStarted() || !particleSystem.emitter || !particleSystem.emitter.position || !particleSystem.emitter.isEnabled()) {
  41020. continue;
  41021. }
  41022. if (currentRenderList.indexOf(particleSystem.emitter) >= 0) {
  41023. this._renderingManager.dispatchParticles(particleSystem);
  41024. }
  41025. }
  41026. if (this.isCube) {
  41027. for (var face = 0; face < 6; face++) {
  41028. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  41029. scene.incrementRenderId();
  41030. scene.resetCachedMaterial();
  41031. }
  41032. }
  41033. else {
  41034. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  41035. }
  41036. this.onAfterUnbindObservable.notifyObservers(this);
  41037. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  41038. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  41039. }
  41040. engine.setViewport(scene.activeCamera.viewport);
  41041. scene.resetCachedMaterial();
  41042. };
  41043. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  41044. var _this = this;
  41045. var scene = this.getScene();
  41046. var engine = scene.getEngine();
  41047. // Bind
  41048. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  41049. if (this.isCube) {
  41050. engine.bindFramebuffer(this._texture, faceIndex);
  41051. }
  41052. else {
  41053. engine.bindFramebuffer(this._texture);
  41054. }
  41055. }
  41056. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  41057. // Clear
  41058. if (this.onClearObservable.hasObservers()) {
  41059. this.onClearObservable.notifyObservers(engine);
  41060. }
  41061. else {
  41062. engine.clear(scene.clearColor, true, true, true);
  41063. }
  41064. if (!this._doNotChangeAspectRatio) {
  41065. scene.updateTransformMatrix(true);
  41066. }
  41067. // Render
  41068. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  41069. if (useCameraPostProcess) {
  41070. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  41071. }
  41072. if (!this._doNotChangeAspectRatio) {
  41073. scene.updateTransformMatrix(true);
  41074. }
  41075. // Dump ?
  41076. if (dumpForDebug) {
  41077. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  41078. }
  41079. // Unbind
  41080. if (!this.isCube || faceIndex === 5) {
  41081. if (this.isCube) {
  41082. if (faceIndex === 5) {
  41083. engine.generateMipMapsForCubemap(this._texture);
  41084. }
  41085. }
  41086. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  41087. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  41088. });
  41089. }
  41090. else {
  41091. this.onAfterRenderObservable.notifyObservers(faceIndex);
  41092. }
  41093. };
  41094. /**
  41095. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  41096. * This allowed control for front to back rendering or reversly depending of the special needs.
  41097. *
  41098. * @param renderingGroupId The rendering group id corresponding to its index
  41099. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  41100. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  41101. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  41102. */
  41103. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  41104. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  41105. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  41106. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  41107. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  41108. };
  41109. /**
  41110. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  41111. *
  41112. * @param renderingGroupId The rendering group id corresponding to its index
  41113. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  41114. */
  41115. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  41116. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  41117. };
  41118. RenderTargetTexture.prototype.clone = function () {
  41119. var textureSize = this.getSize();
  41120. 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);
  41121. // Base texture
  41122. newTexture.hasAlpha = this.hasAlpha;
  41123. newTexture.level = this.level;
  41124. // RenderTarget Texture
  41125. newTexture.coordinatesMode = this.coordinatesMode;
  41126. newTexture.renderList = this.renderList.slice(0);
  41127. return newTexture;
  41128. };
  41129. RenderTargetTexture.prototype.serialize = function () {
  41130. if (!this.name) {
  41131. return null;
  41132. }
  41133. var serializationObject = _super.prototype.serialize.call(this);
  41134. serializationObject.renderTargetSize = this.getRenderSize();
  41135. serializationObject.renderList = [];
  41136. for (var index = 0; index < this.renderList.length; index++) {
  41137. serializationObject.renderList.push(this.renderList[index].id);
  41138. }
  41139. return serializationObject;
  41140. };
  41141. return RenderTargetTexture;
  41142. }(BABYLON.Texture));
  41143. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  41144. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  41145. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  41146. BABYLON.RenderTargetTexture = RenderTargetTexture;
  41147. })(BABYLON || (BABYLON = {}));
  41148. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  41149. /// <reference path="babylon.renderTargetTexture.ts" />
  41150. var BABYLON;
  41151. (function (BABYLON) {
  41152. var MirrorTexture = (function (_super) {
  41153. __extends(MirrorTexture, _super);
  41154. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  41155. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41156. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  41157. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  41158. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  41159. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  41160. _this._transformMatrix = BABYLON.Matrix.Zero();
  41161. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  41162. _this.onBeforeRenderObservable.add(function () {
  41163. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  41164. _this._savedViewMatrix = scene.getViewMatrix();
  41165. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  41166. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  41167. scene.clipPlane = _this.mirrorPlane;
  41168. scene.getEngine().cullBackFaces = false;
  41169. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  41170. });
  41171. _this.onAfterRenderObservable.add(function () {
  41172. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  41173. scene.getEngine().cullBackFaces = true;
  41174. scene._mirroredCameraPosition = null;
  41175. delete scene.clipPlane;
  41176. });
  41177. return _this;
  41178. }
  41179. MirrorTexture.prototype.clone = function () {
  41180. var textureSize = this.getSize();
  41181. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  41182. // Base texture
  41183. newTexture.hasAlpha = this.hasAlpha;
  41184. newTexture.level = this.level;
  41185. // Mirror Texture
  41186. newTexture.mirrorPlane = this.mirrorPlane.clone();
  41187. newTexture.renderList = this.renderList.slice(0);
  41188. return newTexture;
  41189. };
  41190. MirrorTexture.prototype.serialize = function () {
  41191. if (!this.name) {
  41192. return null;
  41193. }
  41194. var serializationObject = _super.prototype.serialize.call(this);
  41195. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  41196. return serializationObject;
  41197. };
  41198. return MirrorTexture;
  41199. }(BABYLON.RenderTargetTexture));
  41200. BABYLON.MirrorTexture = MirrorTexture;
  41201. })(BABYLON || (BABYLON = {}));
  41202. //# sourceMappingURL=babylon.mirrorTexture.js.map
  41203. /// <reference path="babylon.renderTargetTexture.ts" />
  41204. var BABYLON;
  41205. (function (BABYLON) {
  41206. /**
  41207. * Creates a refraction texture used by refraction channel of the standard material.
  41208. * @param name the texture name
  41209. * @param size size of the underlying texture
  41210. * @param scene root scene
  41211. */
  41212. var RefractionTexture = (function (_super) {
  41213. __extends(RefractionTexture, _super);
  41214. function RefractionTexture(name, size, scene, generateMipMaps) {
  41215. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  41216. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  41217. _this.depth = 2.0;
  41218. _this.onBeforeRenderObservable.add(function () {
  41219. scene.clipPlane = _this.refractionPlane;
  41220. });
  41221. _this.onAfterRenderObservable.add(function () {
  41222. delete scene.clipPlane;
  41223. });
  41224. return _this;
  41225. }
  41226. RefractionTexture.prototype.clone = function () {
  41227. var textureSize = this.getSize();
  41228. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  41229. // Base texture
  41230. newTexture.hasAlpha = this.hasAlpha;
  41231. newTexture.level = this.level;
  41232. // Refraction Texture
  41233. newTexture.refractionPlane = this.refractionPlane.clone();
  41234. newTexture.renderList = this.renderList.slice(0);
  41235. newTexture.depth = this.depth;
  41236. return newTexture;
  41237. };
  41238. RefractionTexture.prototype.serialize = function () {
  41239. if (!this.name) {
  41240. return null;
  41241. }
  41242. var serializationObject = _super.prototype.serialize.call(this);
  41243. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  41244. serializationObject.depth = this.depth;
  41245. return serializationObject;
  41246. };
  41247. return RefractionTexture;
  41248. }(BABYLON.RenderTargetTexture));
  41249. BABYLON.RefractionTexture = RefractionTexture;
  41250. })(BABYLON || (BABYLON = {}));
  41251. //# sourceMappingURL=babylon.refractionTexture.js.map
  41252. /// <reference path="babylon.texture.ts" />
  41253. var BABYLON;
  41254. (function (BABYLON) {
  41255. var DynamicTexture = (function (_super) {
  41256. __extends(DynamicTexture, _super);
  41257. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  41258. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41259. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  41260. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  41261. _this.name = name;
  41262. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41263. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41264. _this._generateMipMaps = generateMipMaps;
  41265. if (options.getContext) {
  41266. _this._canvas = options;
  41267. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  41268. }
  41269. else {
  41270. _this._canvas = document.createElement("canvas");
  41271. if (options.width) {
  41272. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  41273. }
  41274. else {
  41275. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  41276. }
  41277. }
  41278. var textureSize = _this.getSize();
  41279. _this._canvas.width = textureSize.width;
  41280. _this._canvas.height = textureSize.height;
  41281. _this._context = _this._canvas.getContext("2d");
  41282. return _this;
  41283. }
  41284. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  41285. get: function () {
  41286. return true;
  41287. },
  41288. enumerable: true,
  41289. configurable: true
  41290. });
  41291. DynamicTexture.prototype.scale = function (ratio) {
  41292. var textureSize = this.getSize();
  41293. textureSize.width *= ratio;
  41294. textureSize.height *= ratio;
  41295. this._canvas.width = textureSize.width;
  41296. this._canvas.height = textureSize.height;
  41297. this.releaseInternalTexture();
  41298. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  41299. };
  41300. DynamicTexture.prototype.getContext = function () {
  41301. return this._context;
  41302. };
  41303. DynamicTexture.prototype.clear = function () {
  41304. var size = this.getSize();
  41305. this._context.fillRect(0, 0, size.width, size.height);
  41306. };
  41307. DynamicTexture.prototype.update = function (invertY) {
  41308. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  41309. };
  41310. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  41311. if (update === void 0) { update = true; }
  41312. var size = this.getSize();
  41313. if (clearColor) {
  41314. this._context.fillStyle = clearColor;
  41315. this._context.fillRect(0, 0, size.width, size.height);
  41316. }
  41317. this._context.font = font;
  41318. if (x === null || x === undefined) {
  41319. var textSize = this._context.measureText(text);
  41320. x = (size.width - textSize.width) / 2;
  41321. }
  41322. if (y === null || y === undefined) {
  41323. var fontSize = parseInt((font.replace(/\D/g, '')));
  41324. ;
  41325. y = (size.height / 2) + (fontSize / 3.65);
  41326. }
  41327. this._context.fillStyle = color;
  41328. this._context.fillText(text, x, y);
  41329. if (update) {
  41330. this.update(invertY);
  41331. }
  41332. };
  41333. DynamicTexture.prototype.clone = function () {
  41334. var textureSize = this.getSize();
  41335. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  41336. // Base texture
  41337. newTexture.hasAlpha = this.hasAlpha;
  41338. newTexture.level = this.level;
  41339. // Dynamic Texture
  41340. newTexture.wrapU = this.wrapU;
  41341. newTexture.wrapV = this.wrapV;
  41342. return newTexture;
  41343. };
  41344. return DynamicTexture;
  41345. }(BABYLON.Texture));
  41346. BABYLON.DynamicTexture = DynamicTexture;
  41347. })(BABYLON || (BABYLON = {}));
  41348. //# sourceMappingURL=babylon.dynamicTexture.js.map
  41349. var BABYLON;
  41350. (function (BABYLON) {
  41351. var VideoTexture = (function (_super) {
  41352. __extends(VideoTexture, _super);
  41353. /**
  41354. * Creates a video texture.
  41355. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  41356. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  41357. * @param {BABYLON.Scene} scene is obviously the current scene.
  41358. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  41359. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  41360. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  41361. */
  41362. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  41363. if (generateMipMaps === void 0) { generateMipMaps = false; }
  41364. if (invertY === void 0) { invertY = false; }
  41365. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41366. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  41367. _this._autoLaunch = true;
  41368. var urls;
  41369. _this.name = name;
  41370. if (urlsOrVideo instanceof HTMLVideoElement) {
  41371. _this.video = urlsOrVideo;
  41372. }
  41373. else {
  41374. urls = urlsOrVideo;
  41375. _this.video = document.createElement("video");
  41376. _this.video.autoplay = false;
  41377. _this.video.loop = true;
  41378. }
  41379. _this._generateMipMaps = generateMipMaps;
  41380. _this._samplingMode = samplingMode;
  41381. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  41382. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  41383. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  41384. }
  41385. else {
  41386. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41387. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41388. _this._generateMipMaps = false;
  41389. }
  41390. if (urls) {
  41391. _this.video.addEventListener("canplay", function () {
  41392. _this._createTexture();
  41393. });
  41394. urls.forEach(function (url) {
  41395. var source = document.createElement("source");
  41396. source.src = url;
  41397. _this.video.appendChild(source);
  41398. });
  41399. }
  41400. else {
  41401. _this._createTexture();
  41402. }
  41403. _this._lastUpdate = BABYLON.Tools.Now;
  41404. return _this;
  41405. }
  41406. VideoTexture.prototype._createTexture = function () {
  41407. var _this = this;
  41408. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  41409. if (this._autoLaunch) {
  41410. this._autoLaunch = false;
  41411. this.video.play();
  41412. }
  41413. this.video.addEventListener("playing", function () {
  41414. _this._texture.isReady = true;
  41415. });
  41416. };
  41417. VideoTexture.prototype.update = function () {
  41418. var now = BABYLON.Tools.Now;
  41419. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  41420. return false;
  41421. }
  41422. this._lastUpdate = now;
  41423. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  41424. return true;
  41425. };
  41426. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  41427. var video = document.createElement("video");
  41428. var constraintsDeviceId;
  41429. if (constraints && constraints.deviceId) {
  41430. constraintsDeviceId = {
  41431. exact: constraints.deviceId
  41432. };
  41433. }
  41434. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  41435. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  41436. if (navigator.getUserMedia) {
  41437. navigator.getUserMedia({
  41438. video: {
  41439. deviceId: constraintsDeviceId,
  41440. width: {
  41441. min: (constraints && constraints.minWidth) || 256,
  41442. max: (constraints && constraints.maxWidth) || 640
  41443. },
  41444. height: {
  41445. min: (constraints && constraints.minHeight) || 256,
  41446. max: (constraints && constraints.maxHeight) || 480
  41447. }
  41448. }
  41449. }, function (stream) {
  41450. if (video.mozSrcObject !== undefined) {
  41451. video.mozSrcObject = stream;
  41452. }
  41453. else {
  41454. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  41455. }
  41456. video.play();
  41457. if (onReady) {
  41458. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  41459. }
  41460. }, function (e) {
  41461. BABYLON.Tools.Error(e.name);
  41462. });
  41463. }
  41464. };
  41465. return VideoTexture;
  41466. }(BABYLON.Texture));
  41467. BABYLON.VideoTexture = VideoTexture;
  41468. })(BABYLON || (BABYLON = {}));
  41469. //# sourceMappingURL=babylon.videoTexture.js.map
  41470. var BABYLON;
  41471. (function (BABYLON) {
  41472. var RawTexture = (function (_super) {
  41473. __extends(RawTexture, _super);
  41474. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  41475. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41476. if (invertY === void 0) { invertY = false; }
  41477. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41478. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  41479. _this.format = format;
  41480. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  41481. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41482. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41483. return _this;
  41484. }
  41485. RawTexture.prototype.update = function (data) {
  41486. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  41487. };
  41488. // Statics
  41489. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41490. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41491. if (invertY === void 0) { invertY = false; }
  41492. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41493. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  41494. };
  41495. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41496. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41497. if (invertY === void 0) { invertY = false; }
  41498. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41499. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  41500. };
  41501. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41502. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41503. if (invertY === void 0) { invertY = false; }
  41504. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41505. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  41506. };
  41507. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41508. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41509. if (invertY === void 0) { invertY = false; }
  41510. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41511. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  41512. };
  41513. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  41514. if (generateMipMaps === void 0) { generateMipMaps = true; }
  41515. if (invertY === void 0) { invertY = false; }
  41516. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41517. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  41518. };
  41519. return RawTexture;
  41520. }(BABYLON.Texture));
  41521. BABYLON.RawTexture = RawTexture;
  41522. })(BABYLON || (BABYLON = {}));
  41523. //# sourceMappingURL=babylon.rawTexture.js.map
  41524. var BABYLON;
  41525. (function (BABYLON) {
  41526. var PostProcess = (function () {
  41527. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  41528. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  41529. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41530. this.name = name;
  41531. this.width = -1;
  41532. this.height = -1;
  41533. /*
  41534. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  41535. Can only be used on a single postprocess or on the last one of a chain.
  41536. */
  41537. this.enablePixelPerfectMode = false;
  41538. this.samples = 1;
  41539. this._reusable = false;
  41540. this._textures = new BABYLON.SmartArray(2);
  41541. this._currentRenderTextureInd = 0;
  41542. this._scaleRatio = new BABYLON.Vector2(1, 1);
  41543. // Events
  41544. /**
  41545. * An event triggered when the postprocess is activated.
  41546. * @type {BABYLON.Observable}
  41547. */
  41548. this.onActivateObservable = new BABYLON.Observable();
  41549. /**
  41550. * An event triggered when the postprocess changes its size.
  41551. * @type {BABYLON.Observable}
  41552. */
  41553. this.onSizeChangedObservable = new BABYLON.Observable();
  41554. /**
  41555. * An event triggered when the postprocess applies its effect.
  41556. * @type {BABYLON.Observable}
  41557. */
  41558. this.onApplyObservable = new BABYLON.Observable();
  41559. /**
  41560. * An event triggered before rendering the postprocess
  41561. * @type {BABYLON.Observable}
  41562. */
  41563. this.onBeforeRenderObservable = new BABYLON.Observable();
  41564. /**
  41565. * An event triggered after rendering the postprocess
  41566. * @type {BABYLON.Observable}
  41567. */
  41568. this.onAfterRenderObservable = new BABYLON.Observable();
  41569. if (camera != null) {
  41570. this._camera = camera;
  41571. this._scene = camera.getScene();
  41572. camera.attachPostProcess(this);
  41573. this._engine = this._scene.getEngine();
  41574. }
  41575. else {
  41576. this._engine = engine;
  41577. }
  41578. this._options = options;
  41579. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  41580. this._reusable = reusable || false;
  41581. this._textureType = textureType;
  41582. this._samplers = samplers || [];
  41583. this._samplers.push("textureSampler");
  41584. this._fragmentUrl = fragmentUrl;
  41585. this._parameters = parameters || [];
  41586. this._parameters.push("scale");
  41587. this.updateEffect(defines);
  41588. }
  41589. Object.defineProperty(PostProcess.prototype, "onActivate", {
  41590. set: function (callback) {
  41591. if (this._onActivateObserver) {
  41592. this.onActivateObservable.remove(this._onActivateObserver);
  41593. }
  41594. this._onActivateObserver = this.onActivateObservable.add(callback);
  41595. },
  41596. enumerable: true,
  41597. configurable: true
  41598. });
  41599. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  41600. set: function (callback) {
  41601. if (this._onSizeChangedObserver) {
  41602. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  41603. }
  41604. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  41605. },
  41606. enumerable: true,
  41607. configurable: true
  41608. });
  41609. Object.defineProperty(PostProcess.prototype, "onApply", {
  41610. set: function (callback) {
  41611. if (this._onApplyObserver) {
  41612. this.onApplyObservable.remove(this._onApplyObserver);
  41613. }
  41614. this._onApplyObserver = this.onApplyObservable.add(callback);
  41615. },
  41616. enumerable: true,
  41617. configurable: true
  41618. });
  41619. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  41620. set: function (callback) {
  41621. if (this._onBeforeRenderObserver) {
  41622. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  41623. }
  41624. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  41625. },
  41626. enumerable: true,
  41627. configurable: true
  41628. });
  41629. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  41630. set: function (callback) {
  41631. if (this._onAfterRenderObserver) {
  41632. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  41633. }
  41634. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  41635. },
  41636. enumerable: true,
  41637. configurable: true
  41638. });
  41639. PostProcess.prototype.updateEffect = function (defines) {
  41640. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  41641. };
  41642. PostProcess.prototype.isReusable = function () {
  41643. return this._reusable;
  41644. };
  41645. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  41646. PostProcess.prototype.markTextureDirty = function () {
  41647. this.width = -1;
  41648. };
  41649. PostProcess.prototype.activate = function (camera, sourceTexture) {
  41650. var _this = this;
  41651. camera = camera || this._camera;
  41652. var scene = camera.getScene();
  41653. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  41654. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  41655. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  41656. var desiredWidth = this._options.width || requiredWidth;
  41657. var desiredHeight = this._options.height || requiredHeight;
  41658. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  41659. if (!this._options.width) {
  41660. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  41661. }
  41662. if (!this._options.height) {
  41663. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  41664. }
  41665. }
  41666. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  41667. if (this._textures.length > 0) {
  41668. for (var i = 0; i < this._textures.length; i++) {
  41669. this._engine._releaseTexture(this._textures.data[i]);
  41670. }
  41671. this._textures.reset();
  41672. }
  41673. this.width = desiredWidth;
  41674. this.height = desiredHeight;
  41675. var textureSize = { width: this.width, height: this.height };
  41676. var textureOptions = {
  41677. generateMipMaps: false,
  41678. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  41679. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  41680. samplingMode: this.renderTargetSamplingMode,
  41681. type: this._textureType
  41682. };
  41683. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  41684. if (this._reusable) {
  41685. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  41686. }
  41687. this.onSizeChangedObservable.notifyObservers(this);
  41688. }
  41689. this._textures.forEach(function (texture) {
  41690. if (texture.samples !== _this.samples) {
  41691. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  41692. }
  41693. });
  41694. if (this.enablePixelPerfectMode) {
  41695. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  41696. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  41697. }
  41698. else {
  41699. this._scaleRatio.copyFromFloats(1, 1);
  41700. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  41701. }
  41702. this.onActivateObservable.notifyObservers(camera);
  41703. // Clear
  41704. if (this.clearColor) {
  41705. this._engine.clear(this.clearColor, true, true, true);
  41706. }
  41707. else {
  41708. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  41709. }
  41710. if (this._reusable) {
  41711. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  41712. }
  41713. };
  41714. Object.defineProperty(PostProcess.prototype, "isSupported", {
  41715. get: function () {
  41716. return this._effect.isSupported;
  41717. },
  41718. enumerable: true,
  41719. configurable: true
  41720. });
  41721. PostProcess.prototype.apply = function () {
  41722. // Check
  41723. if (!this._effect.isReady())
  41724. return null;
  41725. // States
  41726. this._engine.enableEffect(this._effect);
  41727. this._engine.setState(false);
  41728. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  41729. this._engine.setDepthBuffer(false);
  41730. this._engine.setDepthWrite(false);
  41731. // Texture
  41732. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  41733. // Parameters
  41734. this._effect.setVector2("scale", this._scaleRatio);
  41735. this.onApplyObservable.notifyObservers(this._effect);
  41736. return this._effect;
  41737. };
  41738. PostProcess.prototype.dispose = function (camera) {
  41739. camera = camera || this._camera;
  41740. if (this._textures.length > 0) {
  41741. for (var i = 0; i < this._textures.length; i++) {
  41742. this._engine._releaseTexture(this._textures.data[i]);
  41743. }
  41744. }
  41745. this._textures.dispose();
  41746. if (!camera) {
  41747. return;
  41748. }
  41749. camera.detachPostProcess(this);
  41750. var index = camera._postProcesses.indexOf(this);
  41751. if (index === 0 && camera._postProcesses.length > 0) {
  41752. this._camera._postProcesses[0].markTextureDirty();
  41753. }
  41754. this.onActivateObservable.clear();
  41755. this.onAfterRenderObservable.clear();
  41756. this.onApplyObservable.clear();
  41757. this.onBeforeRenderObservable.clear();
  41758. this.onSizeChangedObservable.clear();
  41759. };
  41760. return PostProcess;
  41761. }());
  41762. BABYLON.PostProcess = PostProcess;
  41763. })(BABYLON || (BABYLON = {}));
  41764. //# sourceMappingURL=babylon.postProcess.js.map
  41765. var BABYLON;
  41766. (function (BABYLON) {
  41767. var PassPostProcess = (function (_super) {
  41768. __extends(PassPostProcess, _super);
  41769. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  41770. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  41771. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  41772. }
  41773. return PassPostProcess;
  41774. }(BABYLON.PostProcess));
  41775. BABYLON.PassPostProcess = PassPostProcess;
  41776. })(BABYLON || (BABYLON = {}));
  41777. //# sourceMappingURL=babylon.passPostProcess.js.map
  41778. var BABYLON;
  41779. (function (BABYLON) {
  41780. var ShadowGenerator = (function () {
  41781. /**
  41782. * Creates a ShadowGenerator object.
  41783. * A ShadowGenerator is the required tool to use the shadows.
  41784. * Each light casting shadows needs to use its own ShadowGenerator.
  41785. * Required parameters :
  41786. * - `mapSize` (integer), the size of the texture what stores the shadows. Example : 1024.
  41787. * - `light` : the light object generating the shadows.
  41788. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  41789. */
  41790. function ShadowGenerator(mapSize, light) {
  41791. var _this = this;
  41792. // Members
  41793. this._filter = ShadowGenerator.FILTER_NONE;
  41794. this.blurScale = 2;
  41795. this._blurBoxOffset = 0;
  41796. this._bias = 0.00005;
  41797. this._lightDirection = BABYLON.Vector3.Zero();
  41798. this.forceBackFacesOnly = false;
  41799. this._darkness = 0;
  41800. this._transparencyShadow = false;
  41801. this._viewMatrix = BABYLON.Matrix.Zero();
  41802. this._projectionMatrix = BABYLON.Matrix.Zero();
  41803. this._transformMatrix = BABYLON.Matrix.Zero();
  41804. this._worldViewProjection = BABYLON.Matrix.Zero();
  41805. this._currentFaceIndex = 0;
  41806. this._currentFaceIndexCache = 0;
  41807. this._useFullFloat = true;
  41808. this._light = light;
  41809. this._scene = light.getScene();
  41810. this._mapSize = mapSize;
  41811. light._shadowGenerator = this;
  41812. light._markMeshesAsLightDirty();
  41813. // Texture type fallback from float to int if not supported.
  41814. var textureType;
  41815. var caps = this._scene.getEngine().getCaps();
  41816. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  41817. this._useFullFloat = true;
  41818. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  41819. }
  41820. else {
  41821. this._useFullFloat = false;
  41822. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  41823. }
  41824. // Render target
  41825. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  41826. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41827. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41828. this._shadowMap.anisotropicFilteringLevel = 1;
  41829. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41830. this._shadowMap.renderParticles = false;
  41831. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  41832. _this._currentFaceIndex = faceIndex;
  41833. });
  41834. this._shadowMap.onAfterUnbindObservable.add(function () {
  41835. if (!_this.useBlurExponentialShadowMap) {
  41836. return;
  41837. }
  41838. if (!_this._shadowMap2) {
  41839. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  41840. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41841. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41842. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41843. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine(), false, textureType);
  41844. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  41845. effect.setTexture("textureSampler", _this._shadowMap);
  41846. });
  41847. _this.blurBoxOffset = 1;
  41848. }
  41849. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  41850. });
  41851. // Custom render function
  41852. var renderSubMesh = function (subMesh) {
  41853. var mesh = subMesh.getRenderingMesh();
  41854. var scene = _this._scene;
  41855. var engine = scene.getEngine();
  41856. // Culling
  41857. engine.setState(subMesh.getMaterial().backFaceCulling);
  41858. // Managing instances
  41859. var batch = mesh._getInstancesRenderList(subMesh._id);
  41860. if (batch.mustReturn) {
  41861. return;
  41862. }
  41863. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  41864. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  41865. engine.enableEffect(_this._effect);
  41866. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  41867. var material = subMesh.getMaterial();
  41868. _this._effect.setFloat2("biasAndScale", _this.bias, _this.depthScale);
  41869. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  41870. _this._effect.setVector3("lightPosition", _this.getLight().position);
  41871. if (_this.getLight().needCube()) {
  41872. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  41873. }
  41874. // Alpha test
  41875. if (material && material.needAlphaTesting()) {
  41876. var alphaTexture = material.getAlphaTestTexture();
  41877. _this._effect.setTexture("diffuseSampler", alphaTexture);
  41878. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  41879. }
  41880. // Bones
  41881. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  41882. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  41883. }
  41884. if (_this.forceBackFacesOnly) {
  41885. engine.setState(true, 0, false, true);
  41886. }
  41887. // Draw
  41888. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  41889. if (_this.forceBackFacesOnly) {
  41890. engine.setState(true, 0, false, false);
  41891. }
  41892. }
  41893. else {
  41894. // Need to reset refresh rate of the shadowMap
  41895. _this._shadowMap.resetRefreshCounter();
  41896. }
  41897. };
  41898. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  41899. var index;
  41900. for (index = 0; index < opaqueSubMeshes.length; index++) {
  41901. renderSubMesh(opaqueSubMeshes.data[index]);
  41902. }
  41903. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  41904. renderSubMesh(alphaTestSubMeshes.data[index]);
  41905. }
  41906. if (_this._transparencyShadow) {
  41907. for (index = 0; index < transparentSubMeshes.length; index++) {
  41908. renderSubMesh(transparentSubMeshes.data[index]);
  41909. }
  41910. }
  41911. };
  41912. this._shadowMap.onClearObservable.add(function (engine) {
  41913. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  41914. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  41915. }
  41916. else {
  41917. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  41918. }
  41919. });
  41920. }
  41921. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  41922. // Static
  41923. get: function () {
  41924. return ShadowGenerator._FILTER_NONE;
  41925. },
  41926. enumerable: true,
  41927. configurable: true
  41928. });
  41929. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  41930. get: function () {
  41931. return ShadowGenerator._FILTER_POISSONSAMPLING;
  41932. },
  41933. enumerable: true,
  41934. configurable: true
  41935. });
  41936. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  41937. get: function () {
  41938. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  41939. },
  41940. enumerable: true,
  41941. configurable: true
  41942. });
  41943. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  41944. get: function () {
  41945. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  41946. },
  41947. enumerable: true,
  41948. configurable: true
  41949. });
  41950. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  41951. get: function () {
  41952. return this._bias;
  41953. },
  41954. set: function (bias) {
  41955. this._bias = bias;
  41956. },
  41957. enumerable: true,
  41958. configurable: true
  41959. });
  41960. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  41961. get: function () {
  41962. return this._blurBoxOffset;
  41963. },
  41964. set: function (value) {
  41965. var _this = this;
  41966. if (this._blurBoxOffset === value) {
  41967. return;
  41968. }
  41969. this._blurBoxOffset = value;
  41970. if (this._boxBlurPostprocess) {
  41971. this._boxBlurPostprocess.dispose();
  41972. }
  41973. var textureType;
  41974. var caps = this._scene.getEngine().getCaps();
  41975. if (this._useFullFloat) {
  41976. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  41977. }
  41978. else {
  41979. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  41980. }
  41981. 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);
  41982. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  41983. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  41984. });
  41985. },
  41986. enumerable: true,
  41987. configurable: true
  41988. });
  41989. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  41990. get: function () {
  41991. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  41992. },
  41993. set: function (value) {
  41994. this._depthScale = value;
  41995. },
  41996. enumerable: true,
  41997. configurable: true
  41998. });
  41999. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  42000. get: function () {
  42001. return this._filter;
  42002. },
  42003. set: function (value) {
  42004. if (this._filter === value) {
  42005. return;
  42006. }
  42007. this._filter = value;
  42008. if (this.usePoissonSampling || this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  42009. this._shadowMap.anisotropicFilteringLevel = 16;
  42010. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  42011. }
  42012. else {
  42013. this._shadowMap.anisotropicFilteringLevel = 1;
  42014. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  42015. }
  42016. this._light._markMeshesAsLightDirty();
  42017. },
  42018. enumerable: true,
  42019. configurable: true
  42020. });
  42021. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  42022. get: function () {
  42023. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  42024. return this.useExponentialShadowMap;
  42025. },
  42026. set: function (value) {
  42027. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  42028. this.useExponentialShadowMap = value;
  42029. },
  42030. enumerable: true,
  42031. configurable: true
  42032. });
  42033. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  42034. get: function () {
  42035. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  42036. },
  42037. set: function (value) {
  42038. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  42039. },
  42040. enumerable: true,
  42041. configurable: true
  42042. });
  42043. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  42044. get: function () {
  42045. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  42046. },
  42047. set: function (value) {
  42048. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  42049. },
  42050. enumerable: true,
  42051. configurable: true
  42052. });
  42053. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  42054. get: function () {
  42055. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  42056. return this.useBlurExponentialShadowMap;
  42057. },
  42058. set: function (value) {
  42059. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  42060. this.useBlurExponentialShadowMap = value;
  42061. },
  42062. enumerable: true,
  42063. configurable: true
  42064. });
  42065. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  42066. get: function () {
  42067. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  42068. },
  42069. set: function (value) {
  42070. if (this._light.needCube() && value) {
  42071. this.useExponentialShadowMap = true; // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  42072. }
  42073. else {
  42074. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  42075. }
  42076. },
  42077. enumerable: true,
  42078. configurable: true
  42079. });
  42080. /**
  42081. * Boolean : true when the ShadowGenerator is finally computed.
  42082. */
  42083. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  42084. var defines = [];
  42085. if (this._useFullFloat) {
  42086. defines.push("#define FULLFLOAT");
  42087. }
  42088. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  42089. defines.push("#define ESM");
  42090. }
  42091. if (this.getLight().needCube()) {
  42092. defines.push("#define CUBEMAP");
  42093. }
  42094. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42095. var mesh = subMesh.getMesh();
  42096. var material = subMesh.getMaterial();
  42097. // Alpha test
  42098. if (material && material.needAlphaTesting()) {
  42099. defines.push("#define ALPHATEST");
  42100. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  42101. attribs.push(BABYLON.VertexBuffer.UVKind);
  42102. defines.push("#define UV1");
  42103. }
  42104. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  42105. var alphaTexture = material.getAlphaTestTexture();
  42106. if (alphaTexture.coordinatesIndex === 1) {
  42107. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42108. defines.push("#define UV2");
  42109. }
  42110. }
  42111. }
  42112. // Bones
  42113. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  42114. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42115. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42116. if (mesh.numBoneInfluencers > 4) {
  42117. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42118. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42119. }
  42120. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  42121. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  42122. }
  42123. else {
  42124. defines.push("#define NUM_BONE_INFLUENCERS 0");
  42125. }
  42126. // Instances
  42127. if (useInstances) {
  42128. defines.push("#define INSTANCES");
  42129. attribs.push("world0");
  42130. attribs.push("world1");
  42131. attribs.push("world2");
  42132. attribs.push("world3");
  42133. }
  42134. // Get correct effect
  42135. var join = defines.join("\n");
  42136. if (this._cachedDefines !== join) {
  42137. this._cachedDefines = join;
  42138. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  42139. }
  42140. return this._effect.isReady();
  42141. };
  42142. /**
  42143. * Returns a RenderTargetTexture object : the shadow map texture.
  42144. */
  42145. ShadowGenerator.prototype.getShadowMap = function () {
  42146. return this._shadowMap;
  42147. };
  42148. /**
  42149. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  42150. */
  42151. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  42152. if (this._shadowMap2) {
  42153. return this._shadowMap2;
  42154. }
  42155. return this._shadowMap;
  42156. };
  42157. /**
  42158. * Returns the associated light object.
  42159. */
  42160. ShadowGenerator.prototype.getLight = function () {
  42161. return this._light;
  42162. };
  42163. // Methods
  42164. /**
  42165. * Returns a Matrix object : the updated transformation matrix.
  42166. */
  42167. ShadowGenerator.prototype.getTransformMatrix = function () {
  42168. var scene = this._scene;
  42169. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  42170. return this._transformMatrix;
  42171. }
  42172. this._currentRenderID = scene.getRenderId();
  42173. this._currentFaceIndexCache = this._currentFaceIndex;
  42174. var lightPosition = this._light.position;
  42175. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  42176. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  42177. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  42178. }
  42179. if (this._light.computeTransformedPosition()) {
  42180. lightPosition = this._light.transformedPosition;
  42181. }
  42182. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  42183. this._cachedPosition = lightPosition.clone();
  42184. this._cachedDirection = this._lightDirection.clone();
  42185. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  42186. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  42187. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  42188. }
  42189. return this._transformMatrix;
  42190. };
  42191. /**
  42192. * Returns the darkness value (float).
  42193. */
  42194. ShadowGenerator.prototype.getDarkness = function () {
  42195. return this._darkness;
  42196. };
  42197. /**
  42198. * Sets the ShadowGenerator darkness value (float <= 1.0).
  42199. * Returns the ShadowGenerator.
  42200. */
  42201. ShadowGenerator.prototype.setDarkness = function (darkness) {
  42202. if (darkness >= 1.0)
  42203. this._darkness = 1.0;
  42204. else if (darkness <= 0.0)
  42205. this._darkness = 0.0;
  42206. else
  42207. this._darkness = darkness;
  42208. return this;
  42209. };
  42210. /**
  42211. * Sets the ability to have transparent shadow (boolean).
  42212. * Returns the ShadowGenerator.
  42213. */
  42214. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  42215. this._transparencyShadow = hasShadow;
  42216. return this;
  42217. };
  42218. ShadowGenerator.prototype._packHalf = function (depth) {
  42219. var scale = depth * 255.0;
  42220. var fract = scale - Math.floor(scale);
  42221. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  42222. };
  42223. /**
  42224. * Disposes the ShadowGenerator.
  42225. * Returns nothing.
  42226. */
  42227. ShadowGenerator.prototype.dispose = function () {
  42228. this._shadowMap.dispose();
  42229. if (this._shadowMap2) {
  42230. this._shadowMap2.dispose();
  42231. }
  42232. if (this._downSamplePostprocess) {
  42233. this._downSamplePostprocess.dispose();
  42234. }
  42235. if (this._boxBlurPostprocess) {
  42236. this._boxBlurPostprocess.dispose();
  42237. }
  42238. this._light._shadowGenerator = null;
  42239. this._light._markMeshesAsLightDirty();
  42240. };
  42241. /**
  42242. * Serializes the ShadowGenerator and returns a serializationObject.
  42243. */
  42244. ShadowGenerator.prototype.serialize = function () {
  42245. var serializationObject = {};
  42246. serializationObject.lightId = this._light.id;
  42247. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  42248. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  42249. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  42250. serializationObject.usePoissonSampling = this.usePoissonSampling;
  42251. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  42252. serializationObject.depthScale = this.depthScale;
  42253. serializationObject.darkness = this.getDarkness();
  42254. serializationObject.renderList = [];
  42255. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  42256. var mesh = this.getShadowMap().renderList[meshIndex];
  42257. serializationObject.renderList.push(mesh.id);
  42258. }
  42259. return serializationObject;
  42260. };
  42261. /**
  42262. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  42263. */
  42264. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  42265. //casting to point light, as light is missing the position attr and typescript complains.
  42266. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  42267. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  42268. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  42269. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  42270. meshes.forEach(function (mesh) {
  42271. shadowGenerator.getShadowMap().renderList.push(mesh);
  42272. });
  42273. }
  42274. if (parsedShadowGenerator.usePoissonSampling) {
  42275. shadowGenerator.usePoissonSampling = true;
  42276. }
  42277. else if (parsedShadowGenerator.useExponentialShadowMap) {
  42278. shadowGenerator.useExponentialShadowMap = true;
  42279. }
  42280. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  42281. shadowGenerator.useBlurExponentialShadowMap = true;
  42282. }
  42283. else if (parsedShadowGenerator.useVarianceShadowMap) {
  42284. shadowGenerator.useExponentialShadowMap = true;
  42285. }
  42286. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  42287. shadowGenerator.useBlurExponentialShadowMap = true;
  42288. }
  42289. if (parsedShadowGenerator.depthScale) {
  42290. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  42291. }
  42292. if (parsedShadowGenerator.blurScale) {
  42293. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  42294. }
  42295. if (parsedShadowGenerator.blurBoxOffset) {
  42296. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  42297. }
  42298. if (parsedShadowGenerator.bias !== undefined) {
  42299. shadowGenerator.bias = parsedShadowGenerator.bias;
  42300. }
  42301. if (parsedShadowGenerator.darkness) {
  42302. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  42303. }
  42304. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  42305. return shadowGenerator;
  42306. };
  42307. return ShadowGenerator;
  42308. }());
  42309. ShadowGenerator._FILTER_NONE = 0;
  42310. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  42311. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  42312. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  42313. BABYLON.ShadowGenerator = ShadowGenerator;
  42314. })(BABYLON || (BABYLON = {}));
  42315. //# sourceMappingURL=babylon.shadowGenerator.js.map
  42316. var BABYLON;
  42317. (function (BABYLON) {
  42318. var DefaultLoadingScreen = (function () {
  42319. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  42320. if (_loadingText === void 0) { _loadingText = ""; }
  42321. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  42322. var _this = this;
  42323. this._renderingCanvas = _renderingCanvas;
  42324. this._loadingText = _loadingText;
  42325. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  42326. // Resize
  42327. this._resizeLoadingUI = function () {
  42328. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  42329. _this._loadingDiv.style.position = "absolute";
  42330. _this._loadingDiv.style.left = canvasRect.left + "px";
  42331. _this._loadingDiv.style.top = canvasRect.top + "px";
  42332. _this._loadingDiv.style.width = canvasRect.width + "px";
  42333. _this._loadingDiv.style.height = canvasRect.height + "px";
  42334. };
  42335. }
  42336. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  42337. var _this = this;
  42338. if (this._loadingDiv) {
  42339. // Do not add a loading screen if there is already one
  42340. return;
  42341. }
  42342. this._loadingDiv = document.createElement("div");
  42343. this._loadingDiv.id = "babylonjsLoadingDiv";
  42344. this._loadingDiv.style.opacity = "0";
  42345. this._loadingDiv.style.transition = "opacity 1.5s ease";
  42346. // Loading text
  42347. this._loadingTextDiv = document.createElement("div");
  42348. this._loadingTextDiv.style.position = "absolute";
  42349. this._loadingTextDiv.style.left = "0";
  42350. this._loadingTextDiv.style.top = "50%";
  42351. this._loadingTextDiv.style.marginTop = "80px";
  42352. this._loadingTextDiv.style.width = "100%";
  42353. this._loadingTextDiv.style.height = "20px";
  42354. this._loadingTextDiv.style.fontFamily = "Arial";
  42355. this._loadingTextDiv.style.fontSize = "14px";
  42356. this._loadingTextDiv.style.color = "white";
  42357. this._loadingTextDiv.style.textAlign = "center";
  42358. this._loadingTextDiv.innerHTML = "Loading";
  42359. this._loadingDiv.appendChild(this._loadingTextDiv);
  42360. //set the predefined text
  42361. this._loadingTextDiv.innerHTML = this._loadingText;
  42362. // Loading img
  42363. var imgBack = new Image();
  42364. 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==";
  42365. imgBack.style.position = "absolute";
  42366. imgBack.style.left = "50%";
  42367. imgBack.style.top = "50%";
  42368. imgBack.style.marginLeft = "-50px";
  42369. imgBack.style.marginTop = "-50px";
  42370. imgBack.style.transition = "transform 1.0s ease";
  42371. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  42372. var deg = 360;
  42373. var onTransitionEnd = function () {
  42374. deg += 360;
  42375. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  42376. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  42377. };
  42378. imgBack.addEventListener("transitionend", onTransitionEnd);
  42379. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  42380. this._loadingDiv.appendChild(imgBack);
  42381. // front image
  42382. var imgFront = new Image();
  42383. 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=";
  42384. imgFront.style.position = "absolute";
  42385. imgFront.style.left = "50%";
  42386. imgFront.style.top = "50%";
  42387. imgFront.style.marginLeft = "-50px";
  42388. imgFront.style.marginTop = "-50px";
  42389. this._loadingDiv.appendChild(imgFront);
  42390. this._resizeLoadingUI();
  42391. window.addEventListener("resize", this._resizeLoadingUI);
  42392. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42393. document.body.appendChild(this._loadingDiv);
  42394. setTimeout(function () {
  42395. _this._loadingDiv.style.opacity = "1";
  42396. imgBack.style.transform = "rotateZ(360deg)";
  42397. imgBack.style.webkitTransform = "rotateZ(360deg)";
  42398. }, 0);
  42399. };
  42400. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  42401. var _this = this;
  42402. if (!this._loadingDiv) {
  42403. return;
  42404. }
  42405. var onTransitionEnd = function () {
  42406. if (!_this._loadingDiv) {
  42407. return;
  42408. }
  42409. document.body.removeChild(_this._loadingDiv);
  42410. window.removeEventListener("resize", _this._resizeLoadingUI);
  42411. _this._loadingDiv = null;
  42412. };
  42413. this._loadingDiv.style.opacity = "0";
  42414. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  42415. };
  42416. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  42417. set: function (text) {
  42418. this._loadingText = text;
  42419. if (this._loadingTextDiv) {
  42420. this._loadingTextDiv.innerHTML = this._loadingText;
  42421. }
  42422. },
  42423. enumerable: true,
  42424. configurable: true
  42425. });
  42426. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  42427. get: function () {
  42428. return this._loadingDivBackgroundColor;
  42429. },
  42430. set: function (color) {
  42431. this._loadingDivBackgroundColor = color;
  42432. if (!this._loadingDiv) {
  42433. return;
  42434. }
  42435. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  42436. },
  42437. enumerable: true,
  42438. configurable: true
  42439. });
  42440. return DefaultLoadingScreen;
  42441. }());
  42442. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  42443. })(BABYLON || (BABYLON = {}));
  42444. //# sourceMappingURL=babylon.loadingScreen.js.map
  42445. var BABYLON;
  42446. (function (BABYLON) {
  42447. var SceneLoader = (function () {
  42448. function SceneLoader() {
  42449. }
  42450. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  42451. get: function () {
  42452. return 0;
  42453. },
  42454. enumerable: true,
  42455. configurable: true
  42456. });
  42457. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  42458. get: function () {
  42459. return 1;
  42460. },
  42461. enumerable: true,
  42462. configurable: true
  42463. });
  42464. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  42465. get: function () {
  42466. return 2;
  42467. },
  42468. enumerable: true,
  42469. configurable: true
  42470. });
  42471. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  42472. get: function () {
  42473. return 3;
  42474. },
  42475. enumerable: true,
  42476. configurable: true
  42477. });
  42478. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  42479. get: function () {
  42480. return SceneLoader._ForceFullSceneLoadingForIncremental;
  42481. },
  42482. set: function (value) {
  42483. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  42484. },
  42485. enumerable: true,
  42486. configurable: true
  42487. });
  42488. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  42489. get: function () {
  42490. return SceneLoader._ShowLoadingScreen;
  42491. },
  42492. set: function (value) {
  42493. SceneLoader._ShowLoadingScreen = value;
  42494. },
  42495. enumerable: true,
  42496. configurable: true
  42497. });
  42498. Object.defineProperty(SceneLoader, "loggingLevel", {
  42499. get: function () {
  42500. return SceneLoader._loggingLevel;
  42501. },
  42502. set: function (value) {
  42503. SceneLoader._loggingLevel = value;
  42504. },
  42505. enumerable: true,
  42506. configurable: true
  42507. });
  42508. SceneLoader._getDefaultPlugin = function () {
  42509. return SceneLoader._registeredPlugins[".babylon"];
  42510. };
  42511. SceneLoader._getPluginForExtension = function (extension) {
  42512. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  42513. if (registeredPlugin) {
  42514. return registeredPlugin;
  42515. }
  42516. return SceneLoader._getDefaultPlugin();
  42517. };
  42518. SceneLoader._getPluginForFilename = function (sceneFilename) {
  42519. if (sceneFilename.name) {
  42520. sceneFilename = sceneFilename.name;
  42521. }
  42522. var dotPosition = sceneFilename.lastIndexOf(".");
  42523. var queryStringPosition = sceneFilename.indexOf("?");
  42524. if (queryStringPosition === -1) {
  42525. queryStringPosition = sceneFilename.length;
  42526. }
  42527. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  42528. return SceneLoader._getPluginForExtension(extension);
  42529. };
  42530. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  42531. SceneLoader._getDirectLoad = function (sceneFilename) {
  42532. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  42533. return sceneFilename.substr(5);
  42534. }
  42535. return null;
  42536. };
  42537. // Public functions
  42538. SceneLoader.GetPluginForExtension = function (extension) {
  42539. return SceneLoader._getPluginForExtension(extension).plugin;
  42540. };
  42541. SceneLoader.RegisterPlugin = function (plugin) {
  42542. if (typeof plugin.extensions === "string") {
  42543. var extension = plugin.extensions;
  42544. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  42545. plugin: plugin,
  42546. isBinary: false
  42547. };
  42548. }
  42549. else {
  42550. var extensions = plugin.extensions;
  42551. Object.keys(extensions).forEach(function (extension) {
  42552. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  42553. plugin: plugin,
  42554. isBinary: extensions[extension].isBinary
  42555. };
  42556. });
  42557. }
  42558. };
  42559. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  42560. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  42561. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  42562. return;
  42563. }
  42564. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  42565. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  42566. return;
  42567. }
  42568. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  42569. var loadingToken = {};
  42570. scene._addPendingData(loadingToken);
  42571. var manifestChecked = function (success) {
  42572. scene.database = database;
  42573. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  42574. var plugin = registeredPlugin.plugin;
  42575. var useArrayBuffer = registeredPlugin.isBinary;
  42576. var importMeshFromData = function (data) {
  42577. var meshes = [];
  42578. var particleSystems = [];
  42579. var skeletons = [];
  42580. if (scene.isDisposed) {
  42581. if (onerror) {
  42582. onerror(scene, 'Scene was disposed before being able to load ' + rootUrl + sceneFilename);
  42583. }
  42584. return;
  42585. }
  42586. try {
  42587. if (plugin.importMesh) {
  42588. var syncedPlugin = plugin;
  42589. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  42590. if (onerror) {
  42591. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  42592. }
  42593. scene._removePendingData(loadingToken);
  42594. return;
  42595. }
  42596. if (onsuccess) {
  42597. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  42598. onsuccess(meshes, particleSystems, skeletons);
  42599. scene._removePendingData(loadingToken);
  42600. }
  42601. }
  42602. else {
  42603. var asyncedPlugin = plugin;
  42604. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  42605. if (onsuccess) {
  42606. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  42607. onsuccess(meshes, particleSystems, skeletons);
  42608. scene._removePendingData(loadingToken);
  42609. }
  42610. }, function () {
  42611. if (onerror) {
  42612. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  42613. }
  42614. scene._removePendingData(loadingToken);
  42615. });
  42616. }
  42617. }
  42618. catch (e) {
  42619. if (onerror) {
  42620. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  42621. }
  42622. scene._removePendingData(loadingToken);
  42623. }
  42624. };
  42625. if (directLoad) {
  42626. importMeshFromData(directLoad);
  42627. return;
  42628. }
  42629. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  42630. importMeshFromData(data);
  42631. }, progressCallBack, database, useArrayBuffer, function () {
  42632. if (onerror) {
  42633. onerror(scene, 'Unable to load file ' + rootUrl + sceneFilename);
  42634. }
  42635. });
  42636. };
  42637. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  42638. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  42639. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  42640. }
  42641. else {
  42642. // If the scene is a data stream or offline support is not enabled, it's a direct load
  42643. manifestChecked(true);
  42644. }
  42645. };
  42646. /**
  42647. * Load a scene
  42648. * @param rootUrl a string that defines the root url for scene and resources
  42649. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  42650. * @param engine is the instance of BABYLON.Engine to use to create the scene
  42651. */
  42652. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  42653. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  42654. };
  42655. /**
  42656. * Append a scene
  42657. * @param rootUrl a string that defines the root url for scene and resources
  42658. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  42659. * @param scene is the instance of BABYLON.Scene to append to
  42660. */
  42661. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  42662. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  42663. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  42664. return;
  42665. }
  42666. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  42667. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  42668. var plugin = registeredPlugin.plugin;
  42669. var useArrayBuffer = registeredPlugin.isBinary;
  42670. var database;
  42671. var loadingToken = {};
  42672. scene._addPendingData(loadingToken);
  42673. if (SceneLoader.ShowLoadingScreen) {
  42674. scene.getEngine().displayLoadingUI();
  42675. }
  42676. var loadSceneFromData = function (data) {
  42677. scene.database = database;
  42678. if (plugin.load) {
  42679. var syncedPlugin = plugin;
  42680. if (!syncedPlugin.load(scene, data, rootUrl)) {
  42681. if (onerror) {
  42682. onerror(scene);
  42683. }
  42684. scene._removePendingData(loadingToken);
  42685. scene.getEngine().hideLoadingUI();
  42686. return;
  42687. }
  42688. if (onsuccess) {
  42689. onsuccess(scene);
  42690. }
  42691. scene._removePendingData(loadingToken);
  42692. }
  42693. else {
  42694. var asyncedPlugin = plugin;
  42695. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  42696. if (onsuccess) {
  42697. onsuccess(scene);
  42698. }
  42699. scene._removePendingData(loadingToken);
  42700. }, function () {
  42701. if (onerror) {
  42702. onerror(scene);
  42703. }
  42704. scene._removePendingData(loadingToken);
  42705. scene.getEngine().hideLoadingUI();
  42706. });
  42707. }
  42708. if (SceneLoader.ShowLoadingScreen) {
  42709. scene.executeWhenReady(function () {
  42710. scene.getEngine().hideLoadingUI();
  42711. });
  42712. }
  42713. };
  42714. var manifestChecked = function (success) {
  42715. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  42716. };
  42717. if (directLoad) {
  42718. loadSceneFromData(directLoad);
  42719. return;
  42720. }
  42721. if (rootUrl.indexOf("file:") === -1) {
  42722. if (scene.getEngine().enableOfflineSupport) {
  42723. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  42724. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  42725. }
  42726. else {
  42727. manifestChecked(true);
  42728. }
  42729. }
  42730. else {
  42731. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  42732. }
  42733. };
  42734. return SceneLoader;
  42735. }());
  42736. // Flags
  42737. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  42738. SceneLoader._ShowLoadingScreen = true;
  42739. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  42740. // Members
  42741. SceneLoader._registeredPlugins = {};
  42742. BABYLON.SceneLoader = SceneLoader;
  42743. ;
  42744. })(BABYLON || (BABYLON = {}));
  42745. //# sourceMappingURL=babylon.sceneLoader.js.map
  42746. var BABYLON;
  42747. (function (BABYLON) {
  42748. var Internals;
  42749. (function (Internals) {
  42750. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  42751. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  42752. var parsedMaterial = parsedData.materials[index];
  42753. if (parsedMaterial.id === id) {
  42754. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  42755. }
  42756. }
  42757. return null;
  42758. };
  42759. var isDescendantOf = function (mesh, names, hierarchyIds) {
  42760. names = (names instanceof Array) ? names : [names];
  42761. for (var i in names) {
  42762. if (mesh.name === names[i]) {
  42763. hierarchyIds.push(mesh.id);
  42764. return true;
  42765. }
  42766. }
  42767. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  42768. hierarchyIds.push(mesh.id);
  42769. return true;
  42770. }
  42771. return false;
  42772. };
  42773. var logOperation = function (operation, producer) {
  42774. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  42775. };
  42776. BABYLON.SceneLoader.RegisterPlugin({
  42777. extensions: ".babylon",
  42778. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  42779. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  42780. // when SceneLoader.debugLogging = true (default), or exception encountered.
  42781. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  42782. // and avoid problems with multiple concurrent .babylon loads.
  42783. var log = "importMesh has failed JSON parse";
  42784. try {
  42785. var parsedData = JSON.parse(data);
  42786. log = "";
  42787. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  42788. var loadedSkeletonsIds = [];
  42789. var loadedMaterialsIds = [];
  42790. var hierarchyIds = [];
  42791. var index;
  42792. var cache;
  42793. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  42794. var parsedMesh = parsedData.meshes[index];
  42795. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  42796. if (meshesNames instanceof Array) {
  42797. // Remove found mesh name from list.
  42798. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  42799. }
  42800. //Geometry?
  42801. if (parsedMesh.geometryId) {
  42802. //does the file contain geometries?
  42803. if (parsedData.geometries) {
  42804. //find the correct geometry and add it to the scene
  42805. var found = false;
  42806. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  42807. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  42808. return;
  42809. }
  42810. else {
  42811. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  42812. if (parsedGeometryData.id === parsedMesh.geometryId) {
  42813. switch (geometryType) {
  42814. case "boxes":
  42815. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  42816. break;
  42817. case "spheres":
  42818. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  42819. break;
  42820. case "cylinders":
  42821. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  42822. break;
  42823. case "toruses":
  42824. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  42825. break;
  42826. case "grounds":
  42827. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  42828. break;
  42829. case "planes":
  42830. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  42831. break;
  42832. case "torusKnots":
  42833. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  42834. break;
  42835. case "vertexData":
  42836. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  42837. break;
  42838. }
  42839. found = true;
  42840. }
  42841. });
  42842. }
  42843. });
  42844. if (!found) {
  42845. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  42846. }
  42847. }
  42848. }
  42849. // Material ?
  42850. if (parsedMesh.materialId) {
  42851. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  42852. if (!materialFound && parsedData.multiMaterials) {
  42853. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  42854. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  42855. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  42856. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  42857. var subMatId = parsedMultiMaterial.materials[matIndex];
  42858. loadedMaterialsIds.push(subMatId);
  42859. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  42860. log += "\n\tMaterial " + mat.toString(fullDetails);
  42861. }
  42862. loadedMaterialsIds.push(parsedMultiMaterial.id);
  42863. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  42864. materialFound = true;
  42865. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  42866. break;
  42867. }
  42868. }
  42869. }
  42870. if (!materialFound) {
  42871. loadedMaterialsIds.push(parsedMesh.materialId);
  42872. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  42873. if (!mat) {
  42874. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  42875. }
  42876. else {
  42877. log += "\n\tMaterial " + mat.toString(fullDetails);
  42878. }
  42879. }
  42880. }
  42881. // Skeleton ?
  42882. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  42883. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  42884. if (!skeletonAlreadyLoaded) {
  42885. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  42886. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  42887. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  42888. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  42889. skeletons.push(skeleton);
  42890. loadedSkeletonsIds.push(parsedSkeleton.id);
  42891. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  42892. }
  42893. }
  42894. }
  42895. }
  42896. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  42897. meshes.push(mesh);
  42898. log += "\n\tMesh " + mesh.toString(fullDetails);
  42899. }
  42900. }
  42901. // Connecting parents
  42902. var currentMesh;
  42903. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  42904. currentMesh = scene.meshes[index];
  42905. if (currentMesh._waitingParentId) {
  42906. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  42907. currentMesh._waitingParentId = undefined;
  42908. }
  42909. }
  42910. // freeze and compute world matrix application
  42911. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  42912. currentMesh = scene.meshes[index];
  42913. if (currentMesh._waitingFreezeWorldMatrix) {
  42914. currentMesh.freezeWorldMatrix();
  42915. currentMesh._waitingFreezeWorldMatrix = undefined;
  42916. }
  42917. else {
  42918. currentMesh.computeWorldMatrix(true);
  42919. }
  42920. }
  42921. // Particles
  42922. if (parsedData.particleSystems) {
  42923. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  42924. var parsedParticleSystem = parsedData.particleSystems[index];
  42925. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  42926. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  42927. }
  42928. }
  42929. }
  42930. return true;
  42931. }
  42932. catch (err) {
  42933. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  42934. log = null;
  42935. throw err;
  42936. }
  42937. finally {
  42938. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  42939. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  42940. }
  42941. }
  42942. },
  42943. load: function (scene, data, rootUrl) {
  42944. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  42945. // when SceneLoader.debugLogging = true (default), or exception encountered.
  42946. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  42947. // and avoid problems with multiple concurrent .babylon loads.
  42948. var log = "importScene has failed JSON parse";
  42949. try {
  42950. var parsedData = JSON.parse(data);
  42951. log = "";
  42952. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  42953. // Scene
  42954. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  42955. scene.autoClear = parsedData.autoClear;
  42956. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  42957. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  42958. if (parsedData.gravity) {
  42959. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  42960. }
  42961. // Fog
  42962. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  42963. scene.fogMode = parsedData.fogMode;
  42964. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  42965. scene.fogStart = parsedData.fogStart;
  42966. scene.fogEnd = parsedData.fogEnd;
  42967. scene.fogDensity = parsedData.fogDensity;
  42968. log += "\tFog mode for scene: ";
  42969. switch (scene.fogMode) {
  42970. // getters not compiling, so using hardcoded
  42971. case 1:
  42972. log += "exp\n";
  42973. break;
  42974. case 2:
  42975. log += "exp2\n";
  42976. break;
  42977. case 3:
  42978. log += "linear\n";
  42979. break;
  42980. }
  42981. }
  42982. //Physics
  42983. if (parsedData.physicsEnabled) {
  42984. var physicsPlugin;
  42985. if (parsedData.physicsEngine === "cannon") {
  42986. physicsPlugin = new BABYLON.CannonJSPlugin();
  42987. }
  42988. else if (parsedData.physicsEngine === "oimo") {
  42989. physicsPlugin = new BABYLON.OimoJSPlugin();
  42990. }
  42991. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  42992. //else - default engine, which is currently oimo
  42993. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  42994. scene.enablePhysics(physicsGravity, physicsPlugin);
  42995. }
  42996. // Metadata
  42997. if (parsedData.metadata !== undefined) {
  42998. scene.metadata = parsedData.metadata;
  42999. }
  43000. //collisions, if defined. otherwise, default is true
  43001. if (parsedData.collisionsEnabled != undefined) {
  43002. scene.collisionsEnabled = parsedData.collisionsEnabled;
  43003. }
  43004. scene.workerCollisions = !!parsedData.workerCollisions;
  43005. var index;
  43006. var cache;
  43007. // Lights
  43008. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  43009. var parsedLight = parsedData.lights[index];
  43010. var light = BABYLON.Light.Parse(parsedLight, scene);
  43011. log += (index === 0 ? "\n\tLights:" : "");
  43012. log += "\n\t\t" + light.toString(fullDetails);
  43013. }
  43014. // Animations
  43015. if (parsedData.animations) {
  43016. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  43017. var parsedAnimation = parsedData.animations[index];
  43018. var animation = BABYLON.Animation.Parse(parsedAnimation);
  43019. scene.animations.push(animation);
  43020. log += (index === 0 ? "\n\tAnimations:" : "");
  43021. log += "\n\t\t" + animation.toString(fullDetails);
  43022. }
  43023. }
  43024. if (parsedData.autoAnimate) {
  43025. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  43026. }
  43027. // Materials
  43028. if (parsedData.materials) {
  43029. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  43030. var parsedMaterial = parsedData.materials[index];
  43031. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  43032. log += (index === 0 ? "\n\tMaterials:" : "");
  43033. log += "\n\t\t" + mat.toString(fullDetails);
  43034. }
  43035. }
  43036. if (parsedData.multiMaterials) {
  43037. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  43038. var parsedMultiMaterial = parsedData.multiMaterials[index];
  43039. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  43040. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  43041. log += "\n\t\t" + mmat.toString(fullDetails);
  43042. }
  43043. }
  43044. // Morph targets
  43045. if (parsedData.morphTargetManagers) {
  43046. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  43047. var managerData = _a[_i];
  43048. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  43049. }
  43050. }
  43051. // Skeletons
  43052. if (parsedData.skeletons) {
  43053. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  43054. var parsedSkeleton = parsedData.skeletons[index];
  43055. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  43056. log += (index === 0 ? "\n\tSkeletons:" : "");
  43057. log += "\n\t\t" + skeleton.toString(fullDetails);
  43058. }
  43059. }
  43060. // Geometries
  43061. var geometries = parsedData.geometries;
  43062. if (geometries) {
  43063. // Boxes
  43064. var boxes = geometries.boxes;
  43065. if (boxes) {
  43066. for (index = 0, cache = boxes.length; index < cache; index++) {
  43067. var parsedBox = boxes[index];
  43068. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  43069. }
  43070. }
  43071. // Spheres
  43072. var spheres = geometries.spheres;
  43073. if (spheres) {
  43074. for (index = 0, cache = spheres.length; index < cache; index++) {
  43075. var parsedSphere = spheres[index];
  43076. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  43077. }
  43078. }
  43079. // Cylinders
  43080. var cylinders = geometries.cylinders;
  43081. if (cylinders) {
  43082. for (index = 0, cache = cylinders.length; index < cache; index++) {
  43083. var parsedCylinder = cylinders[index];
  43084. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  43085. }
  43086. }
  43087. // Toruses
  43088. var toruses = geometries.toruses;
  43089. if (toruses) {
  43090. for (index = 0, cache = toruses.length; index < cache; index++) {
  43091. var parsedTorus = toruses[index];
  43092. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  43093. }
  43094. }
  43095. // Grounds
  43096. var grounds = geometries.grounds;
  43097. if (grounds) {
  43098. for (index = 0, cache = grounds.length; index < cache; index++) {
  43099. var parsedGround = grounds[index];
  43100. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  43101. }
  43102. }
  43103. // Planes
  43104. var planes = geometries.planes;
  43105. if (planes) {
  43106. for (index = 0, cache = planes.length; index < cache; index++) {
  43107. var parsedPlane = planes[index];
  43108. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  43109. }
  43110. }
  43111. // TorusKnots
  43112. var torusKnots = geometries.torusKnots;
  43113. if (torusKnots) {
  43114. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  43115. var parsedTorusKnot = torusKnots[index];
  43116. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  43117. }
  43118. }
  43119. // VertexData
  43120. var vertexData = geometries.vertexData;
  43121. if (vertexData) {
  43122. for (index = 0, cache = vertexData.length; index < cache; index++) {
  43123. var parsedVertexData = vertexData[index];
  43124. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  43125. }
  43126. }
  43127. }
  43128. // Meshes
  43129. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  43130. var parsedMesh = parsedData.meshes[index];
  43131. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  43132. log += (index === 0 ? "\n\tMeshes:" : "");
  43133. log += "\n\t\t" + mesh.toString(fullDetails);
  43134. }
  43135. // Cameras
  43136. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  43137. var parsedCamera = parsedData.cameras[index];
  43138. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  43139. log += (index === 0 ? "\n\tCameras:" : "");
  43140. log += "\n\t\t" + camera.toString(fullDetails);
  43141. }
  43142. if (parsedData.activeCameraID) {
  43143. scene.setActiveCameraByID(parsedData.activeCameraID);
  43144. }
  43145. // Browsing all the graph to connect the dots
  43146. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  43147. var camera = scene.cameras[index];
  43148. if (camera._waitingParentId) {
  43149. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  43150. camera._waitingParentId = undefined;
  43151. }
  43152. }
  43153. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  43154. var light = scene.lights[index];
  43155. if (light._waitingParentId) {
  43156. light.parent = scene.getLastEntryByID(light._waitingParentId);
  43157. light._waitingParentId = undefined;
  43158. }
  43159. }
  43160. // Sounds
  43161. var loadedSounds = [];
  43162. var loadedSound;
  43163. if (BABYLON.AudioEngine && parsedData.sounds) {
  43164. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  43165. var parsedSound = parsedData.sounds[index];
  43166. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  43167. if (!parsedSound.url)
  43168. parsedSound.url = parsedSound.name;
  43169. if (!loadedSounds[parsedSound.url]) {
  43170. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  43171. loadedSounds[parsedSound.url] = loadedSound;
  43172. }
  43173. else {
  43174. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  43175. }
  43176. }
  43177. else {
  43178. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  43179. }
  43180. }
  43181. }
  43182. loadedSounds = [];
  43183. // Connect parents & children and parse actions
  43184. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  43185. var mesh = scene.meshes[index];
  43186. if (mesh._waitingParentId) {
  43187. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  43188. mesh._waitingParentId = undefined;
  43189. }
  43190. if (mesh._waitingActions) {
  43191. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  43192. mesh._waitingActions = undefined;
  43193. }
  43194. }
  43195. // freeze world matrix application
  43196. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  43197. var currentMesh = scene.meshes[index];
  43198. if (currentMesh._waitingFreezeWorldMatrix) {
  43199. currentMesh.freezeWorldMatrix();
  43200. currentMesh._waitingFreezeWorldMatrix = undefined;
  43201. }
  43202. else {
  43203. currentMesh.computeWorldMatrix(true);
  43204. }
  43205. }
  43206. // Particles Systems
  43207. if (parsedData.particleSystems) {
  43208. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  43209. var parsedParticleSystem = parsedData.particleSystems[index];
  43210. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  43211. }
  43212. }
  43213. // Lens flares
  43214. if (parsedData.lensFlareSystems) {
  43215. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  43216. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  43217. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  43218. }
  43219. }
  43220. // Shadows
  43221. if (parsedData.shadowGenerators) {
  43222. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  43223. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  43224. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  43225. }
  43226. }
  43227. // Lights exclusions / inclusions
  43228. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  43229. var light = scene.lights[index];
  43230. // Excluded check
  43231. if (light._excludedMeshesIds.length > 0) {
  43232. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  43233. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  43234. if (excludedMesh) {
  43235. light.excludedMeshes.push(excludedMesh);
  43236. }
  43237. }
  43238. light._excludedMeshesIds = [];
  43239. }
  43240. // Included check
  43241. if (light._includedOnlyMeshesIds.length > 0) {
  43242. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  43243. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  43244. if (includedOnlyMesh) {
  43245. light.includedOnlyMeshes.push(includedOnlyMesh);
  43246. }
  43247. }
  43248. light._includedOnlyMeshesIds = [];
  43249. }
  43250. }
  43251. // Actions (scene)
  43252. if (parsedData.actions) {
  43253. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  43254. }
  43255. // Finish
  43256. return true;
  43257. }
  43258. catch (err) {
  43259. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  43260. log = null;
  43261. throw err;
  43262. }
  43263. finally {
  43264. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  43265. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  43266. }
  43267. }
  43268. }
  43269. });
  43270. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43271. })(BABYLON || (BABYLON = {}));
  43272. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  43273. var BABYLON;
  43274. (function (BABYLON) {
  43275. var FilesInput = (function () {
  43276. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  43277. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  43278. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  43279. this._engine = p_engine;
  43280. this._canvas = p_canvas;
  43281. this._currentScene = p_scene;
  43282. this._sceneLoadedCallback = p_sceneLoadedCallback;
  43283. this._progressCallback = p_progressCallback;
  43284. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  43285. this._textureLoadingCallback = p_textureLoadingCallback;
  43286. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  43287. }
  43288. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  43289. var _this = this;
  43290. if (p_elementToMonitor) {
  43291. this._elementToMonitor = p_elementToMonitor;
  43292. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  43293. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  43294. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  43295. }
  43296. };
  43297. FilesInput.prototype.renderFunction = function () {
  43298. if (this._additionnalRenderLoopLogicCallback) {
  43299. this._additionnalRenderLoopLogicCallback();
  43300. }
  43301. if (this._currentScene) {
  43302. if (this._textureLoadingCallback) {
  43303. var remaining = this._currentScene.getWaitingItemsCount();
  43304. if (remaining > 0) {
  43305. this._textureLoadingCallback(remaining);
  43306. }
  43307. }
  43308. this._currentScene.render();
  43309. }
  43310. };
  43311. FilesInput.prototype.drag = function (e) {
  43312. e.stopPropagation();
  43313. e.preventDefault();
  43314. };
  43315. FilesInput.prototype.drop = function (eventDrop) {
  43316. eventDrop.stopPropagation();
  43317. eventDrop.preventDefault();
  43318. this.loadFiles(eventDrop);
  43319. };
  43320. FilesInput.prototype.loadFiles = function (event) {
  43321. if (this._startingProcessingFilesCallback)
  43322. this._startingProcessingFilesCallback();
  43323. // Handling data transfer via drag'n'drop
  43324. if (event && event.dataTransfer && event.dataTransfer.files) {
  43325. this._filesToLoad = event.dataTransfer.files;
  43326. }
  43327. // Handling files from input files
  43328. if (event && event.target && event.target.files) {
  43329. this._filesToLoad = event.target.files;
  43330. }
  43331. if (this._filesToLoad && this._filesToLoad.length > 0) {
  43332. for (var i = 0; i < this._filesToLoad.length; i++) {
  43333. var name_1 = this._filesToLoad[i].name.toLowerCase();
  43334. var extension = name_1.split('.').pop();
  43335. var type = this._filesToLoad[i].type;
  43336. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  43337. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  43338. this._sceneFileToLoad = this._filesToLoad[i];
  43339. }
  43340. else {
  43341. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  43342. }
  43343. }
  43344. this.reload();
  43345. }
  43346. };
  43347. FilesInput.prototype.reload = function () {
  43348. var _this = this;
  43349. var that = this;
  43350. // If a ".babylon" file has been provided
  43351. if (this._sceneFileToLoad) {
  43352. if (this._currentScene) {
  43353. if (BABYLON.Tools.errorsCount > 0) {
  43354. BABYLON.Tools.ClearLogCache();
  43355. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  43356. }
  43357. this._engine.stopRenderLoop();
  43358. this._currentScene.dispose();
  43359. }
  43360. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  43361. that._currentScene = newScene;
  43362. // Wait for textures and shaders to be ready
  43363. that._currentScene.executeWhenReady(function () {
  43364. if (that._sceneLoadedCallback) {
  43365. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  43366. }
  43367. that._engine.runRenderLoop(function () { that.renderFunction(); });
  43368. });
  43369. }, function (progress) {
  43370. if (_this._progressCallback) {
  43371. _this._progressCallback(progress);
  43372. }
  43373. });
  43374. }
  43375. else {
  43376. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  43377. }
  43378. };
  43379. return FilesInput;
  43380. }());
  43381. FilesInput.FilesToLoad = new Array();
  43382. BABYLON.FilesInput = FilesInput;
  43383. })(BABYLON || (BABYLON = {}));
  43384. //# sourceMappingURL=babylon.filesInput.js.map
  43385. var BABYLON;
  43386. (function (BABYLON) {
  43387. /**
  43388. * This class implement a typical dictionary using a string as key and the generic type T as value.
  43389. * The underlying implementation relies on an associative array to ensure the best performances.
  43390. * The value can be anything including 'null' but except 'undefined'
  43391. */
  43392. var StringDictionary = (function () {
  43393. function StringDictionary() {
  43394. this._count = 0;
  43395. this._data = {};
  43396. }
  43397. /**
  43398. * This will clear this dictionary and copy the content from the 'source' one.
  43399. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  43400. * @param source the dictionary to take the content from and copy to this dictionary
  43401. */
  43402. StringDictionary.prototype.copyFrom = function (source) {
  43403. var _this = this;
  43404. this.clear();
  43405. source.forEach(function (t, v) { return _this.add(t, v); });
  43406. };
  43407. /**
  43408. * Get a value based from its key
  43409. * @param key the given key to get the matching value from
  43410. * @return the value if found, otherwise undefined is returned
  43411. */
  43412. StringDictionary.prototype.get = function (key) {
  43413. var val = this._data[key];
  43414. if (val !== undefined) {
  43415. return val;
  43416. }
  43417. return undefined;
  43418. };
  43419. /**
  43420. * Get a value from its key or add it if it doesn't exist.
  43421. * This method will ensure you that a given key/data will be present in the dictionary.
  43422. * @param key the given key to get the matching value from
  43423. * @param factory the factory that will create the value if the key is not present in the dictionary.
  43424. * The factory will only be invoked if there's no data for the given key.
  43425. * @return the value corresponding to the key.
  43426. */
  43427. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  43428. var val = this.get(key);
  43429. if (val !== undefined) {
  43430. return val;
  43431. }
  43432. val = factory(key);
  43433. if (val) {
  43434. this.add(key, val);
  43435. }
  43436. return val;
  43437. };
  43438. /**
  43439. * Get a value from its key if present in the dictionary otherwise add it
  43440. * @param key the key to get the value from
  43441. * @param val if there's no such key/value pair in the dictionary add it with this value
  43442. * @return the value corresponding to the key
  43443. */
  43444. StringDictionary.prototype.getOrAdd = function (key, val) {
  43445. var curVal = this.get(key);
  43446. if (curVal !== undefined) {
  43447. return curVal;
  43448. }
  43449. this.add(key, val);
  43450. return val;
  43451. };
  43452. /**
  43453. * Check if there's a given key in the dictionary
  43454. * @param key the key to check for
  43455. * @return true if the key is present, false otherwise
  43456. */
  43457. StringDictionary.prototype.contains = function (key) {
  43458. return this._data[key] !== undefined;
  43459. };
  43460. /**
  43461. * Add a new key and its corresponding value
  43462. * @param key the key to add
  43463. * @param value the value corresponding to the key
  43464. * @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
  43465. */
  43466. StringDictionary.prototype.add = function (key, value) {
  43467. if (this._data[key] !== undefined) {
  43468. return false;
  43469. }
  43470. this._data[key] = value;
  43471. ++this._count;
  43472. return true;
  43473. };
  43474. StringDictionary.prototype.set = function (key, value) {
  43475. if (this._data[key] === undefined) {
  43476. return false;
  43477. }
  43478. this._data[key] = value;
  43479. return true;
  43480. };
  43481. /**
  43482. * Get the element of the given key and remove it from the dictionary
  43483. * @param key
  43484. */
  43485. StringDictionary.prototype.getAndRemove = function (key) {
  43486. var val = this.get(key);
  43487. if (val !== undefined) {
  43488. delete this._data[key];
  43489. --this._count;
  43490. return val;
  43491. }
  43492. return null;
  43493. };
  43494. /**
  43495. * Remove a key/value from the dictionary.
  43496. * @param key the key to remove
  43497. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  43498. */
  43499. StringDictionary.prototype.remove = function (key) {
  43500. if (this.contains(key)) {
  43501. delete this._data[key];
  43502. --this._count;
  43503. return true;
  43504. }
  43505. return false;
  43506. };
  43507. /**
  43508. * Clear the whole content of the dictionary
  43509. */
  43510. StringDictionary.prototype.clear = function () {
  43511. this._data = {};
  43512. this._count = 0;
  43513. };
  43514. Object.defineProperty(StringDictionary.prototype, "count", {
  43515. get: function () {
  43516. return this._count;
  43517. },
  43518. enumerable: true,
  43519. configurable: true
  43520. });
  43521. /**
  43522. * Execute a callback on each key/val of the dictionary.
  43523. * Note that you can remove any element in this dictionary in the callback implementation
  43524. * @param callback the callback to execute on a given key/value pair
  43525. */
  43526. StringDictionary.prototype.forEach = function (callback) {
  43527. for (var cur in this._data) {
  43528. var val = this._data[cur];
  43529. callback(cur, val);
  43530. }
  43531. };
  43532. /**
  43533. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  43534. * If the callback returns null or undefined the method will iterate to the next key/value pair
  43535. * Note that you can remove any element in this dictionary in the callback implementation
  43536. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  43537. */
  43538. StringDictionary.prototype.first = function (callback) {
  43539. for (var cur in this._data) {
  43540. var val = this._data[cur];
  43541. var res = callback(cur, val);
  43542. if (res) {
  43543. return res;
  43544. }
  43545. }
  43546. return null;
  43547. };
  43548. return StringDictionary;
  43549. }());
  43550. BABYLON.StringDictionary = StringDictionary;
  43551. })(BABYLON || (BABYLON = {}));
  43552. //# sourceMappingURL=babylon.stringDictionary.js.map
  43553. var BABYLON;
  43554. (function (BABYLON) {
  43555. var Tags = (function () {
  43556. function Tags() {
  43557. }
  43558. Tags.EnableFor = function (obj) {
  43559. obj._tags = obj._tags || {};
  43560. obj.hasTags = function () {
  43561. return Tags.HasTags(obj);
  43562. };
  43563. obj.addTags = function (tagsString) {
  43564. return Tags.AddTagsTo(obj, tagsString);
  43565. };
  43566. obj.removeTags = function (tagsString) {
  43567. return Tags.RemoveTagsFrom(obj, tagsString);
  43568. };
  43569. obj.matchesTagsQuery = function (tagsQuery) {
  43570. return Tags.MatchesQuery(obj, tagsQuery);
  43571. };
  43572. };
  43573. Tags.DisableFor = function (obj) {
  43574. delete obj._tags;
  43575. delete obj.hasTags;
  43576. delete obj.addTags;
  43577. delete obj.removeTags;
  43578. delete obj.matchesTagsQuery;
  43579. };
  43580. Tags.HasTags = function (obj) {
  43581. if (!obj._tags) {
  43582. return false;
  43583. }
  43584. return !BABYLON.Tools.IsEmpty(obj._tags);
  43585. };
  43586. Tags.GetTags = function (obj, asString) {
  43587. if (asString === void 0) { asString = true; }
  43588. if (!obj._tags) {
  43589. return null;
  43590. }
  43591. if (asString) {
  43592. var tagsArray = [];
  43593. for (var tag in obj._tags) {
  43594. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  43595. tagsArray.push(tag);
  43596. }
  43597. }
  43598. return tagsArray.join(" ");
  43599. }
  43600. else {
  43601. return obj._tags;
  43602. }
  43603. };
  43604. // the tags 'true' and 'false' are reserved and cannot be used as tags
  43605. // a tag cannot start with '||', '&&', and '!'
  43606. // it cannot contain whitespaces
  43607. Tags.AddTagsTo = function (obj, tagsString) {
  43608. if (!tagsString) {
  43609. return;
  43610. }
  43611. if (typeof tagsString !== "string") {
  43612. return;
  43613. }
  43614. var tags = tagsString.split(" ");
  43615. tags.forEach(function (tag, index, array) {
  43616. Tags._AddTagTo(obj, tag);
  43617. });
  43618. };
  43619. Tags._AddTagTo = function (obj, tag) {
  43620. tag = tag.trim();
  43621. if (tag === "" || tag === "true" || tag === "false") {
  43622. return;
  43623. }
  43624. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  43625. return;
  43626. }
  43627. Tags.EnableFor(obj);
  43628. obj._tags[tag] = true;
  43629. };
  43630. Tags.RemoveTagsFrom = function (obj, tagsString) {
  43631. if (!Tags.HasTags(obj)) {
  43632. return;
  43633. }
  43634. var tags = tagsString.split(" ");
  43635. for (var t in tags) {
  43636. Tags._RemoveTagFrom(obj, tags[t]);
  43637. }
  43638. };
  43639. Tags._RemoveTagFrom = function (obj, tag) {
  43640. delete obj._tags[tag];
  43641. };
  43642. Tags.MatchesQuery = function (obj, tagsQuery) {
  43643. if (tagsQuery === undefined) {
  43644. return true;
  43645. }
  43646. if (tagsQuery === "") {
  43647. return Tags.HasTags(obj);
  43648. }
  43649. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  43650. };
  43651. return Tags;
  43652. }());
  43653. BABYLON.Tags = Tags;
  43654. })(BABYLON || (BABYLON = {}));
  43655. //# sourceMappingURL=babylon.tags.js.map
  43656. var BABYLON;
  43657. (function (BABYLON) {
  43658. var Internals;
  43659. (function (Internals) {
  43660. var AndOrNotEvaluator = (function () {
  43661. function AndOrNotEvaluator() {
  43662. }
  43663. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  43664. if (!query.match(/\([^\(\)]*\)/g)) {
  43665. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  43666. }
  43667. else {
  43668. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  43669. // remove parenthesis
  43670. r = r.slice(1, r.length - 1);
  43671. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  43672. });
  43673. }
  43674. if (query === "true") {
  43675. return true;
  43676. }
  43677. if (query === "false") {
  43678. return false;
  43679. }
  43680. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  43681. };
  43682. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  43683. evaluateCallback = evaluateCallback || (function (r) {
  43684. return r === "true" ? true : false;
  43685. });
  43686. var result;
  43687. var or = parenthesisContent.split("||");
  43688. for (var i in or) {
  43689. if (or.hasOwnProperty(i)) {
  43690. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  43691. var and = ori.split("&&");
  43692. if (and.length > 1) {
  43693. for (var j = 0; j < and.length; ++j) {
  43694. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  43695. if (andj !== "true" && andj !== "false") {
  43696. if (andj[0] === "!") {
  43697. result = !evaluateCallback(andj.substring(1));
  43698. }
  43699. else {
  43700. result = evaluateCallback(andj);
  43701. }
  43702. }
  43703. else {
  43704. result = andj === "true" ? true : false;
  43705. }
  43706. if (!result) {
  43707. ori = "false";
  43708. break;
  43709. }
  43710. }
  43711. }
  43712. if (result || ori === "true") {
  43713. result = true;
  43714. break;
  43715. }
  43716. // result equals false (or undefined)
  43717. if (ori !== "true" && ori !== "false") {
  43718. if (ori[0] === "!") {
  43719. result = !evaluateCallback(ori.substring(1));
  43720. }
  43721. else {
  43722. result = evaluateCallback(ori);
  43723. }
  43724. }
  43725. else {
  43726. result = ori === "true" ? true : false;
  43727. }
  43728. }
  43729. }
  43730. // the whole parenthesis scope is replaced by 'true' or 'false'
  43731. return result ? "true" : "false";
  43732. };
  43733. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  43734. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  43735. // remove whitespaces
  43736. r = r.replace(/[\s]/g, function () { return ""; });
  43737. return r.length % 2 ? "!" : "";
  43738. });
  43739. booleanString = booleanString.trim();
  43740. if (booleanString === "!true") {
  43741. booleanString = "false";
  43742. }
  43743. else if (booleanString === "!false") {
  43744. booleanString = "true";
  43745. }
  43746. return booleanString;
  43747. };
  43748. return AndOrNotEvaluator;
  43749. }());
  43750. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  43751. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43752. })(BABYLON || (BABYLON = {}));
  43753. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  43754. var BABYLON;
  43755. (function (BABYLON) {
  43756. var Database = (function () {
  43757. function Database(urlToScene, callbackManifestChecked) {
  43758. // Handling various flavors of prefixed version of IndexedDB
  43759. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  43760. this.callbackManifestChecked = callbackManifestChecked;
  43761. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  43762. this.db = null;
  43763. this.enableSceneOffline = false;
  43764. this.enableTexturesOffline = false;
  43765. this.manifestVersionFound = 0;
  43766. this.mustUpdateRessources = false;
  43767. this.hasReachedQuota = false;
  43768. if (!Database.IDBStorageEnabled) {
  43769. this.callbackManifestChecked(true);
  43770. }
  43771. else {
  43772. this.checkManifestFile();
  43773. }
  43774. }
  43775. Database.prototype.checkManifestFile = function () {
  43776. var _this = this;
  43777. function noManifestFile() {
  43778. that.enableSceneOffline = false;
  43779. that.enableTexturesOffline = false;
  43780. that.callbackManifestChecked(false);
  43781. }
  43782. var that = this;
  43783. var timeStampUsed = false;
  43784. var manifestURL = this.currentSceneUrl + ".manifest";
  43785. var xhr = new XMLHttpRequest();
  43786. if (navigator.onLine) {
  43787. // Adding a timestamp to by-pass browsers' cache
  43788. timeStampUsed = true;
  43789. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  43790. }
  43791. xhr.open("GET", manifestURL, true);
  43792. xhr.addEventListener("load", function () {
  43793. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  43794. try {
  43795. var manifestFile = JSON.parse(xhr.response);
  43796. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  43797. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  43798. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  43799. _this.manifestVersionFound = manifestFile.version;
  43800. }
  43801. if (_this.callbackManifestChecked) {
  43802. _this.callbackManifestChecked(true);
  43803. }
  43804. }
  43805. catch (ex) {
  43806. noManifestFile();
  43807. }
  43808. }
  43809. else {
  43810. noManifestFile();
  43811. }
  43812. }, false);
  43813. xhr.addEventListener("error", function (event) {
  43814. if (timeStampUsed) {
  43815. timeStampUsed = false;
  43816. // Let's retry without the timeStamp
  43817. // It could fail when coupled with HTML5 Offline API
  43818. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  43819. xhr.open("GET", retryManifestURL, true);
  43820. xhr.send();
  43821. }
  43822. else {
  43823. noManifestFile();
  43824. }
  43825. }, false);
  43826. try {
  43827. xhr.send();
  43828. }
  43829. catch (ex) {
  43830. BABYLON.Tools.Error("Error on XHR send request.");
  43831. that.callbackManifestChecked(false);
  43832. }
  43833. };
  43834. Database.prototype.openAsync = function (successCallback, errorCallback) {
  43835. var _this = this;
  43836. function handleError() {
  43837. that.isSupported = false;
  43838. if (errorCallback)
  43839. errorCallback();
  43840. }
  43841. var that = this;
  43842. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  43843. // Your browser doesn't support IndexedDB
  43844. this.isSupported = false;
  43845. if (errorCallback)
  43846. errorCallback();
  43847. }
  43848. else {
  43849. // If the DB hasn't been opened or created yet
  43850. if (!this.db) {
  43851. this.hasReachedQuota = false;
  43852. this.isSupported = true;
  43853. var request = this.idbFactory.open("babylonjs", 1);
  43854. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  43855. request.onerror = function (event) {
  43856. handleError();
  43857. };
  43858. // executes when a version change transaction cannot complete due to other active transactions
  43859. request.onblocked = function (event) {
  43860. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  43861. handleError();
  43862. };
  43863. // DB has been opened successfully
  43864. request.onsuccess = function (event) {
  43865. _this.db = request.result;
  43866. successCallback();
  43867. };
  43868. // Initialization of the DB. Creating Scenes & Textures stores
  43869. request.onupgradeneeded = function (event) {
  43870. _this.db = (event.target).result;
  43871. try {
  43872. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  43873. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  43874. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  43875. }
  43876. catch (ex) {
  43877. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  43878. handleError();
  43879. }
  43880. };
  43881. }
  43882. else {
  43883. if (successCallback)
  43884. successCallback();
  43885. }
  43886. }
  43887. };
  43888. Database.prototype.loadImageFromDB = function (url, image) {
  43889. var _this = this;
  43890. var completeURL = Database.ReturnFullUrlLocation(url);
  43891. var saveAndLoadImage = function () {
  43892. if (!_this.hasReachedQuota && _this.db !== null) {
  43893. // the texture is not yet in the DB, let's try to save it
  43894. _this._saveImageIntoDBAsync(completeURL, image);
  43895. }
  43896. else {
  43897. image.src = url;
  43898. }
  43899. };
  43900. if (!this.mustUpdateRessources) {
  43901. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  43902. }
  43903. else {
  43904. saveAndLoadImage();
  43905. }
  43906. };
  43907. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  43908. if (this.isSupported && this.db !== null) {
  43909. var texture;
  43910. var transaction = this.db.transaction(["textures"]);
  43911. transaction.onabort = function (event) {
  43912. image.src = url;
  43913. };
  43914. transaction.oncomplete = function (event) {
  43915. var blobTextureURL;
  43916. if (texture) {
  43917. var URL = window.URL || window.webkitURL;
  43918. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  43919. image.onerror = function () {
  43920. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  43921. image.src = url;
  43922. };
  43923. image.src = blobTextureURL;
  43924. }
  43925. else {
  43926. notInDBCallback();
  43927. }
  43928. };
  43929. var getRequest = transaction.objectStore("textures").get(url);
  43930. getRequest.onsuccess = function (event) {
  43931. texture = (event.target).result;
  43932. };
  43933. getRequest.onerror = function (event) {
  43934. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  43935. image.src = url;
  43936. };
  43937. }
  43938. else {
  43939. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  43940. image.src = url;
  43941. }
  43942. };
  43943. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  43944. var _this = this;
  43945. if (this.isSupported) {
  43946. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  43947. var generateBlobUrl = function () {
  43948. var blobTextureURL;
  43949. if (blob) {
  43950. var URL = window.URL || window.webkitURL;
  43951. try {
  43952. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  43953. }
  43954. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  43955. catch (ex) {
  43956. blobTextureURL = URL.createObjectURL(blob);
  43957. }
  43958. }
  43959. image.src = blobTextureURL;
  43960. };
  43961. if (Database.IsUASupportingBlobStorage) {
  43962. var xhr = new XMLHttpRequest(), blob;
  43963. xhr.open("GET", url, true);
  43964. xhr.responseType = "blob";
  43965. xhr.addEventListener("load", function () {
  43966. if (xhr.status === 200) {
  43967. // Blob as response (XHR2)
  43968. blob = xhr.response;
  43969. var transaction = _this.db.transaction(["textures"], "readwrite");
  43970. // the transaction could abort because of a QuotaExceededError error
  43971. transaction.onabort = function (event) {
  43972. try {
  43973. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  43974. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  43975. _this.hasReachedQuota = true;
  43976. }
  43977. }
  43978. catch (ex) { }
  43979. generateBlobUrl();
  43980. };
  43981. transaction.oncomplete = function (event) {
  43982. generateBlobUrl();
  43983. };
  43984. var newTexture = { textureUrl: url, data: blob };
  43985. try {
  43986. // Put the blob into the dabase
  43987. var addRequest = transaction.objectStore("textures").put(newTexture);
  43988. addRequest.onsuccess = function (event) {
  43989. };
  43990. addRequest.onerror = function (event) {
  43991. generateBlobUrl();
  43992. };
  43993. }
  43994. catch (ex) {
  43995. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  43996. if (ex.code === 25) {
  43997. Database.IsUASupportingBlobStorage = false;
  43998. }
  43999. image.src = url;
  44000. }
  44001. }
  44002. else {
  44003. image.src = url;
  44004. }
  44005. }, false);
  44006. xhr.addEventListener("error", function (event) {
  44007. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  44008. image.src = url;
  44009. }, false);
  44010. xhr.send();
  44011. }
  44012. else {
  44013. image.src = url;
  44014. }
  44015. }
  44016. else {
  44017. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44018. image.src = url;
  44019. }
  44020. };
  44021. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  44022. var _this = this;
  44023. var updateVersion = function (event) {
  44024. // the version is not yet in the DB or we need to update it
  44025. _this._saveVersionIntoDBAsync(url, versionLoaded);
  44026. };
  44027. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  44028. };
  44029. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  44030. var _this = this;
  44031. if (this.isSupported) {
  44032. var version;
  44033. try {
  44034. var transaction = this.db.transaction(["versions"]);
  44035. transaction.oncomplete = function (event) {
  44036. if (version) {
  44037. // If the version in the JSON file is > than the version in DB
  44038. if (_this.manifestVersionFound > version.data) {
  44039. _this.mustUpdateRessources = true;
  44040. updateInDBCallback();
  44041. }
  44042. else {
  44043. callback(version.data);
  44044. }
  44045. }
  44046. else {
  44047. _this.mustUpdateRessources = true;
  44048. updateInDBCallback();
  44049. }
  44050. };
  44051. transaction.onabort = function (event) {
  44052. callback(-1);
  44053. };
  44054. var getRequest = transaction.objectStore("versions").get(url);
  44055. getRequest.onsuccess = function (event) {
  44056. version = (event.target).result;
  44057. };
  44058. getRequest.onerror = function (event) {
  44059. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  44060. callback(-1);
  44061. };
  44062. }
  44063. catch (ex) {
  44064. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  44065. callback(-1);
  44066. }
  44067. }
  44068. else {
  44069. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44070. callback(-1);
  44071. }
  44072. };
  44073. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  44074. var _this = this;
  44075. if (this.isSupported && !this.hasReachedQuota) {
  44076. try {
  44077. // Open a transaction to the database
  44078. var transaction = this.db.transaction(["versions"], "readwrite");
  44079. // the transaction could abort because of a QuotaExceededError error
  44080. transaction.onabort = function (event) {
  44081. try {
  44082. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  44083. _this.hasReachedQuota = true;
  44084. }
  44085. }
  44086. catch (ex) { }
  44087. callback(-1);
  44088. };
  44089. transaction.oncomplete = function (event) {
  44090. callback(_this.manifestVersionFound);
  44091. };
  44092. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  44093. // Put the scene into the database
  44094. var addRequest = transaction.objectStore("versions").put(newVersion);
  44095. addRequest.onsuccess = function (event) {
  44096. };
  44097. addRequest.onerror = function (event) {
  44098. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  44099. };
  44100. }
  44101. catch (ex) {
  44102. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  44103. callback(-1);
  44104. }
  44105. }
  44106. else {
  44107. callback(-1);
  44108. }
  44109. };
  44110. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  44111. var _this = this;
  44112. var completeUrl = Database.ReturnFullUrlLocation(url);
  44113. var saveAndLoadFile = function (event) {
  44114. // the scene is not yet in the DB, let's try to save it
  44115. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  44116. };
  44117. this._checkVersionFromDB(completeUrl, function (version) {
  44118. if (version !== -1) {
  44119. if (!_this.mustUpdateRessources) {
  44120. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  44121. }
  44122. else {
  44123. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  44124. }
  44125. }
  44126. else {
  44127. errorCallback();
  44128. }
  44129. });
  44130. };
  44131. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  44132. if (this.isSupported) {
  44133. var targetStore;
  44134. if (url.indexOf(".babylon") !== -1) {
  44135. targetStore = "scenes";
  44136. }
  44137. else {
  44138. targetStore = "textures";
  44139. }
  44140. var file;
  44141. var transaction = this.db.transaction([targetStore]);
  44142. transaction.oncomplete = function (event) {
  44143. if (file) {
  44144. callback(file.data);
  44145. }
  44146. else {
  44147. notInDBCallback();
  44148. }
  44149. };
  44150. transaction.onabort = function (event) {
  44151. notInDBCallback();
  44152. };
  44153. var getRequest = transaction.objectStore(targetStore).get(url);
  44154. getRequest.onsuccess = function (event) {
  44155. file = (event.target).result;
  44156. };
  44157. getRequest.onerror = function (event) {
  44158. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  44159. notInDBCallback();
  44160. };
  44161. }
  44162. else {
  44163. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44164. callback();
  44165. }
  44166. };
  44167. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  44168. var _this = this;
  44169. if (this.isSupported) {
  44170. var targetStore;
  44171. if (url.indexOf(".babylon") !== -1) {
  44172. targetStore = "scenes";
  44173. }
  44174. else {
  44175. targetStore = "textures";
  44176. }
  44177. // Create XHR
  44178. var xhr = new XMLHttpRequest(), fileData;
  44179. xhr.open("GET", url, true);
  44180. if (useArrayBuffer) {
  44181. xhr.responseType = "arraybuffer";
  44182. }
  44183. xhr.onprogress = progressCallback;
  44184. xhr.addEventListener("load", function () {
  44185. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  44186. // Blob as response (XHR2)
  44187. //fileData = xhr.responseText;
  44188. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  44189. if (!_this.hasReachedQuota) {
  44190. // Open a transaction to the database
  44191. var transaction = _this.db.transaction([targetStore], "readwrite");
  44192. // the transaction could abort because of a QuotaExceededError error
  44193. transaction.onabort = function (event) {
  44194. try {
  44195. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  44196. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  44197. _this.hasReachedQuota = true;
  44198. }
  44199. }
  44200. catch (ex) { }
  44201. callback(fileData);
  44202. };
  44203. transaction.oncomplete = function (event) {
  44204. callback(fileData);
  44205. };
  44206. var newFile;
  44207. if (targetStore === "scenes") {
  44208. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  44209. }
  44210. else {
  44211. newFile = { textureUrl: url, data: fileData };
  44212. }
  44213. try {
  44214. // Put the scene into the database
  44215. var addRequest = transaction.objectStore(targetStore).put(newFile);
  44216. addRequest.onsuccess = function (event) {
  44217. };
  44218. addRequest.onerror = function (event) {
  44219. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  44220. };
  44221. }
  44222. catch (ex) {
  44223. callback(fileData);
  44224. }
  44225. }
  44226. else {
  44227. callback(fileData);
  44228. }
  44229. }
  44230. else {
  44231. callback();
  44232. }
  44233. }, false);
  44234. xhr.addEventListener("error", function (event) {
  44235. BABYLON.Tools.Error("error on XHR request.");
  44236. callback();
  44237. }, false);
  44238. xhr.send();
  44239. }
  44240. else {
  44241. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  44242. callback();
  44243. }
  44244. };
  44245. return Database;
  44246. }());
  44247. Database.IsUASupportingBlobStorage = true;
  44248. Database.IDBStorageEnabled = true;
  44249. Database.parseURL = function (url) {
  44250. var a = document.createElement('a');
  44251. a.href = url;
  44252. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  44253. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  44254. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  44255. return absLocation;
  44256. };
  44257. Database.ReturnFullUrlLocation = function (url) {
  44258. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  44259. return (Database.parseURL(window.location.href) + url);
  44260. }
  44261. else {
  44262. return url;
  44263. }
  44264. };
  44265. BABYLON.Database = Database;
  44266. })(BABYLON || (BABYLON = {}));
  44267. //# sourceMappingURL=babylon.database.js.map
  44268. var BABYLON;
  44269. (function (BABYLON) {
  44270. var FresnelParameters = (function () {
  44271. function FresnelParameters() {
  44272. this._isEnabled = true;
  44273. this.leftColor = BABYLON.Color3.White();
  44274. this.rightColor = BABYLON.Color3.Black();
  44275. this.bias = 0;
  44276. this.power = 1;
  44277. }
  44278. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  44279. get: function () {
  44280. return this._isEnabled;
  44281. },
  44282. set: function (value) {
  44283. if (this._isEnabled === value) {
  44284. return;
  44285. }
  44286. this._isEnabled = value;
  44287. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44288. },
  44289. enumerable: true,
  44290. configurable: true
  44291. });
  44292. FresnelParameters.prototype.clone = function () {
  44293. var newFresnelParameters = new FresnelParameters();
  44294. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  44295. return newFresnelParameters;
  44296. };
  44297. FresnelParameters.prototype.serialize = function () {
  44298. var serializationObject = {};
  44299. serializationObject.isEnabled = this.isEnabled;
  44300. serializationObject.leftColor = this.leftColor;
  44301. serializationObject.rightColor = this.rightColor;
  44302. serializationObject.bias = this.bias;
  44303. serializationObject.power = this.power;
  44304. return serializationObject;
  44305. };
  44306. FresnelParameters.Parse = function (parsedFresnelParameters) {
  44307. var fresnelParameters = new FresnelParameters();
  44308. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  44309. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  44310. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  44311. fresnelParameters.bias = parsedFresnelParameters.bias;
  44312. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  44313. return fresnelParameters;
  44314. };
  44315. return FresnelParameters;
  44316. }());
  44317. BABYLON.FresnelParameters = FresnelParameters;
  44318. })(BABYLON || (BABYLON = {}));
  44319. //# sourceMappingURL=babylon.fresnelParameters.js.map
  44320. var BABYLON;
  44321. (function (BABYLON) {
  44322. var MultiMaterial = (function (_super) {
  44323. __extends(MultiMaterial, _super);
  44324. function MultiMaterial(name, scene) {
  44325. var _this = _super.call(this, name, scene, true) || this;
  44326. _this.subMaterials = new Array();
  44327. scene.multiMaterials.push(_this);
  44328. return _this;
  44329. }
  44330. // Properties
  44331. MultiMaterial.prototype.getSubMaterial = function (index) {
  44332. if (index < 0 || index >= this.subMaterials.length) {
  44333. return this.getScene().defaultMaterial;
  44334. }
  44335. return this.subMaterials[index];
  44336. };
  44337. // Methods
  44338. MultiMaterial.prototype.getClassName = function () {
  44339. return "MultiMaterial";
  44340. };
  44341. MultiMaterial.prototype.isReady = function (mesh) {
  44342. for (var index = 0; index < this.subMaterials.length; index++) {
  44343. var subMaterial = this.subMaterials[index];
  44344. if (subMaterial) {
  44345. if (!this.subMaterials[index].isReady(mesh)) {
  44346. return false;
  44347. }
  44348. }
  44349. }
  44350. return true;
  44351. };
  44352. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  44353. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  44354. for (var index = 0; index < this.subMaterials.length; index++) {
  44355. var subMaterial = null;
  44356. if (cloneChildren) {
  44357. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  44358. }
  44359. else {
  44360. subMaterial = this.subMaterials[index];
  44361. }
  44362. newMultiMaterial.subMaterials.push(subMaterial);
  44363. }
  44364. return newMultiMaterial;
  44365. };
  44366. MultiMaterial.prototype.serialize = function () {
  44367. var serializationObject = {};
  44368. serializationObject.name = this.name;
  44369. serializationObject.id = this.id;
  44370. serializationObject.tags = BABYLON.Tags.GetTags(this);
  44371. serializationObject.materials = [];
  44372. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  44373. var subMat = this.subMaterials[matIndex];
  44374. if (subMat) {
  44375. serializationObject.materials.push(subMat.id);
  44376. }
  44377. else {
  44378. serializationObject.materials.push(null);
  44379. }
  44380. }
  44381. return serializationObject;
  44382. };
  44383. return MultiMaterial;
  44384. }(BABYLON.Material));
  44385. BABYLON.MultiMaterial = MultiMaterial;
  44386. })(BABYLON || (BABYLON = {}));
  44387. //# sourceMappingURL=babylon.multiMaterial.js.map
  44388. var BABYLON;
  44389. (function (BABYLON) {
  44390. var FreeCameraTouchInput = (function () {
  44391. function FreeCameraTouchInput() {
  44392. this._offsetX = null;
  44393. this._offsetY = null;
  44394. this._pointerCount = 0;
  44395. this._pointerPressed = [];
  44396. this.touchAngularSensibility = 200000.0;
  44397. this.touchMoveSensibility = 250.0;
  44398. }
  44399. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  44400. var _this = this;
  44401. var previousPosition;
  44402. if (this._pointerInput === undefined) {
  44403. this._onLostFocus = function (evt) {
  44404. _this._offsetX = null;
  44405. _this._offsetY = null;
  44406. };
  44407. this._pointerInput = function (p, s) {
  44408. var evt = p.event;
  44409. if (evt.pointerType === "mouse") {
  44410. return;
  44411. }
  44412. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  44413. if (!noPreventDefault) {
  44414. evt.preventDefault();
  44415. }
  44416. _this._pointerPressed.push(evt.pointerId);
  44417. if (_this._pointerPressed.length !== 1) {
  44418. return;
  44419. }
  44420. previousPosition = {
  44421. x: evt.clientX,
  44422. y: evt.clientY
  44423. };
  44424. }
  44425. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  44426. if (!noPreventDefault) {
  44427. evt.preventDefault();
  44428. }
  44429. var index = _this._pointerPressed.indexOf(evt.pointerId);
  44430. if (index === -1) {
  44431. return;
  44432. }
  44433. _this._pointerPressed.splice(index, 1);
  44434. if (index != 0) {
  44435. return;
  44436. }
  44437. previousPosition = null;
  44438. _this._offsetX = null;
  44439. _this._offsetY = null;
  44440. }
  44441. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44442. if (!noPreventDefault) {
  44443. evt.preventDefault();
  44444. }
  44445. if (!previousPosition) {
  44446. return;
  44447. }
  44448. var index = _this._pointerPressed.indexOf(evt.pointerId);
  44449. if (index != 0) {
  44450. return;
  44451. }
  44452. _this._offsetX = evt.clientX - previousPosition.x;
  44453. _this._offsetY = -(evt.clientY - previousPosition.y);
  44454. }
  44455. };
  44456. }
  44457. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  44458. element.addEventListener("blur", this._onLostFocus);
  44459. };
  44460. FreeCameraTouchInput.prototype.detachControl = function (element) {
  44461. if (this._pointerInput && element) {
  44462. this.camera.getScene().onPointerObservable.remove(this._observer);
  44463. this._observer = null;
  44464. element.removeEventListener("blur", this._onLostFocus);
  44465. this._onLostFocus = null;
  44466. this._pointerPressed = [];
  44467. this._offsetX = null;
  44468. this._offsetY = null;
  44469. this._pointerCount = 0;
  44470. }
  44471. };
  44472. FreeCameraTouchInput.prototype.checkInputs = function () {
  44473. if (this._offsetX) {
  44474. var camera = this.camera;
  44475. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  44476. if (this._pointerPressed.length > 1) {
  44477. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  44478. }
  44479. else {
  44480. var speed = camera._computeLocalCameraSpeed();
  44481. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  44482. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  44483. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  44484. }
  44485. }
  44486. };
  44487. FreeCameraTouchInput.prototype.getTypeName = function () {
  44488. return "FreeCameraTouchInput";
  44489. };
  44490. FreeCameraTouchInput.prototype.getSimpleName = function () {
  44491. return "touch";
  44492. };
  44493. return FreeCameraTouchInput;
  44494. }());
  44495. __decorate([
  44496. BABYLON.serialize()
  44497. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  44498. __decorate([
  44499. BABYLON.serialize()
  44500. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  44501. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  44502. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  44503. })(BABYLON || (BABYLON = {}));
  44504. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  44505. /// <reference path="babylon.freeCamera.ts" />
  44506. var BABYLON;
  44507. (function (BABYLON) {
  44508. // We're mainly based on the logic defined into the FreeCamera code
  44509. var TouchCamera = (function (_super) {
  44510. __extends(TouchCamera, _super);
  44511. //-- end properties for backward compatibility for inputs
  44512. function TouchCamera(name, position, scene) {
  44513. var _this = _super.call(this, name, position, scene) || this;
  44514. _this.inputs.addTouch();
  44515. _this._setupInputs();
  44516. return _this;
  44517. }
  44518. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  44519. //-- Begin properties for backward compatibility for inputs
  44520. get: function () {
  44521. var touch = this.inputs.attached["touch"];
  44522. if (touch)
  44523. return touch.touchAngularSensibility;
  44524. },
  44525. set: function (value) {
  44526. var touch = this.inputs.attached["touch"];
  44527. if (touch)
  44528. touch.touchAngularSensibility = value;
  44529. },
  44530. enumerable: true,
  44531. configurable: true
  44532. });
  44533. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  44534. get: function () {
  44535. var touch = this.inputs.attached["touch"];
  44536. if (touch)
  44537. return touch.touchMoveSensibility;
  44538. },
  44539. set: function (value) {
  44540. var touch = this.inputs.attached["touch"];
  44541. if (touch)
  44542. touch.touchMoveSensibility = value;
  44543. },
  44544. enumerable: true,
  44545. configurable: true
  44546. });
  44547. TouchCamera.prototype.getClassName = function () {
  44548. return "TouchCamera";
  44549. };
  44550. TouchCamera.prototype._setupInputs = function () {
  44551. var mouse = this.inputs.attached["mouse"];
  44552. if (mouse) {
  44553. mouse.touchEnabled = false;
  44554. }
  44555. };
  44556. return TouchCamera;
  44557. }(BABYLON.FreeCamera));
  44558. BABYLON.TouchCamera = TouchCamera;
  44559. })(BABYLON || (BABYLON = {}));
  44560. //# sourceMappingURL=babylon.touchCamera.js.map
  44561. var BABYLON;
  44562. (function (BABYLON) {
  44563. var ProceduralTexture = (function (_super) {
  44564. __extends(ProceduralTexture, _super);
  44565. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  44566. if (generateMipMaps === void 0) { generateMipMaps = true; }
  44567. if (isCube === void 0) { isCube = false; }
  44568. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  44569. _this.isCube = isCube;
  44570. _this.isEnabled = true;
  44571. _this._currentRefreshId = -1;
  44572. _this._refreshRate = 1;
  44573. _this._vertexBuffers = {};
  44574. _this._uniforms = new Array();
  44575. _this._samplers = new Array();
  44576. _this._textures = new Array();
  44577. _this._floats = new Array();
  44578. _this._floatsArrays = {};
  44579. _this._colors3 = new Array();
  44580. _this._colors4 = new Array();
  44581. _this._vectors2 = new Array();
  44582. _this._vectors3 = new Array();
  44583. _this._matrices = new Array();
  44584. _this._fallbackTextureUsed = false;
  44585. scene._proceduralTextures.push(_this);
  44586. _this.name = name;
  44587. _this.isRenderTarget = true;
  44588. _this._size = size;
  44589. _this._generateMipMaps = generateMipMaps;
  44590. _this.setFragment(fragment);
  44591. _this._fallbackTexture = fallbackTexture;
  44592. var engine = scene.getEngine();
  44593. if (isCube) {
  44594. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  44595. _this.setFloat("face", 0);
  44596. }
  44597. else {
  44598. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  44599. }
  44600. // VBO
  44601. var vertices = [];
  44602. vertices.push(1, 1);
  44603. vertices.push(-1, 1);
  44604. vertices.push(-1, -1);
  44605. vertices.push(1, -1);
  44606. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  44607. // Indices
  44608. var indices = [];
  44609. indices.push(0);
  44610. indices.push(1);
  44611. indices.push(2);
  44612. indices.push(0);
  44613. indices.push(2);
  44614. indices.push(3);
  44615. _this._indexBuffer = engine.createIndexBuffer(indices);
  44616. return _this;
  44617. }
  44618. ProceduralTexture.prototype.reset = function () {
  44619. if (this._effect === undefined) {
  44620. return;
  44621. }
  44622. var engine = this.getScene().getEngine();
  44623. engine._releaseEffect(this._effect);
  44624. };
  44625. ProceduralTexture.prototype.isReady = function () {
  44626. var _this = this;
  44627. var engine = this.getScene().getEngine();
  44628. var shaders;
  44629. if (!this._fragment) {
  44630. return false;
  44631. }
  44632. if (this._fallbackTextureUsed) {
  44633. return true;
  44634. }
  44635. if (this._fragment.fragmentElement !== undefined) {
  44636. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  44637. }
  44638. else {
  44639. shaders = { vertex: "procedural", fragment: this._fragment };
  44640. }
  44641. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  44642. _this.releaseInternalTexture();
  44643. if (_this._fallbackTexture) {
  44644. _this._texture = _this._fallbackTexture._texture;
  44645. _this._texture.references++;
  44646. }
  44647. _this._fallbackTextureUsed = true;
  44648. });
  44649. return this._effect.isReady();
  44650. };
  44651. ProceduralTexture.prototype.resetRefreshCounter = function () {
  44652. this._currentRefreshId = -1;
  44653. };
  44654. ProceduralTexture.prototype.setFragment = function (fragment) {
  44655. this._fragment = fragment;
  44656. };
  44657. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  44658. get: function () {
  44659. return this._refreshRate;
  44660. },
  44661. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  44662. set: function (value) {
  44663. this._refreshRate = value;
  44664. this.resetRefreshCounter();
  44665. },
  44666. enumerable: true,
  44667. configurable: true
  44668. });
  44669. ProceduralTexture.prototype._shouldRender = function () {
  44670. if (!this.isEnabled || !this.isReady() || !this._texture) {
  44671. return false;
  44672. }
  44673. if (this._fallbackTextureUsed) {
  44674. return false;
  44675. }
  44676. if (this._currentRefreshId === -1) {
  44677. this._currentRefreshId = 1;
  44678. return true;
  44679. }
  44680. if (this.refreshRate === this._currentRefreshId) {
  44681. this._currentRefreshId = 1;
  44682. return true;
  44683. }
  44684. this._currentRefreshId++;
  44685. return false;
  44686. };
  44687. ProceduralTexture.prototype.getRenderSize = function () {
  44688. return this._size;
  44689. };
  44690. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  44691. if (this._fallbackTextureUsed) {
  44692. return;
  44693. }
  44694. this.releaseInternalTexture();
  44695. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  44696. };
  44697. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  44698. if (this._uniforms.indexOf(uniformName) === -1) {
  44699. this._uniforms.push(uniformName);
  44700. }
  44701. };
  44702. ProceduralTexture.prototype.setTexture = function (name, texture) {
  44703. if (this._samplers.indexOf(name) === -1) {
  44704. this._samplers.push(name);
  44705. }
  44706. this._textures[name] = texture;
  44707. return this;
  44708. };
  44709. ProceduralTexture.prototype.setFloat = function (name, value) {
  44710. this._checkUniform(name);
  44711. this._floats[name] = value;
  44712. return this;
  44713. };
  44714. ProceduralTexture.prototype.setFloats = function (name, value) {
  44715. this._checkUniform(name);
  44716. this._floatsArrays[name] = value;
  44717. return this;
  44718. };
  44719. ProceduralTexture.prototype.setColor3 = function (name, value) {
  44720. this._checkUniform(name);
  44721. this._colors3[name] = value;
  44722. return this;
  44723. };
  44724. ProceduralTexture.prototype.setColor4 = function (name, value) {
  44725. this._checkUniform(name);
  44726. this._colors4[name] = value;
  44727. return this;
  44728. };
  44729. ProceduralTexture.prototype.setVector2 = function (name, value) {
  44730. this._checkUniform(name);
  44731. this._vectors2[name] = value;
  44732. return this;
  44733. };
  44734. ProceduralTexture.prototype.setVector3 = function (name, value) {
  44735. this._checkUniform(name);
  44736. this._vectors3[name] = value;
  44737. return this;
  44738. };
  44739. ProceduralTexture.prototype.setMatrix = function (name, value) {
  44740. this._checkUniform(name);
  44741. this._matrices[name] = value;
  44742. return this;
  44743. };
  44744. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  44745. var scene = this.getScene();
  44746. var engine = scene.getEngine();
  44747. // Render
  44748. engine.enableEffect(this._effect);
  44749. engine.setState(false);
  44750. // Texture
  44751. for (var name in this._textures) {
  44752. this._effect.setTexture(name, this._textures[name]);
  44753. }
  44754. // Float
  44755. for (name in this._floats) {
  44756. this._effect.setFloat(name, this._floats[name]);
  44757. }
  44758. // Floats
  44759. for (name in this._floatsArrays) {
  44760. this._effect.setArray(name, this._floatsArrays[name]);
  44761. }
  44762. // Color3
  44763. for (name in this._colors3) {
  44764. this._effect.setColor3(name, this._colors3[name]);
  44765. }
  44766. // Color4
  44767. for (name in this._colors4) {
  44768. var color = this._colors4[name];
  44769. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  44770. }
  44771. // Vector2
  44772. for (name in this._vectors2) {
  44773. this._effect.setVector2(name, this._vectors2[name]);
  44774. }
  44775. // Vector3
  44776. for (name in this._vectors3) {
  44777. this._effect.setVector3(name, this._vectors3[name]);
  44778. }
  44779. // Matrix
  44780. for (name in this._matrices) {
  44781. this._effect.setMatrix(name, this._matrices[name]);
  44782. }
  44783. if (this.isCube) {
  44784. for (var face = 0; face < 6; face++) {
  44785. engine.bindFramebuffer(this._texture, face);
  44786. // VBOs
  44787. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  44788. this._effect.setFloat("face", face);
  44789. // Clear
  44790. engine.clear(scene.clearColor, true, true, true);
  44791. // Draw order
  44792. engine.draw(true, 0, 6);
  44793. // Mipmaps
  44794. if (face === 5) {
  44795. engine.generateMipMapsForCubemap(this._texture);
  44796. }
  44797. }
  44798. }
  44799. else {
  44800. engine.bindFramebuffer(this._texture);
  44801. // VBOs
  44802. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  44803. // Clear
  44804. engine.clear(scene.clearColor, true, true, true);
  44805. // Draw order
  44806. engine.draw(true, 0, 6);
  44807. }
  44808. // Unbind
  44809. engine.unBindFramebuffer(this._texture, this.isCube);
  44810. if (this.onGenerated) {
  44811. this.onGenerated();
  44812. }
  44813. };
  44814. ProceduralTexture.prototype.clone = function () {
  44815. var textureSize = this.getSize();
  44816. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  44817. // Base texture
  44818. newTexture.hasAlpha = this.hasAlpha;
  44819. newTexture.level = this.level;
  44820. // RenderTarget Texture
  44821. newTexture.coordinatesMode = this.coordinatesMode;
  44822. return newTexture;
  44823. };
  44824. ProceduralTexture.prototype.dispose = function () {
  44825. var index = this.getScene()._proceduralTextures.indexOf(this);
  44826. if (index >= 0) {
  44827. this.getScene()._proceduralTextures.splice(index, 1);
  44828. }
  44829. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  44830. if (vertexBuffer) {
  44831. vertexBuffer.dispose();
  44832. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  44833. }
  44834. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  44835. this._indexBuffer = null;
  44836. }
  44837. _super.prototype.dispose.call(this);
  44838. };
  44839. return ProceduralTexture;
  44840. }(BABYLON.Texture));
  44841. BABYLON.ProceduralTexture = ProceduralTexture;
  44842. })(BABYLON || (BABYLON = {}));
  44843. //# sourceMappingURL=babylon.proceduralTexture.js.map
  44844. /// <reference path="babylon.proceduralTexture.ts" />
  44845. var BABYLON;
  44846. (function (BABYLON) {
  44847. var CustomProceduralTexture = (function (_super) {
  44848. __extends(CustomProceduralTexture, _super);
  44849. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  44850. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  44851. _this._animate = true;
  44852. _this._time = 0;
  44853. _this._texturePath = texturePath;
  44854. //Try to load json
  44855. _this.loadJson(texturePath);
  44856. _this.refreshRate = 1;
  44857. return _this;
  44858. }
  44859. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  44860. var _this = this;
  44861. var that = this;
  44862. function noConfigFile() {
  44863. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  44864. try {
  44865. that.setFragment(that._texturePath);
  44866. }
  44867. catch (ex) {
  44868. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  44869. }
  44870. }
  44871. var configFileUrl = jsonUrl + "/config.json";
  44872. var xhr = new XMLHttpRequest();
  44873. xhr.open("GET", configFileUrl, true);
  44874. xhr.addEventListener("load", function () {
  44875. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  44876. try {
  44877. _this._config = JSON.parse(xhr.response);
  44878. _this.updateShaderUniforms();
  44879. _this.updateTextures();
  44880. _this.setFragment(_this._texturePath + "/custom");
  44881. _this._animate = _this._config.animate;
  44882. _this.refreshRate = _this._config.refreshrate;
  44883. }
  44884. catch (ex) {
  44885. noConfigFile();
  44886. }
  44887. }
  44888. else {
  44889. noConfigFile();
  44890. }
  44891. }, false);
  44892. xhr.addEventListener("error", function () {
  44893. noConfigFile();
  44894. }, false);
  44895. try {
  44896. xhr.send();
  44897. }
  44898. catch (ex) {
  44899. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  44900. }
  44901. };
  44902. CustomProceduralTexture.prototype.isReady = function () {
  44903. if (!_super.prototype.isReady.call(this)) {
  44904. return false;
  44905. }
  44906. for (var name in this._textures) {
  44907. var texture = this._textures[name];
  44908. if (!texture.isReady()) {
  44909. return false;
  44910. }
  44911. }
  44912. return true;
  44913. };
  44914. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  44915. if (this._animate) {
  44916. this._time += this.getScene().getAnimationRatio() * 0.03;
  44917. this.updateShaderUniforms();
  44918. }
  44919. _super.prototype.render.call(this, useCameraPostProcess);
  44920. };
  44921. CustomProceduralTexture.prototype.updateTextures = function () {
  44922. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  44923. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  44924. }
  44925. };
  44926. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  44927. if (this._config) {
  44928. for (var j = 0; j < this._config.uniforms.length; j++) {
  44929. var uniform = this._config.uniforms[j];
  44930. switch (uniform.type) {
  44931. case "float":
  44932. this.setFloat(uniform.name, uniform.value);
  44933. break;
  44934. case "color3":
  44935. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  44936. break;
  44937. case "color4":
  44938. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  44939. break;
  44940. case "vector2":
  44941. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  44942. break;
  44943. case "vector3":
  44944. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  44945. break;
  44946. }
  44947. }
  44948. }
  44949. this.setFloat("time", this._time);
  44950. };
  44951. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  44952. get: function () {
  44953. return this._animate;
  44954. },
  44955. set: function (value) {
  44956. this._animate = value;
  44957. },
  44958. enumerable: true,
  44959. configurable: true
  44960. });
  44961. return CustomProceduralTexture;
  44962. }(BABYLON.ProceduralTexture));
  44963. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  44964. })(BABYLON || (BABYLON = {}));
  44965. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  44966. var BABYLON;
  44967. (function (BABYLON) {
  44968. var FreeCameraGamepadInput = (function () {
  44969. function FreeCameraGamepadInput() {
  44970. this.gamepadAngularSensibility = 200;
  44971. this.gamepadMoveSensibility = 40;
  44972. // private members
  44973. this._cameraTransform = BABYLON.Matrix.Identity();
  44974. this._deltaTransform = BABYLON.Vector3.Zero();
  44975. this._vector3 = BABYLON.Vector3.Zero();
  44976. this._vector2 = BABYLON.Vector2.Zero();
  44977. }
  44978. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  44979. var _this = this;
  44980. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  44981. };
  44982. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  44983. if (this._gamepads) {
  44984. this._gamepads.dispose();
  44985. }
  44986. this.gamepad = null;
  44987. };
  44988. FreeCameraGamepadInput.prototype.checkInputs = function () {
  44989. if (this.gamepad && this.gamepad.leftStick) {
  44990. var camera = this.camera;
  44991. var LSValues = this.gamepad.leftStick;
  44992. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  44993. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  44994. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  44995. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  44996. var RSValues = this.gamepad.rightStick;
  44997. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  44998. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  44999. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  45000. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  45001. if (!camera.rotationQuaternion) {
  45002. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  45003. }
  45004. else {
  45005. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  45006. }
  45007. var speed = camera._computeLocalCameraSpeed() * 50.0;
  45008. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  45009. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  45010. camera.cameraDirection.addInPlace(this._deltaTransform);
  45011. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  45012. camera.cameraRotation.addInPlace(this._vector2);
  45013. }
  45014. };
  45015. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  45016. // Only the first gamepad found can control the camera
  45017. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  45018. // prioritize XBOX gamepads.
  45019. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  45020. this.gamepad = gamepad;
  45021. }
  45022. }
  45023. };
  45024. FreeCameraGamepadInput.prototype.getTypeName = function () {
  45025. return "FreeCameraGamepadInput";
  45026. };
  45027. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  45028. return "gamepad";
  45029. };
  45030. return FreeCameraGamepadInput;
  45031. }());
  45032. __decorate([
  45033. BABYLON.serialize()
  45034. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  45035. __decorate([
  45036. BABYLON.serialize()
  45037. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  45038. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  45039. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  45040. })(BABYLON || (BABYLON = {}));
  45041. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  45042. var BABYLON;
  45043. (function (BABYLON) {
  45044. var ArcRotateCameraGamepadInput = (function () {
  45045. function ArcRotateCameraGamepadInput() {
  45046. this.gamepadRotationSensibility = 80;
  45047. this.gamepadMoveSensibility = 40;
  45048. }
  45049. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  45050. var _this = this;
  45051. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  45052. };
  45053. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  45054. if (this._gamepads) {
  45055. this._gamepads.dispose();
  45056. }
  45057. this.gamepad = null;
  45058. };
  45059. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  45060. if (this.gamepad) {
  45061. var camera = this.camera;
  45062. var RSValues = this.gamepad.rightStick;
  45063. if (RSValues.x != 0) {
  45064. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  45065. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  45066. camera.inertialAlphaOffset += normalizedRX;
  45067. }
  45068. }
  45069. if (RSValues.y != 0) {
  45070. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  45071. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  45072. camera.inertialBetaOffset += normalizedRY;
  45073. }
  45074. }
  45075. var LSValues = this.gamepad.leftStick;
  45076. if (LSValues.y != 0) {
  45077. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  45078. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  45079. this.camera.inertialRadiusOffset -= normalizedLY;
  45080. }
  45081. }
  45082. }
  45083. };
  45084. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  45085. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  45086. // prioritize XBOX gamepads.
  45087. if (!this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  45088. this.gamepad = gamepad;
  45089. }
  45090. }
  45091. };
  45092. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  45093. return "ArcRotateCameraGamepadInput";
  45094. };
  45095. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  45096. return "gamepad";
  45097. };
  45098. return ArcRotateCameraGamepadInput;
  45099. }());
  45100. __decorate([
  45101. BABYLON.serialize()
  45102. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  45103. __decorate([
  45104. BABYLON.serialize()
  45105. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  45106. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  45107. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  45108. })(BABYLON || (BABYLON = {}));
  45109. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  45110. var BABYLON;
  45111. (function (BABYLON) {
  45112. var Gamepads = (function () {
  45113. function Gamepads(ongamedpadconnected) {
  45114. var _this = this;
  45115. this.babylonGamepads = [];
  45116. this.oneGamepadConnected = false;
  45117. this.isMonitoring = false;
  45118. this.gamepadEventSupported = 'GamepadEvent' in window;
  45119. this.gamepadSupport = (navigator.getGamepads ||
  45120. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  45121. this._callbackGamepadConnected = ongamedpadconnected;
  45122. if (this.gamepadSupport) {
  45123. //first add already-connected gamepads
  45124. this._updateGamepadObjects();
  45125. if (this.babylonGamepads.length) {
  45126. this._startMonitoringGamepads();
  45127. }
  45128. // Checking if the gamepad connected event is supported (like in Firefox)
  45129. if (this.gamepadEventSupported) {
  45130. this._onGamepadConnectedEvent = function (evt) {
  45131. _this._onGamepadConnected(evt.gamepad);
  45132. };
  45133. this._onGamepadDisonnectedEvent = function (evt) {
  45134. _this._onGamepadDisconnected(evt);
  45135. };
  45136. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45137. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45138. }
  45139. else {
  45140. this._startMonitoringGamepads();
  45141. }
  45142. }
  45143. }
  45144. Gamepads.prototype.dispose = function () {
  45145. if (Gamepads.gamepadDOMInfo) {
  45146. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45147. }
  45148. if (this._onGamepadConnectedEvent) {
  45149. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  45150. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  45151. this._onGamepadConnectedEvent = null;
  45152. this._onGamepadDisonnectedEvent = null;
  45153. }
  45154. };
  45155. Gamepads.prototype._onGamepadConnected = function (gamepad) {
  45156. var newGamepad = this._addNewGamepad(gamepad);
  45157. if (this._callbackGamepadConnected)
  45158. this._callbackGamepadConnected(newGamepad);
  45159. this._startMonitoringGamepads();
  45160. };
  45161. Gamepads.prototype._addNewGamepad = function (gamepad) {
  45162. if (!this.oneGamepadConnected) {
  45163. this.oneGamepadConnected = true;
  45164. if (Gamepads.gamepadDOMInfo) {
  45165. document.body.removeChild(Gamepads.gamepadDOMInfo);
  45166. Gamepads.gamepadDOMInfo = null;
  45167. }
  45168. }
  45169. var newGamepad;
  45170. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  45171. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  45172. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  45173. }
  45174. else if (gamepad.pose) {
  45175. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  45176. }
  45177. else {
  45178. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  45179. }
  45180. this.babylonGamepads.push(newGamepad);
  45181. return newGamepad;
  45182. };
  45183. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  45184. // Remove the gamepad from the list of gamepads to monitor.
  45185. for (var i in this.babylonGamepads) {
  45186. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  45187. this.babylonGamepads.splice(+i, 1);
  45188. break;
  45189. }
  45190. }
  45191. // If no gamepads are left, stop the polling loop.
  45192. if (this.babylonGamepads.length == 0) {
  45193. this._stopMonitoringGamepads();
  45194. }
  45195. };
  45196. Gamepads.prototype._startMonitoringGamepads = function () {
  45197. if (!this.isMonitoring) {
  45198. this.isMonitoring = true;
  45199. this._checkGamepadsStatus();
  45200. }
  45201. };
  45202. Gamepads.prototype._stopMonitoringGamepads = function () {
  45203. this.isMonitoring = false;
  45204. };
  45205. Gamepads.prototype._checkGamepadsStatus = function () {
  45206. var _this = this;
  45207. // updating gamepad objects
  45208. this._updateGamepadObjects();
  45209. for (var i in this.babylonGamepads) {
  45210. this.babylonGamepads[i].update();
  45211. }
  45212. if (this.isMonitoring) {
  45213. if (window.requestAnimationFrame) {
  45214. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45215. }
  45216. else if (window.mozRequestAnimationFrame) {
  45217. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45218. }
  45219. else if (window.webkitRequestAnimationFrame) {
  45220. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45221. }
  45222. }
  45223. };
  45224. // This function is called only on Chrome, which does not yet support
  45225. // connection/disconnection events, but requires you to monitor
  45226. // an array for changes.
  45227. Gamepads.prototype._updateGamepadObjects = function () {
  45228. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  45229. for (var i = 0; i < gamepads.length; i++) {
  45230. if (gamepads[i]) {
  45231. if (!(gamepads[i].index in this.babylonGamepads)) {
  45232. var newGamepad = this._addNewGamepad(gamepads[i]);
  45233. if (this._callbackGamepadConnected) {
  45234. this._callbackGamepadConnected(newGamepad);
  45235. }
  45236. }
  45237. else {
  45238. this.babylonGamepads[i].browserGamepad = gamepads[i];
  45239. }
  45240. }
  45241. }
  45242. };
  45243. return Gamepads;
  45244. }());
  45245. BABYLON.Gamepads = Gamepads;
  45246. var StickValues = (function () {
  45247. function StickValues(x, y) {
  45248. this.x = x;
  45249. this.y = y;
  45250. }
  45251. return StickValues;
  45252. }());
  45253. BABYLON.StickValues = StickValues;
  45254. var Gamepad = (function () {
  45255. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  45256. if (leftStickX === void 0) { leftStickX = 0; }
  45257. if (leftStickY === void 0) { leftStickY = 1; }
  45258. if (rightStickX === void 0) { rightStickX = 2; }
  45259. if (rightStickY === void 0) { rightStickY = 3; }
  45260. this.id = id;
  45261. this.index = index;
  45262. this.browserGamepad = browserGamepad;
  45263. this.type = Gamepad.GAMEPAD;
  45264. this._leftStickAxisX = leftStickX;
  45265. this._leftStickAxisY = leftStickY;
  45266. this._rightStickAxisX = rightStickX;
  45267. this._rightStickAxisY = rightStickY;
  45268. if (this.browserGamepad.axes.length >= 2) {
  45269. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  45270. }
  45271. if (this.browserGamepad.axes.length >= 4) {
  45272. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  45273. }
  45274. }
  45275. Gamepad.prototype.onleftstickchanged = function (callback) {
  45276. this._onleftstickchanged = callback;
  45277. };
  45278. Gamepad.prototype.onrightstickchanged = function (callback) {
  45279. this._onrightstickchanged = callback;
  45280. };
  45281. Object.defineProperty(Gamepad.prototype, "leftStick", {
  45282. get: function () {
  45283. return this._leftStick;
  45284. },
  45285. set: function (newValues) {
  45286. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  45287. this._onleftstickchanged(newValues);
  45288. }
  45289. this._leftStick = newValues;
  45290. },
  45291. enumerable: true,
  45292. configurable: true
  45293. });
  45294. Object.defineProperty(Gamepad.prototype, "rightStick", {
  45295. get: function () {
  45296. return this._rightStick;
  45297. },
  45298. set: function (newValues) {
  45299. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  45300. this._onrightstickchanged(newValues);
  45301. }
  45302. this._rightStick = newValues;
  45303. },
  45304. enumerable: true,
  45305. configurable: true
  45306. });
  45307. Gamepad.prototype.update = function () {
  45308. if (this._leftStick) {
  45309. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  45310. }
  45311. if (this._rightStick) {
  45312. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  45313. }
  45314. };
  45315. return Gamepad;
  45316. }());
  45317. Gamepad.GAMEPAD = 0;
  45318. Gamepad.GENERIC = 1;
  45319. Gamepad.XBOX = 2;
  45320. Gamepad.POSE_ENABLED = 3;
  45321. BABYLON.Gamepad = Gamepad;
  45322. var GenericPad = (function (_super) {
  45323. __extends(GenericPad, _super);
  45324. function GenericPad(id, index, gamepad) {
  45325. var _this = _super.call(this, id, index, gamepad) || this;
  45326. _this.id = id;
  45327. _this.index = index;
  45328. _this.gamepad = gamepad;
  45329. _this.type = Gamepad.GENERIC;
  45330. _this._buttons = new Array(gamepad.buttons.length);
  45331. return _this;
  45332. }
  45333. GenericPad.prototype.onbuttondown = function (callback) {
  45334. this._onbuttondown = callback;
  45335. };
  45336. GenericPad.prototype.onbuttonup = function (callback) {
  45337. this._onbuttonup = callback;
  45338. };
  45339. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  45340. if (newValue !== currentValue) {
  45341. if (this._onbuttondown && newValue === 1) {
  45342. this._onbuttondown(buttonIndex);
  45343. }
  45344. if (this._onbuttonup && newValue === 0) {
  45345. this._onbuttonup(buttonIndex);
  45346. }
  45347. }
  45348. return newValue;
  45349. };
  45350. GenericPad.prototype.update = function () {
  45351. _super.prototype.update.call(this);
  45352. for (var index = 0; index < this._buttons.length; index++) {
  45353. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  45354. }
  45355. };
  45356. return GenericPad;
  45357. }(Gamepad));
  45358. BABYLON.GenericPad = GenericPad;
  45359. var Xbox360Button;
  45360. (function (Xbox360Button) {
  45361. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  45362. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  45363. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  45364. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  45365. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  45366. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  45367. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  45368. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  45369. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  45370. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  45371. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  45372. var Xbox360Dpad;
  45373. (function (Xbox360Dpad) {
  45374. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  45375. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  45376. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  45377. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  45378. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  45379. var Xbox360Pad = (function (_super) {
  45380. __extends(Xbox360Pad, _super);
  45381. function Xbox360Pad(id, index, gamepad, xboxOne) {
  45382. if (xboxOne === void 0) { xboxOne = false; }
  45383. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  45384. _this._leftTrigger = 0;
  45385. _this._rightTrigger = 0;
  45386. _this._buttonA = 0;
  45387. _this._buttonB = 0;
  45388. _this._buttonX = 0;
  45389. _this._buttonY = 0;
  45390. _this._buttonBack = 0;
  45391. _this._buttonStart = 0;
  45392. _this._buttonLB = 0;
  45393. _this._buttonRB = 0;
  45394. _this._buttonLeftStick = 0;
  45395. _this._buttonRightStick = 0;
  45396. _this._dPadUp = 0;
  45397. _this._dPadDown = 0;
  45398. _this._dPadLeft = 0;
  45399. _this._dPadRight = 0;
  45400. _this._isXboxOnePad = false;
  45401. _this.type = Gamepad.XBOX;
  45402. _this._isXboxOnePad = xboxOne;
  45403. return _this;
  45404. }
  45405. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  45406. this._onlefttriggerchanged = callback;
  45407. };
  45408. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  45409. this._onrighttriggerchanged = callback;
  45410. };
  45411. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  45412. get: function () {
  45413. return this._leftTrigger;
  45414. },
  45415. set: function (newValue) {
  45416. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  45417. this._onlefttriggerchanged(newValue);
  45418. }
  45419. this._leftTrigger = newValue;
  45420. },
  45421. enumerable: true,
  45422. configurable: true
  45423. });
  45424. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  45425. get: function () {
  45426. return this._rightTrigger;
  45427. },
  45428. set: function (newValue) {
  45429. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  45430. this._onrighttriggerchanged(newValue);
  45431. }
  45432. this._rightTrigger = newValue;
  45433. },
  45434. enumerable: true,
  45435. configurable: true
  45436. });
  45437. Xbox360Pad.prototype.onbuttondown = function (callback) {
  45438. this._onbuttondown = callback;
  45439. };
  45440. Xbox360Pad.prototype.onbuttonup = function (callback) {
  45441. this._onbuttonup = callback;
  45442. };
  45443. Xbox360Pad.prototype.ondpaddown = function (callback) {
  45444. this._ondpaddown = callback;
  45445. };
  45446. Xbox360Pad.prototype.ondpadup = function (callback) {
  45447. this._ondpadup = callback;
  45448. };
  45449. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  45450. if (newValue !== currentValue) {
  45451. if (this._onbuttondown && newValue === 1) {
  45452. this._onbuttondown(buttonType);
  45453. }
  45454. if (this._onbuttonup && newValue === 0) {
  45455. this._onbuttonup(buttonType);
  45456. }
  45457. }
  45458. return newValue;
  45459. };
  45460. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  45461. if (newValue !== currentValue) {
  45462. if (this._ondpaddown && newValue === 1) {
  45463. this._ondpaddown(buttonType);
  45464. }
  45465. if (this._ondpadup && newValue === 0) {
  45466. this._ondpadup(buttonType);
  45467. }
  45468. }
  45469. return newValue;
  45470. };
  45471. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  45472. get: function () {
  45473. return this._buttonA;
  45474. },
  45475. set: function (value) {
  45476. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  45477. },
  45478. enumerable: true,
  45479. configurable: true
  45480. });
  45481. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  45482. get: function () {
  45483. return this._buttonB;
  45484. },
  45485. set: function (value) {
  45486. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  45487. },
  45488. enumerable: true,
  45489. configurable: true
  45490. });
  45491. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  45492. get: function () {
  45493. return this._buttonX;
  45494. },
  45495. set: function (value) {
  45496. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  45497. },
  45498. enumerable: true,
  45499. configurable: true
  45500. });
  45501. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  45502. get: function () {
  45503. return this._buttonY;
  45504. },
  45505. set: function (value) {
  45506. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  45507. },
  45508. enumerable: true,
  45509. configurable: true
  45510. });
  45511. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  45512. get: function () {
  45513. return this._buttonStart;
  45514. },
  45515. set: function (value) {
  45516. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  45517. },
  45518. enumerable: true,
  45519. configurable: true
  45520. });
  45521. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  45522. get: function () {
  45523. return this._buttonBack;
  45524. },
  45525. set: function (value) {
  45526. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  45527. },
  45528. enumerable: true,
  45529. configurable: true
  45530. });
  45531. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  45532. get: function () {
  45533. return this._buttonLB;
  45534. },
  45535. set: function (value) {
  45536. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  45537. },
  45538. enumerable: true,
  45539. configurable: true
  45540. });
  45541. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  45542. get: function () {
  45543. return this._buttonRB;
  45544. },
  45545. set: function (value) {
  45546. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  45547. },
  45548. enumerable: true,
  45549. configurable: true
  45550. });
  45551. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  45552. get: function () {
  45553. return this._buttonLeftStick;
  45554. },
  45555. set: function (value) {
  45556. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  45557. },
  45558. enumerable: true,
  45559. configurable: true
  45560. });
  45561. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  45562. get: function () {
  45563. return this._buttonRightStick;
  45564. },
  45565. set: function (value) {
  45566. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  45567. },
  45568. enumerable: true,
  45569. configurable: true
  45570. });
  45571. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  45572. get: function () {
  45573. return this._dPadUp;
  45574. },
  45575. set: function (value) {
  45576. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  45577. },
  45578. enumerable: true,
  45579. configurable: true
  45580. });
  45581. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  45582. get: function () {
  45583. return this._dPadDown;
  45584. },
  45585. set: function (value) {
  45586. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  45587. },
  45588. enumerable: true,
  45589. configurable: true
  45590. });
  45591. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  45592. get: function () {
  45593. return this._dPadLeft;
  45594. },
  45595. set: function (value) {
  45596. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  45597. },
  45598. enumerable: true,
  45599. configurable: true
  45600. });
  45601. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  45602. get: function () {
  45603. return this._dPadRight;
  45604. },
  45605. set: function (value) {
  45606. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  45607. },
  45608. enumerable: true,
  45609. configurable: true
  45610. });
  45611. Xbox360Pad.prototype.update = function () {
  45612. _super.prototype.update.call(this);
  45613. if (this._isXboxOnePad) {
  45614. this.buttonA = this.browserGamepad.buttons[0].value;
  45615. this.buttonB = this.browserGamepad.buttons[1].value;
  45616. this.buttonX = this.browserGamepad.buttons[2].value;
  45617. this.buttonY = this.browserGamepad.buttons[3].value;
  45618. this.buttonLB = this.browserGamepad.buttons[4].value;
  45619. this.buttonRB = this.browserGamepad.buttons[5].value;
  45620. this.leftTrigger = this.browserGamepad.axes[2];
  45621. this.rightTrigger = this.browserGamepad.axes[5];
  45622. this.buttonBack = this.browserGamepad.buttons[9].value;
  45623. this.buttonStart = this.browserGamepad.buttons[8].value;
  45624. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  45625. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  45626. this.dPadUp = this.browserGamepad.buttons[11].value;
  45627. this.dPadDown = this.browserGamepad.buttons[12].value;
  45628. this.dPadLeft = this.browserGamepad.buttons[13].value;
  45629. this.dPadRight = this.browserGamepad.buttons[14].value;
  45630. }
  45631. else {
  45632. this.buttonA = this.browserGamepad.buttons[0].value;
  45633. this.buttonB = this.browserGamepad.buttons[1].value;
  45634. this.buttonX = this.browserGamepad.buttons[2].value;
  45635. this.buttonY = this.browserGamepad.buttons[3].value;
  45636. this.buttonLB = this.browserGamepad.buttons[4].value;
  45637. this.buttonRB = this.browserGamepad.buttons[5].value;
  45638. this.leftTrigger = this.browserGamepad.buttons[6].value;
  45639. this.rightTrigger = this.browserGamepad.buttons[7].value;
  45640. this.buttonBack = this.browserGamepad.buttons[8].value;
  45641. this.buttonStart = this.browserGamepad.buttons[9].value;
  45642. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  45643. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  45644. this.dPadUp = this.browserGamepad.buttons[12].value;
  45645. this.dPadDown = this.browserGamepad.buttons[13].value;
  45646. this.dPadLeft = this.browserGamepad.buttons[14].value;
  45647. this.dPadRight = this.browserGamepad.buttons[15].value;
  45648. }
  45649. };
  45650. return Xbox360Pad;
  45651. }(Gamepad));
  45652. BABYLON.Xbox360Pad = Xbox360Pad;
  45653. })(BABYLON || (BABYLON = {}));
  45654. //# sourceMappingURL=babylon.gamepads.js.map
  45655. var BABYLON;
  45656. (function (BABYLON) {
  45657. var PoseEnabledControllerType;
  45658. (function (PoseEnabledControllerType) {
  45659. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  45660. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  45661. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 2] = "GENERIC";
  45662. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  45663. var PoseEnabledControllerHelper = (function () {
  45664. function PoseEnabledControllerHelper() {
  45665. }
  45666. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  45667. // for now, only Oculus and Vive are supported
  45668. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  45669. return new OculusTouchController(vrGamepad);
  45670. }
  45671. else {
  45672. return new ViveController(vrGamepad);
  45673. }
  45674. };
  45675. return PoseEnabledControllerHelper;
  45676. }());
  45677. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  45678. var PoseEnabledController = (function (_super) {
  45679. __extends(PoseEnabledController, _super);
  45680. function PoseEnabledController(vrGamepad) {
  45681. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  45682. _this.vrGamepad = vrGamepad;
  45683. _this.deviceScaleFactor = 1;
  45684. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  45685. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  45686. _this.controllerType = PoseEnabledControllerType.GENERIC;
  45687. _this.position = BABYLON.Vector3.Zero();
  45688. _this.rotationQuaternion = new BABYLON.Quaternion();
  45689. _this.devicePosition = BABYLON.Vector3.Zero();
  45690. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  45691. _this._calculatedPosition = BABYLON.Vector3.Zero();
  45692. _this._calculatedRotation = new BABYLON.Quaternion();
  45693. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  45694. return _this;
  45695. }
  45696. PoseEnabledController.prototype.update = function () {
  45697. _super.prototype.update.call(this);
  45698. var pose = this.vrGamepad.pose;
  45699. this.updateFromDevice(pose);
  45700. if (this._mesh) {
  45701. this._mesh.position.copyFrom(this._calculatedPosition);
  45702. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  45703. }
  45704. };
  45705. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  45706. if (poseData) {
  45707. this.rawPose = poseData;
  45708. if (poseData.position) {
  45709. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  45710. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  45711. this.devicePosition.z *= -1;
  45712. }
  45713. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  45714. this._calculatedPosition.addInPlace(this.position);
  45715. }
  45716. if (poseData.orientation) {
  45717. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  45718. if (this._mesh) {
  45719. if (this._mesh.getScene().useRightHandedSystem) {
  45720. this.deviceRotationQuaternion.z *= -1;
  45721. this.deviceRotationQuaternion.w *= -1;
  45722. }
  45723. else {
  45724. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  45725. }
  45726. }
  45727. // if the camera is set, rotate to the camera's rotation
  45728. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  45729. }
  45730. }
  45731. };
  45732. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  45733. if (this._mesh) {
  45734. this._mesh.parent = undefined;
  45735. }
  45736. this._mesh = mesh;
  45737. if (this._poseControlledCamera) {
  45738. this._mesh.parent = this._poseControlledCamera;
  45739. }
  45740. if (!this._mesh.rotationQuaternion) {
  45741. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  45742. }
  45743. };
  45744. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  45745. this._poseControlledCamera = camera;
  45746. if (this._mesh) {
  45747. this._mesh.parent = this._poseControlledCamera;
  45748. }
  45749. };
  45750. PoseEnabledController.prototype.detachMesh = function () {
  45751. this._mesh = undefined;
  45752. };
  45753. return PoseEnabledController;
  45754. }(BABYLON.Gamepad));
  45755. BABYLON.PoseEnabledController = PoseEnabledController;
  45756. var WebVRController = (function (_super) {
  45757. __extends(WebVRController, _super);
  45758. function WebVRController(vrGamepad) {
  45759. var _this = _super.call(this, vrGamepad) || this;
  45760. //public onTriggerStateChangedObservable = new Observable<{ state: ExtendedGamepadButton, changes: GamepadButtonChanges }>();
  45761. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  45762. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  45763. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  45764. _this.onPadStateChangedObservable = new BABYLON.Observable();
  45765. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  45766. _this.pad = { x: 0, y: 0 };
  45767. // avoid GC, store state in a tmp object
  45768. _this._changes = {
  45769. pressChanged: false,
  45770. touchChanged: false,
  45771. valueChanged: false,
  45772. changed: false
  45773. };
  45774. _this._buttons = new Array(vrGamepad.buttons.length);
  45775. _this.hand = vrGamepad.hand;
  45776. return _this;
  45777. }
  45778. WebVRController.prototype.onButtonStateChange = function (callback) {
  45779. this._onButtonStateChange = callback;
  45780. };
  45781. WebVRController.prototype.update = function () {
  45782. _super.prototype.update.call(this);
  45783. for (var index = 0; index < this._buttons.length; index++) {
  45784. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  45785. }
  45786. ;
  45787. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  45788. this.pad.x = this.leftStick.x;
  45789. this.pad.y = this.leftStick.y;
  45790. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  45791. }
  45792. };
  45793. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  45794. if (!currentState) {
  45795. this._buttons[buttonIndex] = {
  45796. pressed: newState.pressed,
  45797. touched: newState.touched,
  45798. value: newState.value
  45799. };
  45800. return;
  45801. }
  45802. this._checkChanges(newState, currentState);
  45803. if (this._changes.changed) {
  45804. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  45805. this.handleButtonChange(buttonIndex, newState, this._changes);
  45806. }
  45807. this._buttons[buttonIndex].pressed = newState.pressed;
  45808. this._buttons[buttonIndex].touched = newState.touched;
  45809. // oculus triggers are never 0, thou not touched.
  45810. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  45811. };
  45812. WebVRController.prototype._checkChanges = function (newState, currentState) {
  45813. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  45814. this._changes.touchChanged = newState.touched !== currentState.touched;
  45815. this._changes.valueChanged = newState.value !== currentState.value;
  45816. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  45817. return this._changes;
  45818. };
  45819. return WebVRController;
  45820. }(PoseEnabledController));
  45821. BABYLON.WebVRController = WebVRController;
  45822. var OculusTouchController = (function (_super) {
  45823. __extends(OculusTouchController, _super);
  45824. function OculusTouchController(vrGamepad) {
  45825. var _this = _super.call(this, vrGamepad) || this;
  45826. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  45827. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  45828. _this.controllerType = PoseEnabledControllerType.OCULUS;
  45829. return _this;
  45830. }
  45831. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  45832. var _this = this;
  45833. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  45834. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  45835. /*
  45836. Parent Mesh name: oculus_touch_left
  45837. - body
  45838. - trigger
  45839. - thumbstick
  45840. - grip
  45841. - button_y
  45842. - button_x
  45843. - button_enter
  45844. */
  45845. _this._defaultModel = newMeshes[1];
  45846. if (meshLoaded) {
  45847. meshLoaded(_this._defaultModel);
  45848. }
  45849. _this.attachToMesh(_this._defaultModel);
  45850. });
  45851. };
  45852. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  45853. // helper getters for left and right hand.
  45854. get: function () {
  45855. if (this.hand === 'right') {
  45856. return this.onMainButtonStateChangedObservable;
  45857. }
  45858. else {
  45859. throw new Error('No A button on left hand');
  45860. }
  45861. },
  45862. enumerable: true,
  45863. configurable: true
  45864. });
  45865. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  45866. get: function () {
  45867. if (this.hand === 'right') {
  45868. return this.onSecondaryButtonStateChangedObservable;
  45869. }
  45870. else {
  45871. throw new Error('No B button on left hand');
  45872. }
  45873. },
  45874. enumerable: true,
  45875. configurable: true
  45876. });
  45877. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  45878. get: function () {
  45879. if (this.hand === 'left') {
  45880. return this.onMainButtonStateChangedObservable;
  45881. }
  45882. else {
  45883. throw new Error('No X button on right hand');
  45884. }
  45885. },
  45886. enumerable: true,
  45887. configurable: true
  45888. });
  45889. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  45890. get: function () {
  45891. if (this.hand === 'left') {
  45892. return this.onSecondaryButtonStateChangedObservable;
  45893. }
  45894. else {
  45895. throw new Error('No Y button on right hand');
  45896. }
  45897. },
  45898. enumerable: true,
  45899. configurable: true
  45900. });
  45901. /*
  45902. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  45903. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  45904. 2) secondary trigger (same)
  45905. 3) A (right) X (left), touch, pressed = value
  45906. 4) B / Y
  45907. 5) thumb rest
  45908. */
  45909. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  45910. var notifyObject = state; //{ state: state, changes: changes };
  45911. var triggerDirection = this.hand === 'right' ? -1 : 1;
  45912. switch (buttonIdx) {
  45913. case 0:
  45914. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  45915. return;
  45916. case 1:
  45917. if (this._defaultModel) {
  45918. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  45919. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  45920. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  45921. }
  45922. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  45923. return;
  45924. case 2:
  45925. if (this._defaultModel) {
  45926. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  45927. }
  45928. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  45929. return;
  45930. case 3:
  45931. if (this._defaultModel) {
  45932. if (notifyObject.pressed) {
  45933. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  45934. }
  45935. else {
  45936. (this._defaultModel.getChildren()[1]).position.y = 0;
  45937. }
  45938. }
  45939. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  45940. return;
  45941. case 4:
  45942. if (this._defaultModel) {
  45943. if (notifyObject.pressed) {
  45944. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  45945. }
  45946. else {
  45947. (this._defaultModel.getChildren()[2]).position.y = 0;
  45948. }
  45949. }
  45950. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  45951. return;
  45952. case 5:
  45953. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  45954. return;
  45955. }
  45956. };
  45957. return OculusTouchController;
  45958. }(WebVRController));
  45959. BABYLON.OculusTouchController = OculusTouchController;
  45960. var ViveController = (function (_super) {
  45961. __extends(ViveController, _super);
  45962. function ViveController(vrGamepad) {
  45963. var _this = _super.call(this, vrGamepad) || this;
  45964. _this.controllerType = PoseEnabledControllerType.VIVE;
  45965. return _this;
  45966. }
  45967. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  45968. var _this = this;
  45969. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  45970. /*
  45971. Parent Mesh name: ViveWand
  45972. - body
  45973. - r_gripper
  45974. - l_gripper
  45975. - menu_button
  45976. - system_button
  45977. - trackpad
  45978. - trigger
  45979. - LED
  45980. */
  45981. _this._defaultModel = newMeshes[1];
  45982. if (meshLoaded) {
  45983. meshLoaded(_this._defaultModel);
  45984. }
  45985. _this.attachToMesh(_this._defaultModel);
  45986. });
  45987. };
  45988. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  45989. get: function () {
  45990. return this.onMainButtonStateChangedObservable;
  45991. },
  45992. enumerable: true,
  45993. configurable: true
  45994. });
  45995. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  45996. get: function () {
  45997. return this.onMainButtonStateChangedObservable;
  45998. },
  45999. enumerable: true,
  46000. configurable: true
  46001. });
  46002. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  46003. get: function () {
  46004. return this.onSecondaryButtonStateChangedObservable;
  46005. },
  46006. enumerable: true,
  46007. configurable: true
  46008. });
  46009. /**
  46010. * Vive mapping:
  46011. * 0: touchpad
  46012. * 1: trigger
  46013. * 2: left AND right buttons
  46014. * 3: menu button
  46015. */
  46016. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  46017. var notifyObject = state; //{ state: state, changes: changes };
  46018. switch (buttonIdx) {
  46019. case 0:
  46020. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  46021. return;
  46022. case 1:
  46023. if (this._defaultModel) {
  46024. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  46025. }
  46026. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  46027. return;
  46028. case 2:
  46029. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  46030. return;
  46031. case 3:
  46032. if (this._defaultModel) {
  46033. if (notifyObject.pressed) {
  46034. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  46035. }
  46036. else {
  46037. (this._defaultModel.getChildren()[2]).position.y = 0;
  46038. }
  46039. }
  46040. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  46041. return;
  46042. }
  46043. };
  46044. return ViveController;
  46045. }(WebVRController));
  46046. BABYLON.ViveController = ViveController;
  46047. })(BABYLON || (BABYLON = {}));
  46048. //# sourceMappingURL=babylon.extendedGamepad.js.map
  46049. /// <reference path="babylon.targetCamera.ts" />
  46050. var BABYLON;
  46051. (function (BABYLON) {
  46052. var FollowCamera = (function (_super) {
  46053. __extends(FollowCamera, _super);
  46054. function FollowCamera(name, position, scene, lockedTarget) {
  46055. var _this = _super.call(this, name, position, scene) || this;
  46056. _this.radius = 12;
  46057. _this.rotationOffset = 0;
  46058. _this.heightOffset = 4;
  46059. _this.cameraAcceleration = 0.05;
  46060. _this.maxCameraSpeed = 20;
  46061. _this.lockedTarget = lockedTarget;
  46062. return _this;
  46063. }
  46064. FollowCamera.prototype.getRadians = function (degrees) {
  46065. return degrees * Math.PI / 180;
  46066. };
  46067. FollowCamera.prototype.follow = function (cameraTarget) {
  46068. if (!cameraTarget)
  46069. return;
  46070. var yRotation;
  46071. if (cameraTarget.rotationQuaternion) {
  46072. var rotMatrix = new BABYLON.Matrix();
  46073. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  46074. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  46075. }
  46076. else {
  46077. yRotation = cameraTarget.rotation.y;
  46078. }
  46079. var radians = this.getRadians(this.rotationOffset) + yRotation;
  46080. var targetPosition = cameraTarget.getAbsolutePosition();
  46081. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  46082. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  46083. var dx = targetX - this.position.x;
  46084. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  46085. var dz = (targetZ) - this.position.z;
  46086. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  46087. var vy = dy * this.cameraAcceleration;
  46088. var vz = dz * this.cameraAcceleration * 2;
  46089. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  46090. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  46091. }
  46092. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  46093. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  46094. }
  46095. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  46096. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  46097. }
  46098. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  46099. this.setTarget(targetPosition);
  46100. };
  46101. FollowCamera.prototype._checkInputs = function () {
  46102. _super.prototype._checkInputs.call(this);
  46103. this.follow(this.lockedTarget);
  46104. };
  46105. FollowCamera.prototype.getClassName = function () {
  46106. return "FollowCamera";
  46107. };
  46108. return FollowCamera;
  46109. }(BABYLON.TargetCamera));
  46110. __decorate([
  46111. BABYLON.serialize()
  46112. ], FollowCamera.prototype, "radius", void 0);
  46113. __decorate([
  46114. BABYLON.serialize()
  46115. ], FollowCamera.prototype, "rotationOffset", void 0);
  46116. __decorate([
  46117. BABYLON.serialize()
  46118. ], FollowCamera.prototype, "heightOffset", void 0);
  46119. __decorate([
  46120. BABYLON.serialize()
  46121. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  46122. __decorate([
  46123. BABYLON.serialize()
  46124. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  46125. __decorate([
  46126. BABYLON.serializeAsMeshReference("lockedTargetId")
  46127. ], FollowCamera.prototype, "lockedTarget", void 0);
  46128. BABYLON.FollowCamera = FollowCamera;
  46129. var ArcFollowCamera = (function (_super) {
  46130. __extends(ArcFollowCamera, _super);
  46131. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  46132. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  46133. _this.alpha = alpha;
  46134. _this.beta = beta;
  46135. _this.radius = radius;
  46136. _this.target = target;
  46137. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  46138. _this.follow();
  46139. return _this;
  46140. }
  46141. ArcFollowCamera.prototype.follow = function () {
  46142. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  46143. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  46144. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  46145. var targetPosition = this.target.getAbsolutePosition();
  46146. this.position = targetPosition.add(this._cartesianCoordinates);
  46147. this.setTarget(targetPosition);
  46148. };
  46149. ArcFollowCamera.prototype._checkInputs = function () {
  46150. _super.prototype._checkInputs.call(this);
  46151. this.follow();
  46152. };
  46153. ArcFollowCamera.prototype.getClassName = function () {
  46154. return "ArcFollowCamera";
  46155. };
  46156. return ArcFollowCamera;
  46157. }(BABYLON.TargetCamera));
  46158. BABYLON.ArcFollowCamera = ArcFollowCamera;
  46159. })(BABYLON || (BABYLON = {}));
  46160. //# sourceMappingURL=babylon.followCamera.js.map
  46161. /// <reference path="babylon.touchCamera.ts" />
  46162. var BABYLON;
  46163. (function (BABYLON) {
  46164. // We're mainly based on the logic defined into the FreeCamera code
  46165. var UniversalCamera = (function (_super) {
  46166. __extends(UniversalCamera, _super);
  46167. //-- end properties for backward compatibility for inputs
  46168. function UniversalCamera(name, position, scene) {
  46169. var _this = _super.call(this, name, position, scene) || this;
  46170. _this.inputs.addGamepad();
  46171. return _this;
  46172. }
  46173. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  46174. //-- Begin properties for backward compatibility for inputs
  46175. get: function () {
  46176. var gamepad = this.inputs.attached["gamepad"];
  46177. if (gamepad)
  46178. return gamepad.gamepadAngularSensibility;
  46179. },
  46180. set: function (value) {
  46181. var gamepad = this.inputs.attached["gamepad"];
  46182. if (gamepad)
  46183. gamepad.gamepadAngularSensibility = value;
  46184. },
  46185. enumerable: true,
  46186. configurable: true
  46187. });
  46188. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  46189. get: function () {
  46190. var gamepad = this.inputs.attached["gamepad"];
  46191. if (gamepad)
  46192. return gamepad.gamepadMoveSensibility;
  46193. },
  46194. set: function (value) {
  46195. var gamepad = this.inputs.attached["gamepad"];
  46196. if (gamepad)
  46197. gamepad.gamepadMoveSensibility = value;
  46198. },
  46199. enumerable: true,
  46200. configurable: true
  46201. });
  46202. UniversalCamera.prototype.getClassName = function () {
  46203. return "UniversalCamera";
  46204. };
  46205. return UniversalCamera;
  46206. }(BABYLON.TouchCamera));
  46207. BABYLON.UniversalCamera = UniversalCamera;
  46208. })(BABYLON || (BABYLON = {}));
  46209. //# sourceMappingURL=babylon.universalCamera.js.map
  46210. /// <reference path="babylon.universalCamera.ts" />
  46211. var BABYLON;
  46212. (function (BABYLON) {
  46213. // We're mainly based on the logic defined into the FreeCamera code
  46214. var GamepadCamera = (function (_super) {
  46215. __extends(GamepadCamera, _super);
  46216. //-- end properties for backward compatibility for inputs
  46217. function GamepadCamera(name, position, scene) {
  46218. return _super.call(this, name, position, scene) || this;
  46219. }
  46220. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  46221. //-- Begin properties for backward compatibility for inputs
  46222. get: function () {
  46223. var gamepad = this.inputs.attached["gamepad"];
  46224. if (gamepad)
  46225. return gamepad.gamepadAngularSensibility;
  46226. },
  46227. set: function (value) {
  46228. var gamepad = this.inputs.attached["gamepad"];
  46229. if (gamepad)
  46230. gamepad.gamepadAngularSensibility = value;
  46231. },
  46232. enumerable: true,
  46233. configurable: true
  46234. });
  46235. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  46236. get: function () {
  46237. var gamepad = this.inputs.attached["gamepad"];
  46238. if (gamepad)
  46239. return gamepad.gamepadMoveSensibility;
  46240. },
  46241. set: function (value) {
  46242. var gamepad = this.inputs.attached["gamepad"];
  46243. if (gamepad)
  46244. gamepad.gamepadMoveSensibility = value;
  46245. },
  46246. enumerable: true,
  46247. configurable: true
  46248. });
  46249. GamepadCamera.prototype.getClassName = function () {
  46250. return "GamepadCamera";
  46251. };
  46252. return GamepadCamera;
  46253. }(BABYLON.UniversalCamera));
  46254. BABYLON.GamepadCamera = GamepadCamera;
  46255. })(BABYLON || (BABYLON = {}));
  46256. //# sourceMappingURL=babylon.gamepadCamera.js.map
  46257. var BABYLON;
  46258. (function (BABYLON) {
  46259. var PostProcessRenderPipelineManager = (function () {
  46260. function PostProcessRenderPipelineManager() {
  46261. this._renderPipelines = {};
  46262. }
  46263. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  46264. this._renderPipelines[renderPipeline._name] = renderPipeline;
  46265. };
  46266. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  46267. var renderPipeline = this._renderPipelines[renderPipelineName];
  46268. if (!renderPipeline) {
  46269. return;
  46270. }
  46271. renderPipeline._attachCameras(cameras, unique);
  46272. };
  46273. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  46274. var renderPipeline = this._renderPipelines[renderPipelineName];
  46275. if (!renderPipeline) {
  46276. return;
  46277. }
  46278. renderPipeline._detachCameras(cameras);
  46279. };
  46280. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  46281. var renderPipeline = this._renderPipelines[renderPipelineName];
  46282. if (!renderPipeline) {
  46283. return;
  46284. }
  46285. renderPipeline._enableEffect(renderEffectName, cameras);
  46286. };
  46287. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  46288. var renderPipeline = this._renderPipelines[renderPipelineName];
  46289. if (!renderPipeline) {
  46290. return;
  46291. }
  46292. renderPipeline._disableEffect(renderEffectName, cameras);
  46293. };
  46294. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  46295. var renderPipeline = this._renderPipelines[renderPipelineName];
  46296. if (!renderPipeline) {
  46297. return;
  46298. }
  46299. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  46300. };
  46301. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  46302. var renderPipeline = this._renderPipelines[renderPipelineName];
  46303. if (!renderPipeline) {
  46304. return;
  46305. }
  46306. renderPipeline._disableDisplayOnlyPass(cameras);
  46307. };
  46308. PostProcessRenderPipelineManager.prototype.update = function () {
  46309. for (var renderPipelineName in this._renderPipelines) {
  46310. var pipeline = this._renderPipelines[renderPipelineName];
  46311. if (!pipeline.isSupported) {
  46312. pipeline.dispose();
  46313. delete this._renderPipelines[renderPipelineName];
  46314. }
  46315. else {
  46316. pipeline._update();
  46317. }
  46318. }
  46319. };
  46320. return PostProcessRenderPipelineManager;
  46321. }());
  46322. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  46323. })(BABYLON || (BABYLON = {}));
  46324. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  46325. var BABYLON;
  46326. (function (BABYLON) {
  46327. var PostProcessRenderPass = (function () {
  46328. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  46329. this._enabled = true;
  46330. this._refCount = 0;
  46331. this._name = name;
  46332. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  46333. this.setRenderList(renderList);
  46334. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  46335. this._renderTexture.onAfterRenderObservable.add(afterRender);
  46336. this._scene = scene;
  46337. this._renderList = renderList;
  46338. }
  46339. // private
  46340. PostProcessRenderPass.prototype._incRefCount = function () {
  46341. if (this._refCount === 0) {
  46342. this._scene.customRenderTargets.push(this._renderTexture);
  46343. }
  46344. return ++this._refCount;
  46345. };
  46346. PostProcessRenderPass.prototype._decRefCount = function () {
  46347. this._refCount--;
  46348. if (this._refCount <= 0) {
  46349. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  46350. }
  46351. return this._refCount;
  46352. };
  46353. PostProcessRenderPass.prototype._update = function () {
  46354. this.setRenderList(this._renderList);
  46355. };
  46356. // public
  46357. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  46358. this._renderTexture.renderList = renderList;
  46359. };
  46360. PostProcessRenderPass.prototype.getRenderTexture = function () {
  46361. return this._renderTexture;
  46362. };
  46363. return PostProcessRenderPass;
  46364. }());
  46365. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  46366. })(BABYLON || (BABYLON = {}));
  46367. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  46368. var BABYLON;
  46369. (function (BABYLON) {
  46370. var PostProcessRenderEffect = (function () {
  46371. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  46372. this._engine = engine;
  46373. this._name = name;
  46374. this._singleInstance = singleInstance || true;
  46375. this._getPostProcess = getPostProcess;
  46376. this._cameras = [];
  46377. this._indicesForCamera = [];
  46378. this._postProcesses = {};
  46379. this._renderPasses = {};
  46380. this._renderEffectAsPasses = {};
  46381. }
  46382. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  46383. get: function () {
  46384. for (var index in this._postProcesses) {
  46385. if (!this._postProcesses[index].isSupported) {
  46386. return false;
  46387. }
  46388. }
  46389. return true;
  46390. },
  46391. enumerable: true,
  46392. configurable: true
  46393. });
  46394. PostProcessRenderEffect.prototype._update = function () {
  46395. for (var renderPassName in this._renderPasses) {
  46396. this._renderPasses[renderPassName]._update();
  46397. }
  46398. };
  46399. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  46400. this._renderPasses[renderPass._name] = renderPass;
  46401. this._linkParameters();
  46402. };
  46403. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  46404. delete this._renderPasses[renderPass._name];
  46405. this._linkParameters();
  46406. };
  46407. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  46408. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  46409. this._linkParameters();
  46410. };
  46411. PostProcessRenderEffect.prototype.getPass = function (passName) {
  46412. for (var renderPassName in this._renderPasses) {
  46413. if (renderPassName === passName) {
  46414. return this._renderPasses[passName];
  46415. }
  46416. }
  46417. };
  46418. PostProcessRenderEffect.prototype.emptyPasses = function () {
  46419. this._renderPasses = {};
  46420. this._linkParameters();
  46421. };
  46422. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  46423. var cameraKey;
  46424. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46425. for (var i = 0; i < _cam.length; i++) {
  46426. var camera = _cam[i];
  46427. var cameraName = camera.name;
  46428. if (this._singleInstance) {
  46429. cameraKey = 0;
  46430. }
  46431. else {
  46432. cameraKey = cameraName;
  46433. }
  46434. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  46435. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  46436. if (!this._indicesForCamera[cameraName]) {
  46437. this._indicesForCamera[cameraName] = [];
  46438. }
  46439. this._indicesForCamera[cameraName].push(index);
  46440. if (this._cameras.indexOf(camera) === -1) {
  46441. this._cameras[cameraName] = camera;
  46442. }
  46443. for (var passName in this._renderPasses) {
  46444. this._renderPasses[passName]._incRefCount();
  46445. }
  46446. }
  46447. this._linkParameters();
  46448. };
  46449. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  46450. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46451. for (var i = 0; i < _cam.length; i++) {
  46452. var camera = _cam[i];
  46453. var cameraName = camera.name;
  46454. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  46455. var index = this._cameras.indexOf(cameraName);
  46456. this._indicesForCamera.splice(index, 1);
  46457. this._cameras.splice(index, 1);
  46458. for (var passName in this._renderPasses) {
  46459. this._renderPasses[passName]._decRefCount();
  46460. }
  46461. }
  46462. };
  46463. PostProcessRenderEffect.prototype._enable = function (cameras) {
  46464. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46465. for (var i = 0; i < _cam.length; i++) {
  46466. var camera = _cam[i];
  46467. var cameraName = camera.name;
  46468. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  46469. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  46470. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  46471. }
  46472. }
  46473. for (var passName in this._renderPasses) {
  46474. this._renderPasses[passName]._incRefCount();
  46475. }
  46476. }
  46477. };
  46478. PostProcessRenderEffect.prototype._disable = function (cameras) {
  46479. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46480. for (var i = 0; i < _cam.length; i++) {
  46481. var camera = _cam[i];
  46482. var cameraName = camera.Name;
  46483. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  46484. for (var passName in this._renderPasses) {
  46485. this._renderPasses[passName]._decRefCount();
  46486. }
  46487. }
  46488. };
  46489. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  46490. if (this._singleInstance) {
  46491. return this._postProcesses[0];
  46492. }
  46493. else {
  46494. return this._postProcesses[camera.name];
  46495. }
  46496. };
  46497. PostProcessRenderEffect.prototype._linkParameters = function () {
  46498. var _this = this;
  46499. for (var index in this._postProcesses) {
  46500. if (this.applyParameters) {
  46501. this.applyParameters(this._postProcesses[index]);
  46502. }
  46503. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  46504. _this._linkTextures(effect);
  46505. });
  46506. }
  46507. };
  46508. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  46509. for (var renderPassName in this._renderPasses) {
  46510. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  46511. }
  46512. for (var renderEffectName in this._renderEffectAsPasses) {
  46513. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  46514. }
  46515. };
  46516. return PostProcessRenderEffect;
  46517. }());
  46518. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  46519. })(BABYLON || (BABYLON = {}));
  46520. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  46521. var BABYLON;
  46522. (function (BABYLON) {
  46523. var PostProcessRenderPipeline = (function () {
  46524. function PostProcessRenderPipeline(engine, name) {
  46525. this._engine = engine;
  46526. this._name = name;
  46527. this._renderEffects = {};
  46528. this._renderEffectsForIsolatedPass = {};
  46529. this._cameras = [];
  46530. }
  46531. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  46532. get: function () {
  46533. for (var renderEffectName in this._renderEffects) {
  46534. if (!this._renderEffects[renderEffectName].isSupported) {
  46535. return false;
  46536. }
  46537. }
  46538. return true;
  46539. },
  46540. enumerable: true,
  46541. configurable: true
  46542. });
  46543. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  46544. this._renderEffects[renderEffect._name] = renderEffect;
  46545. };
  46546. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  46547. var renderEffects = this._renderEffects[renderEffectName];
  46548. if (!renderEffects) {
  46549. return;
  46550. }
  46551. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  46552. };
  46553. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  46554. var renderEffects = this._renderEffects[renderEffectName];
  46555. if (!renderEffects) {
  46556. return;
  46557. }
  46558. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  46559. };
  46560. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  46561. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46562. var indicesToDelete = [];
  46563. var i;
  46564. for (i = 0; i < _cam.length; i++) {
  46565. var camera = _cam[i];
  46566. var cameraName = camera.name;
  46567. if (this._cameras.indexOf(camera) === -1) {
  46568. this._cameras[cameraName] = camera;
  46569. }
  46570. else if (unique) {
  46571. indicesToDelete.push(i);
  46572. }
  46573. }
  46574. for (i = 0; i < indicesToDelete.length; i++) {
  46575. cameras.splice(indicesToDelete[i], 1);
  46576. }
  46577. for (var renderEffectName in this._renderEffects) {
  46578. this._renderEffects[renderEffectName]._attachCameras(_cam);
  46579. }
  46580. };
  46581. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  46582. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46583. for (var renderEffectName in this._renderEffects) {
  46584. this._renderEffects[renderEffectName]._detachCameras(_cam);
  46585. }
  46586. for (var i = 0; i < _cam.length; i++) {
  46587. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  46588. }
  46589. };
  46590. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  46591. var _this = this;
  46592. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46593. var pass = null;
  46594. var renderEffectName;
  46595. for (renderEffectName in this._renderEffects) {
  46596. pass = this._renderEffects[renderEffectName].getPass(passName);
  46597. if (pass != null) {
  46598. break;
  46599. }
  46600. }
  46601. if (pass === null) {
  46602. return;
  46603. }
  46604. for (renderEffectName in this._renderEffects) {
  46605. this._renderEffects[renderEffectName]._disable(_cam);
  46606. }
  46607. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  46608. for (var i = 0; i < _cam.length; i++) {
  46609. var camera = _cam[i];
  46610. var cameraName = camera.name;
  46611. 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); });
  46612. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  46613. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  46614. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  46615. }
  46616. };
  46617. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  46618. var _this = this;
  46619. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  46620. for (var i = 0; i < _cam.length; i++) {
  46621. var camera = _cam[i];
  46622. var cameraName = camera.name;
  46623. 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); });
  46624. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  46625. }
  46626. for (var renderEffectName in this._renderEffects) {
  46627. this._renderEffects[renderEffectName]._enable(_cam);
  46628. }
  46629. };
  46630. PostProcessRenderPipeline.prototype._update = function () {
  46631. for (var renderEffectName in this._renderEffects) {
  46632. this._renderEffects[renderEffectName]._update();
  46633. }
  46634. for (var i = 0; i < this._cameras.length; i++) {
  46635. var cameraName = this._cameras[i].name;
  46636. if (this._renderEffectsForIsolatedPass[cameraName]) {
  46637. this._renderEffectsForIsolatedPass[cameraName]._update();
  46638. }
  46639. }
  46640. };
  46641. PostProcessRenderPipeline.prototype.dispose = function () {
  46642. // Must be implemented by children
  46643. };
  46644. return PostProcessRenderPipeline;
  46645. }());
  46646. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  46647. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  46648. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  46649. })(BABYLON || (BABYLON = {}));
  46650. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  46651. var BABYLON;
  46652. (function (BABYLON) {
  46653. var DepthRenderer = (function () {
  46654. function DepthRenderer(scene, type) {
  46655. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  46656. var _this = this;
  46657. this._viewMatrix = BABYLON.Matrix.Zero();
  46658. this._projectionMatrix = BABYLON.Matrix.Zero();
  46659. this._transformMatrix = BABYLON.Matrix.Zero();
  46660. this._worldViewProjection = BABYLON.Matrix.Zero();
  46661. this._scene = scene;
  46662. var engine = scene.getEngine();
  46663. // Render target
  46664. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  46665. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46666. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46667. this._depthMap.refreshRate = 1;
  46668. this._depthMap.renderParticles = false;
  46669. this._depthMap.renderList = null;
  46670. // set default depth value to 1.0 (far away)
  46671. this._depthMap.onClearObservable.add(function (engine) {
  46672. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  46673. });
  46674. // Custom render function
  46675. var renderSubMesh = function (subMesh) {
  46676. var mesh = subMesh.getRenderingMesh();
  46677. var scene = _this._scene;
  46678. var engine = scene.getEngine();
  46679. // Culling
  46680. engine.setState(subMesh.getMaterial().backFaceCulling);
  46681. // Managing instances
  46682. var batch = mesh._getInstancesRenderList(subMesh._id);
  46683. if (batch.mustReturn) {
  46684. return;
  46685. }
  46686. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  46687. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  46688. engine.enableEffect(_this._effect);
  46689. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  46690. var material = subMesh.getMaterial();
  46691. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  46692. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  46693. // Alpha test
  46694. if (material && material.needAlphaTesting()) {
  46695. var alphaTexture = material.getAlphaTestTexture();
  46696. _this._effect.setTexture("diffuseSampler", alphaTexture);
  46697. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  46698. }
  46699. // Bones
  46700. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46701. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46702. }
  46703. // Draw
  46704. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  46705. }
  46706. };
  46707. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  46708. var index;
  46709. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46710. renderSubMesh(opaqueSubMeshes.data[index]);
  46711. }
  46712. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  46713. renderSubMesh(alphaTestSubMeshes.data[index]);
  46714. }
  46715. };
  46716. }
  46717. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  46718. var material = subMesh.getMaterial();
  46719. if (material.disableDepthWrite) {
  46720. return false;
  46721. }
  46722. var defines = [];
  46723. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46724. var mesh = subMesh.getMesh();
  46725. var scene = mesh.getScene();
  46726. // Alpha test
  46727. if (material && material.needAlphaTesting()) {
  46728. defines.push("#define ALPHATEST");
  46729. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46730. attribs.push(BABYLON.VertexBuffer.UVKind);
  46731. defines.push("#define UV1");
  46732. }
  46733. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  46734. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46735. defines.push("#define UV2");
  46736. }
  46737. }
  46738. // Bones
  46739. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46740. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46741. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46742. if (mesh.numBoneInfluencers > 4) {
  46743. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  46744. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  46745. }
  46746. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46747. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46748. }
  46749. else {
  46750. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46751. }
  46752. // Instances
  46753. if (useInstances) {
  46754. defines.push("#define INSTANCES");
  46755. attribs.push("world0");
  46756. attribs.push("world1");
  46757. attribs.push("world2");
  46758. attribs.push("world3");
  46759. }
  46760. // Get correct effect
  46761. var join = defines.join("\n");
  46762. if (this._cachedDefines !== join) {
  46763. this._cachedDefines = join;
  46764. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  46765. }
  46766. return this._effect.isReady();
  46767. };
  46768. DepthRenderer.prototype.getDepthMap = function () {
  46769. return this._depthMap;
  46770. };
  46771. // Methods
  46772. DepthRenderer.prototype.dispose = function () {
  46773. this._depthMap.dispose();
  46774. };
  46775. return DepthRenderer;
  46776. }());
  46777. BABYLON.DepthRenderer = DepthRenderer;
  46778. })(BABYLON || (BABYLON = {}));
  46779. //# sourceMappingURL=babylon.depthRenderer.js.map
  46780. var BABYLON;
  46781. (function (BABYLON) {
  46782. var SSAORenderingPipeline = (function (_super) {
  46783. __extends(SSAORenderingPipeline, _super);
  46784. /**
  46785. * @constructor
  46786. * @param {string} name - The rendering pipeline name
  46787. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46788. * @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 }
  46789. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46790. */
  46791. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  46792. var _this = _super.call(this, scene.getEngine(), name) || this;
  46793. // Members
  46794. /**
  46795. * The PassPostProcess id in the pipeline that contains the original scene color
  46796. * @type {string}
  46797. */
  46798. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  46799. /**
  46800. * The SSAO PostProcess id in the pipeline
  46801. * @type {string}
  46802. */
  46803. _this.SSAORenderEffect = "SSAORenderEffect";
  46804. /**
  46805. * The horizontal blur PostProcess id in the pipeline
  46806. * @type {string}
  46807. */
  46808. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  46809. /**
  46810. * The vertical blur PostProcess id in the pipeline
  46811. * @type {string}
  46812. */
  46813. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  46814. /**
  46815. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  46816. * @type {string}
  46817. */
  46818. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  46819. /**
  46820. * The output strength of the SSAO post-process. Default value is 1.0.
  46821. * @type {number}
  46822. */
  46823. _this.totalStrength = 1.0;
  46824. /**
  46825. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  46826. * @type {number}
  46827. */
  46828. _this.radius = 0.0001;
  46829. /**
  46830. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  46831. * Must not be equal to fallOff and superior to fallOff.
  46832. * Default value is 0.975
  46833. * @type {number}
  46834. */
  46835. _this.area = 0.0075;
  46836. /**
  46837. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  46838. * Must not be equal to area and inferior to area.
  46839. * Default value is 0.0
  46840. * @type {number}
  46841. */
  46842. _this.fallOff = 0.000001;
  46843. /**
  46844. * The base color of the SSAO post-process
  46845. * The final result is "base + ssao" between [0, 1]
  46846. * @type {number}
  46847. */
  46848. _this.base = 0.5;
  46849. _this._firstUpdate = true;
  46850. _this._scene = scene;
  46851. // Set up assets
  46852. _this._createRandomTexture();
  46853. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  46854. var ssaoRatio = ratio.ssaoRatio || ratio;
  46855. var combineRatio = ratio.combineRatio || ratio;
  46856. _this._ratio = {
  46857. ssaoRatio: ssaoRatio,
  46858. combineRatio: combineRatio
  46859. };
  46860. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  46861. _this._createSSAOPostProcess(ssaoRatio);
  46862. _this._createBlurPostProcess(ssaoRatio);
  46863. _this._createSSAOCombinePostProcess(combineRatio);
  46864. // Set up pipeline
  46865. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  46866. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  46867. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  46868. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  46869. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  46870. // Finish
  46871. scene.postProcessRenderPipelineManager.addPipeline(_this);
  46872. if (cameras)
  46873. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46874. return _this;
  46875. }
  46876. // Public Methods
  46877. /**
  46878. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  46879. */
  46880. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  46881. if (disableDepthRender === void 0) { disableDepthRender = false; }
  46882. for (var i = 0; i < this._scene.cameras.length; i++) {
  46883. var camera = this._scene.cameras[i];
  46884. this._originalColorPostProcess.dispose(camera);
  46885. this._ssaoPostProcess.dispose(camera);
  46886. this._blurHPostProcess.dispose(camera);
  46887. this._blurVPostProcess.dispose(camera);
  46888. this._ssaoCombinePostProcess.dispose(camera);
  46889. }
  46890. this._randomTexture.dispose();
  46891. if (disableDepthRender)
  46892. this._scene.disableDepthRenderer();
  46893. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46894. _super.prototype.dispose.call(this);
  46895. };
  46896. // Private Methods
  46897. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  46898. var _this = this;
  46899. /*
  46900. var samplerOffsets = [
  46901. -8.0, -6.0, -4.0, -2.0,
  46902. 0.0,
  46903. 2.0, 4.0, 6.0, 8.0
  46904. ];
  46905. */
  46906. var samples = 16;
  46907. var samplerOffsets = [];
  46908. for (var i = -8; i < 8; i++) {
  46909. samplerOffsets.push(i * 2);
  46910. }
  46911. 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");
  46912. this._blurHPostProcess.onApply = function (effect) {
  46913. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  46914. effect.setTexture("depthSampler", _this._depthTexture);
  46915. if (_this._firstUpdate) {
  46916. effect.setArray("samplerOffsets", samplerOffsets);
  46917. }
  46918. };
  46919. 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");
  46920. this._blurVPostProcess.onApply = function (effect) {
  46921. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  46922. effect.setTexture("depthSampler", _this._depthTexture);
  46923. if (_this._firstUpdate) {
  46924. effect.setArray("samplerOffsets", samplerOffsets);
  46925. _this._firstUpdate = false;
  46926. }
  46927. };
  46928. };
  46929. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  46930. var _this = this;
  46931. var numSamples = 16;
  46932. var sampleSphere = [
  46933. 0.5381, 0.1856, -0.4319,
  46934. 0.1379, 0.2486, 0.4430,
  46935. 0.3371, 0.5679, -0.0057,
  46936. -0.6999, -0.0451, -0.0019,
  46937. 0.0689, -0.1598, -0.8547,
  46938. 0.0560, 0.0069, -0.1843,
  46939. -0.0146, 0.1402, 0.0762,
  46940. 0.0100, -0.1924, -0.0344,
  46941. -0.3577, -0.5301, -0.4358,
  46942. -0.3169, 0.1063, 0.0158,
  46943. 0.0103, -0.5869, 0.0046,
  46944. -0.0897, -0.4940, 0.3287,
  46945. 0.7119, -0.0154, -0.0918,
  46946. -0.0533, 0.0596, -0.5411,
  46947. 0.0352, -0.0631, 0.5460,
  46948. -0.4776, 0.2847, -0.0271
  46949. ];
  46950. var samplesFactor = 1.0 / numSamples;
  46951. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  46952. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  46953. "area", "fallOff", "base", "range", "viewport"
  46954. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  46955. var viewport = new BABYLON.Vector2(0, 0);
  46956. this._ssaoPostProcess.onApply = function (effect) {
  46957. if (_this._firstUpdate) {
  46958. effect.setArray3("sampleSphere", sampleSphere);
  46959. effect.setFloat("samplesFactor", samplesFactor);
  46960. effect.setFloat("randTextureTiles", 4.0);
  46961. }
  46962. effect.setFloat("totalStrength", _this.totalStrength);
  46963. effect.setFloat("radius", _this.radius);
  46964. effect.setFloat("area", _this.area);
  46965. effect.setFloat("fallOff", _this.fallOff);
  46966. effect.setFloat("base", _this.base);
  46967. effect.setTexture("textureSampler", _this._depthTexture);
  46968. effect.setTexture("randomSampler", _this._randomTexture);
  46969. };
  46970. };
  46971. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  46972. var _this = this;
  46973. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46974. this._ssaoCombinePostProcess.onApply = function (effect) {
  46975. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  46976. };
  46977. };
  46978. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  46979. var size = 512;
  46980. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  46981. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46982. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46983. var context = this._randomTexture.getContext();
  46984. var rand = function (min, max) {
  46985. return Math.random() * (max - min) + min;
  46986. };
  46987. var randVector = BABYLON.Vector3.Zero();
  46988. for (var x = 0; x < size; x++) {
  46989. for (var y = 0; y < size; y++) {
  46990. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  46991. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  46992. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  46993. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  46994. context.fillRect(x, y, 1, 1);
  46995. }
  46996. }
  46997. this._randomTexture.update(false);
  46998. };
  46999. return SSAORenderingPipeline;
  47000. }(BABYLON.PostProcessRenderPipeline));
  47001. __decorate([
  47002. BABYLON.serialize()
  47003. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  47004. __decorate([
  47005. BABYLON.serialize()
  47006. ], SSAORenderingPipeline.prototype, "radius", void 0);
  47007. __decorate([
  47008. BABYLON.serialize()
  47009. ], SSAORenderingPipeline.prototype, "area", void 0);
  47010. __decorate([
  47011. BABYLON.serialize()
  47012. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  47013. __decorate([
  47014. BABYLON.serialize()
  47015. ], SSAORenderingPipeline.prototype, "base", void 0);
  47016. __decorate([
  47017. BABYLON.serialize()
  47018. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  47019. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  47020. })(BABYLON || (BABYLON = {}));
  47021. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  47022. // BABYLON.JS Chromatic Aberration GLSL Shader
  47023. // Author: Olivier Guyot
  47024. // Separates very slightly R, G and B colors on the edges of the screen
  47025. // Inspired by Francois Tarlier & Martins Upitis
  47026. var BABYLON;
  47027. (function (BABYLON) {
  47028. var LensRenderingPipeline = (function (_super) {
  47029. __extends(LensRenderingPipeline, _super);
  47030. /**
  47031. * @constructor
  47032. *
  47033. * Effect parameters are as follow:
  47034. * {
  47035. * chromatic_aberration: number; // from 0 to x (1 for realism)
  47036. * edge_blur: number; // from 0 to x (1 for realism)
  47037. * distortion: number; // from 0 to x (1 for realism)
  47038. * grain_amount: number; // from 0 to 1
  47039. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  47040. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  47041. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  47042. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  47043. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  47044. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  47045. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  47046. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  47047. * }
  47048. * Note: if an effect parameter is unset, effect is disabled
  47049. *
  47050. * @param {string} name - The rendering pipeline name
  47051. * @param {object} parameters - An object containing all parameters (see above)
  47052. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47053. * @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)
  47054. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47055. */
  47056. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  47057. if (ratio === void 0) { ratio = 1.0; }
  47058. var _this = _super.call(this, scene.getEngine(), name) || this;
  47059. // Lens effects can be of the following:
  47060. // - chromatic aberration (slight shift of RGB colors)
  47061. // - blur on the edge of the lens
  47062. // - lens distortion
  47063. // - depth-of-field blur & highlights enhancing
  47064. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  47065. // - grain effect (noise or custom texture)
  47066. // Two additional texture samplers are needed:
  47067. // - depth map (for depth-of-field)
  47068. // - grain texture
  47069. /**
  47070. * The chromatic aberration PostProcess id in the pipeline
  47071. * @type {string}
  47072. */
  47073. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  47074. /**
  47075. * The highlights enhancing PostProcess id in the pipeline
  47076. * @type {string}
  47077. */
  47078. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  47079. /**
  47080. * The depth-of-field PostProcess id in the pipeline
  47081. * @type {string}
  47082. */
  47083. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  47084. _this._scene = scene;
  47085. // Fetch texture samplers
  47086. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47087. if (parameters.grain_texture) {
  47088. _this._grainTexture = parameters.grain_texture;
  47089. }
  47090. else {
  47091. _this._createGrainTexture();
  47092. }
  47093. // save parameters
  47094. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  47095. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  47096. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  47097. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  47098. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  47099. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  47100. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  47101. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  47102. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  47103. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  47104. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  47105. // Create effects
  47106. _this._createChromaticAberrationPostProcess(ratio);
  47107. _this._createHighlightsPostProcess(ratio);
  47108. _this._createDepthOfFieldPostProcess(ratio / 4);
  47109. // Set up pipeline
  47110. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  47111. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  47112. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  47113. if (_this._highlightsGain === -1) {
  47114. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  47115. }
  47116. // Finish
  47117. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47118. if (cameras) {
  47119. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47120. }
  47121. return _this;
  47122. }
  47123. // public methods (self explanatory)
  47124. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  47125. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  47126. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  47127. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  47128. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  47129. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  47130. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  47131. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  47132. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  47133. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  47134. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  47135. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  47136. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  47137. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  47138. };
  47139. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  47140. this._highlightsPostProcess.updateEffect();
  47141. };
  47142. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  47143. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  47144. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  47145. this._highlightsGain = amount;
  47146. };
  47147. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  47148. if (this._highlightsGain === -1) {
  47149. this._highlightsGain = 1.0;
  47150. }
  47151. this._highlightsThreshold = amount;
  47152. };
  47153. LensRenderingPipeline.prototype.disableHighlights = function () {
  47154. this._highlightsGain = -1;
  47155. };
  47156. /**
  47157. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  47158. */
  47159. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47160. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47161. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47162. this._chromaticAberrationPostProcess = undefined;
  47163. this._highlightsPostProcess = undefined;
  47164. this._depthOfFieldPostProcess = undefined;
  47165. this._grainTexture.dispose();
  47166. if (disableDepthRender)
  47167. this._scene.disableDepthRenderer();
  47168. };
  47169. // colors shifting and distortion
  47170. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  47171. var _this = this;
  47172. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  47173. [], // samplers
  47174. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47175. this._chromaticAberrationPostProcess.onApply = function (effect) {
  47176. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  47177. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47178. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47179. };
  47180. };
  47181. // highlights enhancing
  47182. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  47183. var _this = this;
  47184. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  47185. [], // samplers
  47186. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  47187. this._highlightsPostProcess.onApply = function (effect) {
  47188. effect.setFloat('gain', _this._highlightsGain);
  47189. effect.setFloat('threshold', _this._highlightsThreshold);
  47190. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  47191. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47192. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47193. };
  47194. };
  47195. // colors shifting and distortion
  47196. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  47197. var _this = this;
  47198. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  47199. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  47200. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  47201. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47202. this._depthOfFieldPostProcess.onApply = function (effect) {
  47203. effect.setTexture("depthSampler", _this._depthTexture);
  47204. effect.setTexture("grainSampler", _this._grainTexture);
  47205. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  47206. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  47207. effect.setFloat('grain_amount', _this._grainAmount);
  47208. effect.setBool('blur_noise', _this._blurNoise);
  47209. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47210. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47211. effect.setFloat('distortion', _this._distortion);
  47212. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  47213. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  47214. effect.setFloat('aperture', _this._dofAperture);
  47215. effect.setFloat('darken', _this._dofDarken);
  47216. effect.setFloat('edge_blur', _this._edgeBlur);
  47217. effect.setBool('highlights', (_this._highlightsGain !== -1));
  47218. effect.setFloat('near', _this._scene.activeCamera.minZ);
  47219. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  47220. };
  47221. };
  47222. // creates a black and white random noise texture, 512x512
  47223. LensRenderingPipeline.prototype._createGrainTexture = function () {
  47224. var size = 512;
  47225. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47226. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47227. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47228. var context = this._grainTexture.getContext();
  47229. var rand = function (min, max) {
  47230. return Math.random() * (max - min) + min;
  47231. };
  47232. var value;
  47233. for (var x = 0; x < size; x++) {
  47234. for (var y = 0; y < size; y++) {
  47235. value = Math.floor(rand(0.42, 0.58) * 255);
  47236. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  47237. context.fillRect(x, y, 1, 1);
  47238. }
  47239. }
  47240. this._grainTexture.update(false);
  47241. };
  47242. return LensRenderingPipeline;
  47243. }(BABYLON.PostProcessRenderPipeline));
  47244. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  47245. })(BABYLON || (BABYLON = {}));
  47246. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  47247. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  47248. var BABYLON;
  47249. (function (BABYLON) {
  47250. var HDRRenderingPipeline = (function (_super) {
  47251. __extends(HDRRenderingPipeline, _super);
  47252. /**
  47253. * @constructor
  47254. * @param {string} name - The rendering pipeline name
  47255. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47256. * @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)
  47257. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  47258. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47259. */
  47260. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  47261. if (originalPostProcess === void 0) { originalPostProcess = null; }
  47262. var _this = _super.call(this, scene.getEngine(), name) || this;
  47263. /**
  47264. * Public members
  47265. */
  47266. // Gaussian Blur
  47267. /**
  47268. * Gaussian blur coefficient
  47269. * @type {number}
  47270. */
  47271. _this.gaussCoeff = 0.3;
  47272. /**
  47273. * Gaussian blur mean
  47274. * @type {number}
  47275. */
  47276. _this.gaussMean = 1.0;
  47277. /**
  47278. * Gaussian blur standard deviation
  47279. * @type {number}
  47280. */
  47281. _this.gaussStandDev = 0.8;
  47282. /**
  47283. * Gaussian blur multiplier. Multiplies the blur effect
  47284. * @type {number}
  47285. */
  47286. _this.gaussMultiplier = 4.0;
  47287. // HDR
  47288. /**
  47289. * Exposure, controls the overall intensity of the pipeline
  47290. * @type {number}
  47291. */
  47292. _this.exposure = 1.0;
  47293. /**
  47294. * Minimum luminance that the post-process can output. Luminance is >= 0
  47295. * @type {number}
  47296. */
  47297. _this.minimumLuminance = 1.0;
  47298. /**
  47299. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  47300. * @type {number}
  47301. */
  47302. _this.maximumLuminance = 1e20;
  47303. /**
  47304. * Increase rate for luminance: eye adaptation speed to dark
  47305. * @type {number}
  47306. */
  47307. _this.luminanceIncreaserate = 0.5;
  47308. /**
  47309. * Decrease rate for luminance: eye adaptation speed to bright
  47310. * @type {number}
  47311. */
  47312. _this.luminanceDecreaseRate = 0.5;
  47313. // Bright pass
  47314. /**
  47315. * Minimum luminance needed to compute HDR
  47316. * @type {number}
  47317. */
  47318. _this.brightThreshold = 0.8;
  47319. _this._needUpdate = true;
  47320. _this._scene = scene;
  47321. // Bright pass
  47322. _this._createBrightPassPostProcess(scene, ratio);
  47323. // Down sample X4
  47324. _this._createDownSampleX4PostProcess(scene, ratio);
  47325. // Create gaussian blur post-processes
  47326. _this._createGaussianBlurPostProcess(scene, ratio);
  47327. // Texture adder
  47328. _this._createTextureAdderPostProcess(scene, ratio);
  47329. // Luminance generator
  47330. _this._createLuminanceGeneratorPostProcess(scene);
  47331. // HDR
  47332. _this._createHDRPostProcess(scene, ratio);
  47333. // Pass postprocess
  47334. if (originalPostProcess === null) {
  47335. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47336. }
  47337. else {
  47338. _this._originalPostProcess = originalPostProcess;
  47339. }
  47340. // Configure pipeline
  47341. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  47342. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  47343. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  47344. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  47345. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  47346. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  47347. var addDownSamplerPostProcess = function (id) {
  47348. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  47349. };
  47350. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  47351. addDownSamplerPostProcess(i);
  47352. }
  47353. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  47354. // Finish
  47355. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47356. if (cameras !== null) {
  47357. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47358. }
  47359. _this.update();
  47360. return _this;
  47361. }
  47362. /**
  47363. * Tells the pipeline to update its post-processes
  47364. */
  47365. HDRRenderingPipeline.prototype.update = function () {
  47366. this._needUpdate = true;
  47367. };
  47368. /**
  47369. * Returns the current calculated luminance
  47370. */
  47371. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  47372. return this._hdrCurrentLuminance;
  47373. };
  47374. /**
  47375. * Returns the currently drawn luminance
  47376. */
  47377. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  47378. return this._hdrOutputLuminance;
  47379. };
  47380. /**
  47381. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  47382. */
  47383. HDRRenderingPipeline.prototype.dispose = function () {
  47384. for (var i = 0; i < this._scene.cameras.length; i++) {
  47385. var camera = this._scene.cameras[i];
  47386. this._originalPostProcess.dispose(camera);
  47387. this._brightPassPostProcess.dispose(camera);
  47388. this._downSampleX4PostProcess.dispose(camera);
  47389. this._guassianBlurHPostProcess.dispose(camera);
  47390. this._guassianBlurVPostProcess.dispose(camera);
  47391. this._textureAdderPostProcess.dispose(camera);
  47392. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  47393. this._downSamplePostProcesses[j].dispose(camera);
  47394. }
  47395. this._hdrPostProcess.dispose(camera);
  47396. }
  47397. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47398. _super.prototype.dispose.call(this);
  47399. };
  47400. /**
  47401. * Creates the HDR post-process and computes the luminance adaptation
  47402. */
  47403. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  47404. var _this = this;
  47405. var hdrLastLuminance = 0.0;
  47406. this._hdrOutputLuminance = -1.0;
  47407. this._hdrCurrentLuminance = 1.0;
  47408. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  47409. this._hdrPostProcess.onApply = function (effect) {
  47410. if (_this._hdrOutputLuminance < 0.0) {
  47411. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  47412. }
  47413. else {
  47414. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  47415. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  47416. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  47417. }
  47418. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  47419. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  47420. }
  47421. else {
  47422. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  47423. }
  47424. }
  47425. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  47426. hdrLastLuminance += scene.getEngine().getDeltaTime();
  47427. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  47428. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  47429. effect.setFloat("exposure", _this.exposure);
  47430. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  47431. _this._needUpdate = false;
  47432. };
  47433. };
  47434. /**
  47435. * Texture Adder post-process
  47436. */
  47437. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  47438. var _this = this;
  47439. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  47440. this._textureAdderPostProcess.onApply = function (effect) {
  47441. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  47442. };
  47443. };
  47444. /**
  47445. * Down sample X4 post-process
  47446. */
  47447. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  47448. var _this = this;
  47449. var downSampleX4Offsets = new Array(32);
  47450. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  47451. this._downSampleX4PostProcess.onApply = function (effect) {
  47452. if (_this._needUpdate) {
  47453. var id = 0;
  47454. for (var i = -2; i < 2; i++) {
  47455. for (var j = -2; j < 2; j++) {
  47456. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  47457. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  47458. id += 2;
  47459. }
  47460. }
  47461. }
  47462. effect.setArray2("dsOffsets", downSampleX4Offsets);
  47463. };
  47464. };
  47465. /**
  47466. * Bright pass post-process
  47467. */
  47468. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  47469. var _this = this;
  47470. var brightOffsets = new Array(8);
  47471. var brightPassCallback = function (effect) {
  47472. if (_this._needUpdate) {
  47473. var sU = (1.0 / _this._brightPassPostProcess.width);
  47474. var sV = (1.0 / _this._brightPassPostProcess.height);
  47475. brightOffsets[0] = -0.5 * sU;
  47476. brightOffsets[1] = 0.5 * sV;
  47477. brightOffsets[2] = 0.5 * sU;
  47478. brightOffsets[3] = 0.5 * sV;
  47479. brightOffsets[4] = -0.5 * sU;
  47480. brightOffsets[5] = -0.5 * sV;
  47481. brightOffsets[6] = 0.5 * sU;
  47482. brightOffsets[7] = -0.5 * sV;
  47483. }
  47484. effect.setArray2("dsOffsets", brightOffsets);
  47485. effect.setFloat("brightThreshold", _this.brightThreshold);
  47486. };
  47487. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  47488. this._brightPassPostProcess.onApply = brightPassCallback;
  47489. };
  47490. /**
  47491. * Luminance generator. Creates the luminance post-process and down sample post-processes
  47492. */
  47493. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  47494. var _this = this;
  47495. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  47496. var luminanceOffsets = new Array(8);
  47497. var downSampleOffsets = new Array(18);
  47498. var halfDestPixelSize;
  47499. this._downSamplePostProcesses = new Array(lumSteps);
  47500. // Utils for luminance
  47501. var luminanceUpdateSourceOffsets = function (width, height) {
  47502. var sU = (1.0 / width);
  47503. var sV = (1.0 / height);
  47504. luminanceOffsets[0] = -0.5 * sU;
  47505. luminanceOffsets[1] = 0.5 * sV;
  47506. luminanceOffsets[2] = 0.5 * sU;
  47507. luminanceOffsets[3] = 0.5 * sV;
  47508. luminanceOffsets[4] = -0.5 * sU;
  47509. luminanceOffsets[5] = -0.5 * sV;
  47510. luminanceOffsets[6] = 0.5 * sU;
  47511. luminanceOffsets[7] = -0.5 * sV;
  47512. };
  47513. var luminanceUpdateDestOffsets = function (width, height) {
  47514. var id = 0;
  47515. for (var x = -1; x < 2; x++) {
  47516. for (var y = -1; y < 2; y++) {
  47517. downSampleOffsets[id] = (x) / width;
  47518. downSampleOffsets[id + 1] = (y) / height;
  47519. id += 2;
  47520. }
  47521. }
  47522. };
  47523. // Luminance callback
  47524. var luminanceCallback = function (effect) {
  47525. if (_this._needUpdate) {
  47526. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  47527. }
  47528. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  47529. effect.setArray2("lumOffsets", luminanceOffsets);
  47530. };
  47531. // Down sample callbacks
  47532. var downSampleCallback = function (indice) {
  47533. var i = indice;
  47534. return function (effect) {
  47535. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47536. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  47537. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  47538. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  47539. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  47540. effect.setArray2("dsOffsets", downSampleOffsets);
  47541. };
  47542. };
  47543. var downSampleAfterRenderCallback = function (effect) {
  47544. // Unpack result
  47545. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  47546. 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);
  47547. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  47548. };
  47549. // Create luminance post-process
  47550. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  47551. 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);
  47552. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  47553. // Create down sample post-processes
  47554. for (var i = lumSteps - 2; i >= 0; i--) {
  47555. var length = Math.pow(3, i);
  47556. ratio = { width: length, height: length };
  47557. var defines = "#define DOWN_SAMPLE\n";
  47558. if (i === 0) {
  47559. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  47560. }
  47561. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  47562. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  47563. if (i === 0) {
  47564. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  47565. }
  47566. }
  47567. };
  47568. /**
  47569. * Gaussian blur post-processes. Horizontal and Vertical
  47570. */
  47571. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  47572. var _this = this;
  47573. var blurOffsetsW = new Array(9);
  47574. var blurOffsetsH = new Array(9);
  47575. var blurWeights = new Array(9);
  47576. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  47577. // Utils for gaussian blur
  47578. var calculateBlurOffsets = function (height) {
  47579. var lastOutputDimensions = {
  47580. width: scene.getEngine().getRenderWidth(),
  47581. height: scene.getEngine().getRenderHeight()
  47582. };
  47583. for (var i = 0; i < 9; i++) {
  47584. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  47585. if (height) {
  47586. blurOffsetsH[i] = value;
  47587. }
  47588. else {
  47589. blurOffsetsW[i] = value;
  47590. }
  47591. }
  47592. };
  47593. var calculateWeights = function () {
  47594. var x = 0.0;
  47595. for (var i = 0; i < 9; i++) {
  47596. x = (i - 4.0) / 4.0;
  47597. 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));
  47598. }
  47599. };
  47600. // Callback
  47601. var gaussianBlurCallback = function (height) {
  47602. return function (effect) {
  47603. if (_this._needUpdate) {
  47604. calculateWeights();
  47605. calculateBlurOffsets(height);
  47606. }
  47607. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  47608. effect.setArray("blurWeights", blurWeights);
  47609. effect.setFloat("multiplier", _this.gaussMultiplier);
  47610. };
  47611. };
  47612. // Create horizontal gaussian blur post-processes
  47613. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  47614. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  47615. // Create vertical gaussian blur post-process
  47616. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  47617. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  47618. };
  47619. return HDRRenderingPipeline;
  47620. }(BABYLON.PostProcessRenderPipeline));
  47621. // Luminance generator
  47622. HDRRenderingPipeline.LUM_STEPS = 6;
  47623. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  47624. })(BABYLON || (BABYLON = {}));
  47625. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  47626. /// <reference path="RenderPipeline\babylon.postProcessRenderPipeline.ts" />
  47627. var BABYLON;
  47628. (function (BABYLON) {
  47629. var StandardRenderingPipeline = (function (_super) {
  47630. __extends(StandardRenderingPipeline, _super);
  47631. /**
  47632. * @constructor
  47633. * @param {string} name - The rendering pipeline name
  47634. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47635. * @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)
  47636. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  47637. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47638. */
  47639. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  47640. if (originalPostProcess === void 0) { originalPostProcess = null; }
  47641. var _this = _super.call(this, scene.getEngine(), name) || this;
  47642. _this.downSampleX4PostProcess = null;
  47643. _this.brightPassPostProcess = null;
  47644. _this.gaussianBlurHPostProcesses = [];
  47645. _this.gaussianBlurVPostProcesses = [];
  47646. _this.textureAdderPostProcess = null;
  47647. _this.textureAdderFinalPostProcess = null;
  47648. _this.lensFlareFinalPostProcess = null;
  47649. _this.lensFlarePostProcess = null;
  47650. _this.lensFlareComposePostProcess = null;
  47651. _this.depthOfFieldPostProcess = null;
  47652. // Values
  47653. _this.brightThreshold = 1.0;
  47654. _this.blurWidth = 2.0;
  47655. _this.horizontalBlur = false;
  47656. _this.gaussianCoefficient = 0.25;
  47657. _this.gaussianMean = 1.0;
  47658. _this.gaussianStandardDeviation = 1.0;
  47659. _this.exposure = 1.0;
  47660. _this.lensTexture = null;
  47661. _this.lensColorTexture = null;
  47662. _this.lensFlareStrength = 20.0;
  47663. _this.lensFlareGhostDispersal = 1.4;
  47664. _this.lensFlareHaloWidth = 0.7;
  47665. _this.lensFlareDistortionStrength = 16.0;
  47666. _this.lensStarTexture = null;
  47667. _this.lensFlareDirtTexture = null;
  47668. _this.depthOfFieldDistance = 10.0;
  47669. _this.depthOfFieldBlurWidth = 2.0;
  47670. // IAnimatable
  47671. _this.animations = [];
  47672. _this._depthRenderer = null;
  47673. _this._currentDepthOfFieldSource = null;
  47674. // Getters and setters
  47675. _this._depthOfFieldEnabled = true;
  47676. _this._lensFlareEnabled = true;
  47677. _this._cameras = cameras || [];
  47678. // Initialize
  47679. _this._scene = scene;
  47680. // Create pass post-processe
  47681. if (!originalPostProcess) {
  47682. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  47683. }
  47684. else {
  47685. _this.originalPostProcess = originalPostProcess;
  47686. }
  47687. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  47688. // Create down sample X4 post-process
  47689. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  47690. // Create bright pass post-process
  47691. _this._createBrightPassPostProcess(scene, ratio / 2);
  47692. // Create gaussian blur post-processes (down sampling blurs)
  47693. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  47694. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  47695. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  47696. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  47697. // Create texture adder post-process
  47698. _this._createTextureAdderPostProcess(scene, ratio);
  47699. // Create depth-of-field source post-process
  47700. _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);
  47701. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  47702. // Create lens flare post-process
  47703. _this._createLensFlarePostProcess(scene, ratio);
  47704. // Create depth-of-field source post-process post lens-flare and disable it now
  47705. _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);
  47706. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  47707. // Create gaussian blur used by depth-of-field
  47708. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5, "depthOfFieldBlurWidth");
  47709. // Create depth-of-field post-process
  47710. _this._createDepthOfFieldPostProcess(scene, ratio);
  47711. // Finish
  47712. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47713. if (cameras !== null) {
  47714. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47715. }
  47716. // Deactivate
  47717. _this.LensFlareEnabled = false;
  47718. _this.DepthOfFieldEnabled = false;
  47719. return _this;
  47720. }
  47721. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  47722. get: function () {
  47723. return this._depthOfFieldEnabled;
  47724. },
  47725. set: function (enabled) {
  47726. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  47727. if (enabled && !this._depthOfFieldEnabled) {
  47728. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  47729. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  47730. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._cameras);
  47731. this._depthRenderer = this._scene.enableDepthRenderer();
  47732. }
  47733. else if (!enabled && this._depthOfFieldEnabled) {
  47734. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  47735. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  47736. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._cameras);
  47737. }
  47738. this._depthOfFieldEnabled = enabled;
  47739. },
  47740. enumerable: true,
  47741. configurable: true
  47742. });
  47743. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  47744. get: function () {
  47745. return this._lensFlareEnabled;
  47746. },
  47747. set: function (enabled) {
  47748. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  47749. if (enabled && !this._lensFlareEnabled) {
  47750. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._cameras);
  47751. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._cameras);
  47752. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  47753. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  47754. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._cameras);
  47755. this._setDepthOfFieldSavePostProcess("HDRPostLensFlareDepthOfFieldSource");
  47756. }
  47757. else if (!enabled && this._lensFlareEnabled) {
  47758. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._cameras);
  47759. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._cameras);
  47760. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._cameras);
  47761. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._cameras);
  47762. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._cameras);
  47763. this._setDepthOfFieldSavePostProcess("HDRBaseDepthOfFieldSource");
  47764. }
  47765. this._lensFlareEnabled = enabled;
  47766. },
  47767. enumerable: true,
  47768. configurable: true
  47769. });
  47770. // Sets depth-of-field save post-process
  47771. StandardRenderingPipeline.prototype._setDepthOfFieldSavePostProcess = function (name) {
  47772. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRPostLensFlareDepthOfFieldSource", this._cameras);
  47773. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, name, this._cameras);
  47774. switch (name) {
  47775. case "HDRBaseDepthOfFieldSource":
  47776. this._currentDepthOfFieldSource = this.textureAdderFinalPostProcess;
  47777. break;
  47778. case "HDRPostLensFlareDepthOfFieldSource":
  47779. this._currentDepthOfFieldSource = this.lensFlareFinalPostProcess;
  47780. break;
  47781. default: break;
  47782. }
  47783. };
  47784. // Down Sample X4 Post-Processs
  47785. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  47786. var _this = this;
  47787. var downSampleX4Offsets = new Array(32);
  47788. 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);
  47789. this.downSampleX4PostProcess.onApply = function (effect) {
  47790. var id = 0;
  47791. for (var i = -2; i < 2; i++) {
  47792. for (var j = -2; j < 2; j++) {
  47793. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  47794. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  47795. id += 2;
  47796. }
  47797. }
  47798. effect.setArray2("dsOffsets", downSampleX4Offsets);
  47799. };
  47800. // Add to pipeline
  47801. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  47802. };
  47803. // Brightpass Post-Process
  47804. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  47805. var _this = this;
  47806. var brightOffsets = new Array(8);
  47807. 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);
  47808. this.brightPassPostProcess.onApply = function (effect) {
  47809. var sU = (1.0 / _this.brightPassPostProcess.width);
  47810. var sV = (1.0 / _this.brightPassPostProcess.height);
  47811. brightOffsets[0] = -0.5 * sU;
  47812. brightOffsets[1] = 0.5 * sV;
  47813. brightOffsets[2] = 0.5 * sU;
  47814. brightOffsets[3] = 0.5 * sV;
  47815. brightOffsets[4] = -0.5 * sU;
  47816. brightOffsets[5] = -0.5 * sV;
  47817. brightOffsets[6] = 0.5 * sU;
  47818. brightOffsets[7] = -0.5 * sV;
  47819. effect.setArray2("dsOffsets", brightOffsets);
  47820. effect.setFloat("brightThreshold", _this.brightThreshold);
  47821. };
  47822. // Add to pipeline
  47823. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  47824. };
  47825. // Create gaussian blur H&V post-processes
  47826. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  47827. var _this = this;
  47828. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  47829. var blurOffsets = new Array(9);
  47830. var blurWeights = new Array(9);
  47831. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  47832. var callback = function (height) {
  47833. return function (effect) {
  47834. // Weights
  47835. var x = 0.0;
  47836. for (var i = 0; i < 9; i++) {
  47837. x = (i - 4.0) / 4.0;
  47838. blurWeights[i] =
  47839. _this.gaussianCoefficient
  47840. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  47841. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  47842. }
  47843. var lastOutputDimensions = {
  47844. width: scene.getEngine().getRenderWidth(),
  47845. height: scene.getEngine().getRenderHeight()
  47846. };
  47847. for (var i = 0; i < 9; i++) {
  47848. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  47849. blurOffsets[i] = value;
  47850. }
  47851. effect.setArray("blurOffsets", blurOffsets);
  47852. effect.setArray("blurWeights", blurWeights);
  47853. if (height) {
  47854. effect.setFloat("blurWidth", _this.horizontalBlur ? 1.0 : _this[blurWidthKey]);
  47855. }
  47856. else {
  47857. effect.setFloat("blurWidth", _this[blurWidthKey]);
  47858. }
  47859. };
  47860. };
  47861. // Create horizontal gaussian blur post-processes
  47862. 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);
  47863. gaussianBlurHPostProcess.onApply = callback(false);
  47864. // Create vertical gaussian blur post-process
  47865. 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);
  47866. gaussianBlurVPostProcess.onApply = callback(true);
  47867. // Add to pipeline
  47868. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  47869. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  47870. // Finish
  47871. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  47872. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  47873. };
  47874. // Create texture adder post-process
  47875. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  47876. var _this = this;
  47877. 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);
  47878. this.textureAdderPostProcess.onApply = function (effect) {
  47879. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  47880. effect.setTexture("lensSampler", _this.lensTexture);
  47881. effect.setFloat("exposure", _this.exposure);
  47882. };
  47883. // Add to pipeline
  47884. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  47885. };
  47886. // Create lens flare post-process
  47887. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  47888. var _this = this;
  47889. 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);
  47890. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  47891. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  47892. 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);
  47893. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  47894. var resolution = new BABYLON.Vector2(0, 0);
  47895. // Lens flare
  47896. this.lensFlarePostProcess.onApply = function (effect) {
  47897. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  47898. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  47899. effect.setFloat("strength", _this.lensFlareStrength);
  47900. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  47901. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  47902. // Shift
  47903. resolution.x = _this.lensFlarePostProcess.width;
  47904. resolution.y = _this.lensFlarePostProcess.height;
  47905. effect.setVector2("resolution", resolution);
  47906. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  47907. };
  47908. // Compose
  47909. 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);
  47910. 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);
  47911. this.lensFlareComposePostProcess.onApply = function (effect) {
  47912. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  47913. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  47914. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  47915. // Lens start rotation matrix
  47916. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  47917. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  47918. 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));
  47919. camRot *= 4.0;
  47920. 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);
  47921. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  47922. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  47923. };
  47924. };
  47925. // Create depth-of-field post-process
  47926. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  47927. var _this = this;
  47928. 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);
  47929. this.depthOfFieldPostProcess.onApply = function (effect) {
  47930. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  47931. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  47932. effect.setFloat("distance", _this.depthOfFieldDistance);
  47933. };
  47934. // Add to pipeline
  47935. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  47936. };
  47937. // Dispose
  47938. StandardRenderingPipeline.prototype.dispose = function () {
  47939. for (var i = 0; i < this._cameras.length; i++) {
  47940. var camera = this._cameras[i];
  47941. this.originalPostProcess.dispose(camera);
  47942. this.downSampleX4PostProcess.dispose(camera);
  47943. this.brightPassPostProcess.dispose(camera);
  47944. this.textureAdderPostProcess.dispose(camera);
  47945. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  47946. this.gaussianBlurHPostProcesses[j].dispose(camera);
  47947. }
  47948. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  47949. this.gaussianBlurVPostProcesses[j].dispose(camera);
  47950. }
  47951. this.textureAdderFinalPostProcess.dispose(camera);
  47952. this.lensFlarePostProcess.dispose(camera);
  47953. this.lensFlareComposePostProcess.dispose(camera);
  47954. this.depthOfFieldPostProcess.dispose(camera);
  47955. }
  47956. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  47957. _super.prototype.dispose.call(this);
  47958. };
  47959. // Serialize rendering pipeline
  47960. StandardRenderingPipeline.prototype.serialize = function () {
  47961. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47962. serializationObject.customType = "StandardRenderingPipeline";
  47963. return serializationObject;
  47964. };
  47965. // Parse serialized pipeline
  47966. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  47967. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  47968. };
  47969. return StandardRenderingPipeline;
  47970. }(BABYLON.PostProcessRenderPipeline));
  47971. __decorate([
  47972. BABYLON.serialize()
  47973. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  47974. __decorate([
  47975. BABYLON.serialize()
  47976. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  47977. __decorate([
  47978. BABYLON.serialize()
  47979. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  47980. __decorate([
  47981. BABYLON.serialize()
  47982. ], StandardRenderingPipeline.prototype, "gaussianCoefficient", void 0);
  47983. __decorate([
  47984. BABYLON.serialize()
  47985. ], StandardRenderingPipeline.prototype, "gaussianMean", void 0);
  47986. __decorate([
  47987. BABYLON.serialize()
  47988. ], StandardRenderingPipeline.prototype, "gaussianStandardDeviation", void 0);
  47989. __decorate([
  47990. BABYLON.serialize()
  47991. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  47992. __decorate([
  47993. BABYLON.serializeAsTexture("lensTexture")
  47994. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  47995. __decorate([
  47996. BABYLON.serializeAsTexture("lensColorTexture")
  47997. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  47998. __decorate([
  47999. BABYLON.serialize()
  48000. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  48001. __decorate([
  48002. BABYLON.serialize()
  48003. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  48004. __decorate([
  48005. BABYLON.serialize()
  48006. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  48007. __decorate([
  48008. BABYLON.serialize()
  48009. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  48010. __decorate([
  48011. BABYLON.serializeAsTexture("lensStarTexture")
  48012. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  48013. __decorate([
  48014. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  48015. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  48016. __decorate([
  48017. BABYLON.serialize()
  48018. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  48019. __decorate([
  48020. BABYLON.serialize()
  48021. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  48022. __decorate([
  48023. BABYLON.serialize()
  48024. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  48025. __decorate([
  48026. BABYLON.serialize()
  48027. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  48028. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  48029. })(BABYLON || (BABYLON = {}));
  48030. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  48031. var BABYLON;
  48032. (function (BABYLON) {
  48033. var BlurPostProcess = (function (_super) {
  48034. __extends(BlurPostProcess, _super);
  48035. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  48036. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48037. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  48038. _this.direction = direction;
  48039. _this.blurWidth = blurWidth;
  48040. _this.onApplyObservable.add(function (effect) {
  48041. effect.setFloat2("screenSize", _this.width, _this.height);
  48042. effect.setVector2("direction", _this.direction);
  48043. effect.setFloat("blurWidth", _this.blurWidth);
  48044. });
  48045. return _this;
  48046. }
  48047. return BlurPostProcess;
  48048. }(BABYLON.PostProcess));
  48049. BABYLON.BlurPostProcess = BlurPostProcess;
  48050. })(BABYLON || (BABYLON = {}));
  48051. //# sourceMappingURL=babylon.blurPostProcess.js.map
  48052. var BABYLON;
  48053. (function (BABYLON) {
  48054. var RefractionPostProcess = (function (_super) {
  48055. __extends(RefractionPostProcess, _super);
  48056. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  48057. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  48058. _this.color = color;
  48059. _this.depth = depth;
  48060. _this.colorLevel = colorLevel;
  48061. _this.onActivateObservable.add(function (cam) {
  48062. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  48063. });
  48064. _this.onApplyObservable.add(function (effect) {
  48065. effect.setColor3("baseColor", _this.color);
  48066. effect.setFloat("depth", _this.depth);
  48067. effect.setFloat("colorLevel", _this.colorLevel);
  48068. effect.setTexture("refractionSampler", _this._refRexture);
  48069. });
  48070. return _this;
  48071. }
  48072. // Methods
  48073. RefractionPostProcess.prototype.dispose = function (camera) {
  48074. if (this._refRexture) {
  48075. this._refRexture.dispose();
  48076. }
  48077. _super.prototype.dispose.call(this, camera);
  48078. };
  48079. return RefractionPostProcess;
  48080. }(BABYLON.PostProcess));
  48081. BABYLON.RefractionPostProcess = RefractionPostProcess;
  48082. })(BABYLON || (BABYLON = {}));
  48083. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  48084. var BABYLON;
  48085. (function (BABYLON) {
  48086. var BlackAndWhitePostProcess = (function (_super) {
  48087. __extends(BlackAndWhitePostProcess, _super);
  48088. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  48089. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  48090. }
  48091. return BlackAndWhitePostProcess;
  48092. }(BABYLON.PostProcess));
  48093. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  48094. })(BABYLON || (BABYLON = {}));
  48095. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  48096. var BABYLON;
  48097. (function (BABYLON) {
  48098. var ConvolutionPostProcess = (function (_super) {
  48099. __extends(ConvolutionPostProcess, _super);
  48100. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  48101. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  48102. _this.kernel = kernel;
  48103. _this.onApply = function (effect) {
  48104. effect.setFloat2("screenSize", _this.width, _this.height);
  48105. effect.setArray("kernel", _this.kernel);
  48106. };
  48107. return _this;
  48108. }
  48109. return ConvolutionPostProcess;
  48110. }(BABYLON.PostProcess));
  48111. // Statics
  48112. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  48113. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  48114. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  48115. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  48116. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  48117. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  48118. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  48119. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  48120. })(BABYLON || (BABYLON = {}));
  48121. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  48122. var BABYLON;
  48123. (function (BABYLON) {
  48124. var FilterPostProcess = (function (_super) {
  48125. __extends(FilterPostProcess, _super);
  48126. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  48127. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  48128. _this.kernelMatrix = kernelMatrix;
  48129. _this.onApply = function (effect) {
  48130. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  48131. };
  48132. return _this;
  48133. }
  48134. return FilterPostProcess;
  48135. }(BABYLON.PostProcess));
  48136. BABYLON.FilterPostProcess = FilterPostProcess;
  48137. })(BABYLON || (BABYLON = {}));
  48138. //# sourceMappingURL=babylon.filterPostProcess.js.map
  48139. var BABYLON;
  48140. (function (BABYLON) {
  48141. var FxaaPostProcess = (function (_super) {
  48142. __extends(FxaaPostProcess, _super);
  48143. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  48144. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable) || this;
  48145. _this.onSizeChangedObservable.add(function () {
  48146. _this.texelWidth = 1.0 / _this.width;
  48147. _this.texelHeight = 1.0 / _this.height;
  48148. });
  48149. _this.onApplyObservable.add(function (effect) {
  48150. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  48151. });
  48152. return _this;
  48153. }
  48154. return FxaaPostProcess;
  48155. }(BABYLON.PostProcess));
  48156. BABYLON.FxaaPostProcess = FxaaPostProcess;
  48157. })(BABYLON || (BABYLON = {}));
  48158. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  48159. var BABYLON;
  48160. (function (BABYLON) {
  48161. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  48162. var VolumetricLightScatteringPostProcess = (function (_super) {
  48163. __extends(VolumetricLightScatteringPostProcess, _super);
  48164. /**
  48165. * @constructor
  48166. * @param {string} name - The post-process name
  48167. * @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)
  48168. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  48169. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  48170. * @param {number} samples - The post-process quality, default 100
  48171. * @param {number} samplingMode - The post-process filtering mode
  48172. * @param {BABYLON.Engine} engine - The babylon engine
  48173. * @param {boolean} reusable - If the post-process is reusable
  48174. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  48175. */
  48176. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  48177. if (samples === void 0) { samples = 100; }
  48178. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48179. 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;
  48180. _this._screenCoordinates = BABYLON.Vector2.Zero();
  48181. /**
  48182. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  48183. * @type {Vector3}
  48184. */
  48185. _this.customMeshPosition = BABYLON.Vector3.Zero();
  48186. /**
  48187. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  48188. * @type {boolean}
  48189. */
  48190. _this.useCustomMeshPosition = false;
  48191. /**
  48192. * If the post-process should inverse the light scattering direction
  48193. * @type {boolean}
  48194. */
  48195. _this.invert = true;
  48196. /**
  48197. * Array containing the excluded meshes not rendered in the internal pass
  48198. */
  48199. _this.excludedMeshes = new Array();
  48200. /**
  48201. * Controls the overall intensity of the post-process
  48202. * @type {number}
  48203. */
  48204. _this.exposure = 0.3;
  48205. /**
  48206. * Dissipates each sample's contribution in range [0, 1]
  48207. * @type {number}
  48208. */
  48209. _this.decay = 0.96815;
  48210. /**
  48211. * Controls the overall intensity of each sample
  48212. * @type {number}
  48213. */
  48214. _this.weight = 0.58767;
  48215. /**
  48216. * Controls the density of each sample
  48217. * @type {number}
  48218. */
  48219. _this.density = 0.926;
  48220. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  48221. var engine = scene.getEngine();
  48222. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  48223. // Configure mesh
  48224. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  48225. // Configure
  48226. _this._createPass(scene, ratio.passRatio || ratio);
  48227. _this.onActivate = function (camera) {
  48228. if (!_this.isSupported) {
  48229. _this.dispose(camera);
  48230. }
  48231. _this.onActivate = null;
  48232. };
  48233. _this.onApplyObservable.add(function (effect) {
  48234. _this._updateMeshScreenCoordinates(scene);
  48235. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  48236. effect.setFloat("exposure", _this.exposure);
  48237. effect.setFloat("decay", _this.decay);
  48238. effect.setFloat("weight", _this.weight);
  48239. effect.setFloat("density", _this.density);
  48240. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  48241. });
  48242. return _this;
  48243. }
  48244. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  48245. get: function () {
  48246. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48247. return false;
  48248. },
  48249. set: function (useDiffuseColor) {
  48250. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48251. },
  48252. enumerable: true,
  48253. configurable: true
  48254. });
  48255. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  48256. var mesh = subMesh.getMesh();
  48257. // Render this.mesh as default
  48258. if (mesh === this.mesh) {
  48259. return mesh.material.isReady(mesh);
  48260. }
  48261. var defines = [];
  48262. var attribs = [BABYLON.VertexBuffer.PositionKind];
  48263. var material = subMesh.getMaterial();
  48264. var needUV = false;
  48265. // Alpha test
  48266. if (material) {
  48267. if (material.needAlphaTesting()) {
  48268. defines.push("#define ALPHATEST");
  48269. }
  48270. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48271. attribs.push(BABYLON.VertexBuffer.UVKind);
  48272. defines.push("#define UV1");
  48273. }
  48274. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48275. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48276. defines.push("#define UV2");
  48277. }
  48278. }
  48279. // Bones
  48280. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48281. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48282. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48283. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48284. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48285. }
  48286. else {
  48287. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48288. }
  48289. // Instances
  48290. if (useInstances) {
  48291. defines.push("#define INSTANCES");
  48292. attribs.push("world0");
  48293. attribs.push("world1");
  48294. attribs.push("world2");
  48295. attribs.push("world3");
  48296. }
  48297. // Get correct effect
  48298. var join = defines.join("\n");
  48299. if (this._cachedDefines !== join) {
  48300. this._cachedDefines = join;
  48301. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  48302. }
  48303. return this._volumetricLightScatteringPass.isReady();
  48304. };
  48305. /**
  48306. * Sets the new light position for light scattering effect
  48307. * @param {BABYLON.Vector3} The new custom light position
  48308. */
  48309. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  48310. this.customMeshPosition = position;
  48311. };
  48312. /**
  48313. * Returns the light position for light scattering effect
  48314. * @return {BABYLON.Vector3} The custom light position
  48315. */
  48316. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  48317. return this.customMeshPosition;
  48318. };
  48319. /**
  48320. * Disposes the internal assets and detaches the post-process from the camera
  48321. */
  48322. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  48323. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  48324. if (rttIndex !== -1) {
  48325. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  48326. }
  48327. this._volumetricLightScatteringRTT.dispose();
  48328. _super.prototype.dispose.call(this, camera);
  48329. };
  48330. /**
  48331. * Returns the render target texture used by the post-process
  48332. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  48333. */
  48334. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  48335. return this._volumetricLightScatteringRTT;
  48336. };
  48337. // Private methods
  48338. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  48339. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  48340. return true;
  48341. }
  48342. return false;
  48343. };
  48344. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  48345. var _this = this;
  48346. var engine = scene.getEngine();
  48347. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48348. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48349. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48350. this._volumetricLightScatteringRTT.renderList = null;
  48351. this._volumetricLightScatteringRTT.renderParticles = false;
  48352. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  48353. // Custom render function for submeshes
  48354. var renderSubMesh = function (subMesh) {
  48355. var mesh = subMesh.getRenderingMesh();
  48356. if (_this._meshExcluded(mesh)) {
  48357. return;
  48358. }
  48359. var scene = mesh.getScene();
  48360. var engine = scene.getEngine();
  48361. // Culling
  48362. engine.setState(subMesh.getMaterial().backFaceCulling);
  48363. // Managing instances
  48364. var batch = mesh._getInstancesRenderList(subMesh._id);
  48365. if (batch.mustReturn) {
  48366. return;
  48367. }
  48368. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  48369. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  48370. var effect = _this._volumetricLightScatteringPass;
  48371. if (mesh === _this.mesh) {
  48372. if (subMesh.effect) {
  48373. effect = subMesh.effect;
  48374. }
  48375. else {
  48376. effect = subMesh.getMaterial().getEffect();
  48377. }
  48378. }
  48379. engine.enableEffect(effect);
  48380. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  48381. if (mesh === _this.mesh) {
  48382. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  48383. }
  48384. else {
  48385. var material = subMesh.getMaterial();
  48386. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  48387. // Alpha test
  48388. if (material && material.needAlphaTesting()) {
  48389. var alphaTexture = material.getAlphaTestTexture();
  48390. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  48391. if (alphaTexture) {
  48392. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48393. }
  48394. }
  48395. // Bones
  48396. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48397. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48398. }
  48399. }
  48400. // Draw
  48401. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  48402. }
  48403. };
  48404. // Render target texture callbacks
  48405. var savedSceneClearColor;
  48406. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  48407. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  48408. savedSceneClearColor = scene.clearColor;
  48409. scene.clearColor = sceneClearColor;
  48410. });
  48411. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  48412. scene.clearColor = savedSceneClearColor;
  48413. });
  48414. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  48415. var engine = scene.getEngine();
  48416. var index;
  48417. for (index = 0; index < opaqueSubMeshes.length; index++) {
  48418. renderSubMesh(opaqueSubMeshes.data[index]);
  48419. }
  48420. engine.setAlphaTesting(true);
  48421. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  48422. renderSubMesh(alphaTestSubMeshes.data[index]);
  48423. }
  48424. engine.setAlphaTesting(false);
  48425. if (transparentSubMeshes.length) {
  48426. // Sort sub meshes
  48427. for (index = 0; index < transparentSubMeshes.length; index++) {
  48428. var submesh = transparentSubMeshes.data[index];
  48429. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  48430. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  48431. }
  48432. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  48433. sortedArray.sort(function (a, b) {
  48434. // Alpha index first
  48435. if (a._alphaIndex > b._alphaIndex) {
  48436. return 1;
  48437. }
  48438. if (a._alphaIndex < b._alphaIndex) {
  48439. return -1;
  48440. }
  48441. // Then distance to camera
  48442. if (a._distanceToCamera < b._distanceToCamera) {
  48443. return 1;
  48444. }
  48445. if (a._distanceToCamera > b._distanceToCamera) {
  48446. return -1;
  48447. }
  48448. return 0;
  48449. });
  48450. // Render sub meshes
  48451. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48452. for (index = 0; index < sortedArray.length; index++) {
  48453. renderSubMesh(sortedArray[index]);
  48454. }
  48455. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48456. }
  48457. };
  48458. };
  48459. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  48460. var transform = scene.getTransformMatrix();
  48461. var meshPosition;
  48462. if (this.useCustomMeshPosition) {
  48463. meshPosition = this.customMeshPosition;
  48464. }
  48465. else if (this.attachedNode) {
  48466. meshPosition = this.attachedNode.position;
  48467. }
  48468. else {
  48469. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  48470. }
  48471. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  48472. this._screenCoordinates.x = pos.x / this._viewPort.width;
  48473. this._screenCoordinates.y = pos.y / this._viewPort.height;
  48474. if (this.invert)
  48475. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  48476. };
  48477. // Static methods
  48478. /**
  48479. * Creates a default mesh for the Volumeric Light Scattering post-process
  48480. * @param {string} The mesh name
  48481. * @param {BABYLON.Scene} The scene where to create the mesh
  48482. * @return {BABYLON.Mesh} the default mesh
  48483. */
  48484. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  48485. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  48486. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  48487. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  48488. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  48489. mesh.material = material;
  48490. return mesh;
  48491. };
  48492. return VolumetricLightScatteringPostProcess;
  48493. }(BABYLON.PostProcess));
  48494. __decorate([
  48495. BABYLON.serializeAsVector3()
  48496. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  48497. __decorate([
  48498. BABYLON.serialize()
  48499. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  48500. __decorate([
  48501. BABYLON.serialize()
  48502. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  48503. __decorate([
  48504. BABYLON.serializeAsMeshReference()
  48505. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  48506. __decorate([
  48507. BABYLON.serialize()
  48508. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  48509. __decorate([
  48510. BABYLON.serialize()
  48511. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  48512. __decorate([
  48513. BABYLON.serialize()
  48514. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  48515. __decorate([
  48516. BABYLON.serialize()
  48517. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  48518. __decorate([
  48519. BABYLON.serialize()
  48520. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  48521. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  48522. })(BABYLON || (BABYLON = {}));
  48523. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  48524. //
  48525. // This post-process allows the modification of rendered colors by using
  48526. // a 'look-up table' (LUT). This effect is also called Color Grading.
  48527. //
  48528. // The object needs to be provided an url to a texture containing the color
  48529. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  48530. // Use an image editing software to tweak the LUT to match your needs.
  48531. //
  48532. // For an example of a color LUT, see here:
  48533. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  48534. // For explanations on color grading, see here:
  48535. // http://udn.epicgames.com/Three/ColorGrading.html
  48536. //
  48537. var BABYLON;
  48538. (function (BABYLON) {
  48539. var ColorCorrectionPostProcess = (function (_super) {
  48540. __extends(ColorCorrectionPostProcess, _super);
  48541. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  48542. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  48543. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  48544. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  48545. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48546. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48547. _this.onApply = function (effect) {
  48548. effect.setTexture("colorTable", _this._colorTableTexture);
  48549. };
  48550. return _this;
  48551. }
  48552. return ColorCorrectionPostProcess;
  48553. }(BABYLON.PostProcess));
  48554. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  48555. })(BABYLON || (BABYLON = {}));
  48556. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  48557. var BABYLON;
  48558. (function (BABYLON) {
  48559. var TonemappingOperator;
  48560. (function (TonemappingOperator) {
  48561. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  48562. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  48563. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  48564. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  48565. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  48566. ;
  48567. var TonemapPostProcess = (function (_super) {
  48568. __extends(TonemapPostProcess, _super);
  48569. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  48570. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48571. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48572. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  48573. _this._operator = _operator;
  48574. _this.exposureAdjustment = exposureAdjustment;
  48575. var defines = "#define ";
  48576. if (_this._operator === TonemappingOperator.Hable)
  48577. defines += "HABLE_TONEMAPPING";
  48578. else if (_this._operator === TonemappingOperator.Reinhard)
  48579. defines += "REINHARD_TONEMAPPING";
  48580. else if (_this._operator === TonemappingOperator.HejiDawson)
  48581. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  48582. else if (_this._operator === TonemappingOperator.Photographic)
  48583. defines += "PHOTOGRAPHIC_TONEMAPPING";
  48584. //sadly a second call to create the effect.
  48585. _this.updateEffect(defines);
  48586. _this.onApply = function (effect) {
  48587. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  48588. };
  48589. return _this;
  48590. }
  48591. return TonemapPostProcess;
  48592. }(BABYLON.PostProcess));
  48593. BABYLON.TonemapPostProcess = TonemapPostProcess;
  48594. })(BABYLON || (BABYLON = {}));
  48595. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  48596. var BABYLON;
  48597. (function (BABYLON) {
  48598. var DisplayPassPostProcess = (function (_super) {
  48599. __extends(DisplayPassPostProcess, _super);
  48600. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  48601. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  48602. }
  48603. return DisplayPassPostProcess;
  48604. }(BABYLON.PostProcess));
  48605. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  48606. })(BABYLON || (BABYLON = {}));
  48607. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  48608. /// <reference path="..\babylon.node.ts" />
  48609. var BABYLON;
  48610. (function (BABYLON) {
  48611. var Bone = (function (_super) {
  48612. __extends(Bone, _super);
  48613. function Bone(name, skeleton, parentBone, matrix, restPose) {
  48614. var _this = _super.call(this, name, skeleton.getScene()) || this;
  48615. _this.name = name;
  48616. _this.children = new Array();
  48617. _this.animations = new Array();
  48618. _this._worldTransform = new BABYLON.Matrix();
  48619. _this._absoluteTransform = new BABYLON.Matrix();
  48620. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  48621. _this._scaleMatrix = BABYLON.Matrix.Identity();
  48622. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  48623. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  48624. _this._scalingDeterminant = 1;
  48625. _this._skeleton = skeleton;
  48626. _this._localMatrix = matrix;
  48627. _this._baseMatrix = matrix.clone();
  48628. _this._restPose = restPose ? restPose : matrix.clone();
  48629. skeleton.bones.push(_this);
  48630. if (parentBone) {
  48631. _this._parent = parentBone;
  48632. parentBone.children.push(_this);
  48633. }
  48634. else {
  48635. _this._parent = null;
  48636. }
  48637. _this._updateDifferenceMatrix();
  48638. if (_this.getAbsoluteTransform().determinant() < 0) {
  48639. _this._scalingDeterminant *= -1;
  48640. }
  48641. return _this;
  48642. }
  48643. Object.defineProperty(Bone.prototype, "_matrix", {
  48644. get: function () {
  48645. return this._localMatrix;
  48646. },
  48647. set: function (val) {
  48648. if (this._localMatrix) {
  48649. this._localMatrix.copyFrom(val);
  48650. }
  48651. else {
  48652. this._localMatrix = val;
  48653. }
  48654. },
  48655. enumerable: true,
  48656. configurable: true
  48657. });
  48658. // Members
  48659. Bone.prototype.getParent = function () {
  48660. return this._parent;
  48661. };
  48662. Bone.prototype.getLocalMatrix = function () {
  48663. return this._localMatrix;
  48664. };
  48665. Bone.prototype.getBaseMatrix = function () {
  48666. return this._baseMatrix;
  48667. };
  48668. Bone.prototype.getRestPose = function () {
  48669. return this._restPose;
  48670. };
  48671. Bone.prototype.returnToRest = function () {
  48672. this.updateMatrix(this._restPose.clone());
  48673. };
  48674. Bone.prototype.getWorldMatrix = function () {
  48675. return this._worldTransform;
  48676. };
  48677. Bone.prototype.getInvertedAbsoluteTransform = function () {
  48678. return this._invertedAbsoluteTransform;
  48679. };
  48680. Bone.prototype.getAbsoluteTransform = function () {
  48681. return this._absoluteTransform;
  48682. };
  48683. // Methods
  48684. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  48685. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  48686. this._baseMatrix = matrix.clone();
  48687. this._localMatrix = matrix.clone();
  48688. this._skeleton._markAsDirty();
  48689. if (updateDifferenceMatrix) {
  48690. this._updateDifferenceMatrix();
  48691. }
  48692. };
  48693. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  48694. if (!rootMatrix) {
  48695. rootMatrix = this._baseMatrix;
  48696. }
  48697. if (this._parent) {
  48698. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  48699. }
  48700. else {
  48701. this._absoluteTransform.copyFrom(rootMatrix);
  48702. }
  48703. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  48704. for (var index = 0; index < this.children.length; index++) {
  48705. this.children[index]._updateDifferenceMatrix();
  48706. }
  48707. };
  48708. Bone.prototype.markAsDirty = function () {
  48709. this._currentRenderId++;
  48710. this._skeleton._markAsDirty();
  48711. };
  48712. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  48713. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  48714. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  48715. // all animation may be coming from a library skeleton, so may need to create animation
  48716. if (this.animations.length === 0) {
  48717. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  48718. this.animations[0].setKeys([]);
  48719. }
  48720. // get animation info / verify there is such a range from the source bone
  48721. var sourceRange = source.animations[0].getRange(rangeName);
  48722. if (!sourceRange) {
  48723. return false;
  48724. }
  48725. var from = sourceRange.from;
  48726. var to = sourceRange.to;
  48727. var sourceKeys = source.animations[0].getKeys();
  48728. // rescaling prep
  48729. var sourceBoneLength = source.length;
  48730. var sourceParent = source.getParent();
  48731. var parent = this.getParent();
  48732. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  48733. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  48734. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  48735. var destKeys = this.animations[0].getKeys();
  48736. // loop vars declaration
  48737. var orig;
  48738. var origTranslation;
  48739. var mat;
  48740. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  48741. orig = sourceKeys[key];
  48742. if (orig.frame >= from && orig.frame <= to) {
  48743. if (rescaleAsRequired) {
  48744. mat = orig.value.clone();
  48745. // scale based on parent ratio, when bone has parent
  48746. if (parentScalingReqd) {
  48747. origTranslation = mat.getTranslation();
  48748. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  48749. // scale based on skeleton dimension ratio when root bone, and value is passed
  48750. }
  48751. else if (dimensionsScalingReqd) {
  48752. origTranslation = mat.getTranslation();
  48753. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  48754. // use original when root bone, and no data for skelDimensionsRatio
  48755. }
  48756. else {
  48757. mat = orig.value;
  48758. }
  48759. }
  48760. else {
  48761. mat = orig.value;
  48762. }
  48763. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  48764. }
  48765. }
  48766. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  48767. return true;
  48768. };
  48769. /**
  48770. * Translate the bone in local or world space.
  48771. * @param vec The amount to translate the bone.
  48772. * @param space The space that the translation is in.
  48773. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48774. */
  48775. Bone.prototype.translate = function (vec, space, mesh) {
  48776. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48777. var lm = this.getLocalMatrix();
  48778. if (space == BABYLON.Space.LOCAL) {
  48779. lm.m[12] += vec.x;
  48780. lm.m[13] += vec.y;
  48781. lm.m[14] += vec.z;
  48782. }
  48783. else {
  48784. var wm;
  48785. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  48786. if (mesh) {
  48787. wm = mesh.getWorldMatrix();
  48788. }
  48789. this._skeleton.computeAbsoluteTransforms();
  48790. var tmat = Bone._tmpMats[0];
  48791. var tvec = Bone._tmpVecs[0];
  48792. if (mesh) {
  48793. tmat.copyFrom(this._parent.getAbsoluteTransform());
  48794. tmat.multiplyToRef(wm, tmat);
  48795. }
  48796. else {
  48797. tmat.copyFrom(this._parent.getAbsoluteTransform());
  48798. }
  48799. tmat.m[12] = 0;
  48800. tmat.m[13] = 0;
  48801. tmat.m[14] = 0;
  48802. tmat.invert();
  48803. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  48804. lm.m[12] += tvec.x;
  48805. lm.m[13] += tvec.y;
  48806. lm.m[14] += tvec.z;
  48807. }
  48808. this.markAsDirty();
  48809. };
  48810. /**
  48811. * Set the postion of the bone in local or world space.
  48812. * @param position The position to set the bone.
  48813. * @param space The space that the position is in.
  48814. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48815. */
  48816. Bone.prototype.setPosition = function (position, space, mesh) {
  48817. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48818. var lm = this.getLocalMatrix();
  48819. if (space == BABYLON.Space.LOCAL) {
  48820. lm.m[12] = position.x;
  48821. lm.m[13] = position.y;
  48822. lm.m[14] = position.z;
  48823. }
  48824. else {
  48825. var wm;
  48826. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  48827. if (mesh) {
  48828. wm = mesh.getWorldMatrix();
  48829. }
  48830. this._skeleton.computeAbsoluteTransforms();
  48831. var tmat = Bone._tmpMats[0];
  48832. var vec = Bone._tmpVecs[0];
  48833. if (mesh) {
  48834. tmat.copyFrom(this._parent.getAbsoluteTransform());
  48835. tmat.multiplyToRef(wm, tmat);
  48836. }
  48837. else {
  48838. tmat.copyFrom(this._parent.getAbsoluteTransform());
  48839. }
  48840. tmat.invert();
  48841. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  48842. lm.m[12] = vec.x;
  48843. lm.m[13] = vec.y;
  48844. lm.m[14] = vec.z;
  48845. }
  48846. this.markAsDirty();
  48847. };
  48848. /**
  48849. * Set the absolute postion of the bone (world space).
  48850. * @param position The position to set the bone.
  48851. * @param mesh The mesh that this bone is attached to.
  48852. */
  48853. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  48854. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  48855. };
  48856. /**
  48857. * Set the scale of the bone on the x, y and z axes.
  48858. * @param x The scale of the bone on the x axis.
  48859. * @param x The scale of the bone on the y axis.
  48860. * @param z The scale of the bone on the z axis.
  48861. * @param scaleChildren Set this to true if children of the bone should be scaled.
  48862. */
  48863. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  48864. if (scaleChildren === void 0) { scaleChildren = false; }
  48865. if (this.animations[0] && !this.animations[0].isStopped()) {
  48866. if (!scaleChildren) {
  48867. this._negateScaleChildren.x = 1 / x;
  48868. this._negateScaleChildren.y = 1 / y;
  48869. this._negateScaleChildren.z = 1 / z;
  48870. }
  48871. this._syncScaleVector();
  48872. }
  48873. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  48874. };
  48875. /**
  48876. * Scale the bone on the x, y and z axes.
  48877. * @param x The amount to scale the bone on the x axis.
  48878. * @param x The amount to scale the bone on the y axis.
  48879. * @param z The amount to scale the bone on the z axis.
  48880. * @param scaleChildren Set this to true if children of the bone should be scaled.
  48881. */
  48882. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  48883. if (scaleChildren === void 0) { scaleChildren = false; }
  48884. var locMat = this.getLocalMatrix();
  48885. var origLocMat = Bone._tmpMats[0];
  48886. origLocMat.copyFrom(locMat);
  48887. var origLocMatInv = Bone._tmpMats[1];
  48888. origLocMatInv.copyFrom(origLocMat);
  48889. origLocMatInv.invert();
  48890. var scaleMat = Bone._tmpMats[2];
  48891. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  48892. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  48893. this._scaleVector.x *= x;
  48894. this._scaleVector.y *= y;
  48895. this._scaleVector.z *= z;
  48896. locMat.multiplyToRef(origLocMatInv, locMat);
  48897. locMat.multiplyToRef(scaleMat, locMat);
  48898. locMat.multiplyToRef(origLocMat, locMat);
  48899. var parent = this.getParent();
  48900. if (parent) {
  48901. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  48902. }
  48903. else {
  48904. this.getAbsoluteTransform().copyFrom(locMat);
  48905. }
  48906. var len = this.children.length;
  48907. scaleMat.invert();
  48908. for (var i = 0; i < len; i++) {
  48909. var child = this.children[i];
  48910. var cm = child.getLocalMatrix();
  48911. cm.multiplyToRef(scaleMat, cm);
  48912. var lm = child.getLocalMatrix();
  48913. lm.m[12] *= x;
  48914. lm.m[13] *= y;
  48915. lm.m[14] *= z;
  48916. }
  48917. this.computeAbsoluteTransforms();
  48918. if (scaleChildren) {
  48919. for (var i = 0; i < len; i++) {
  48920. this.children[i].scale(x, y, z, scaleChildren);
  48921. }
  48922. }
  48923. this.markAsDirty();
  48924. };
  48925. /**
  48926. * Set the yaw, pitch, and roll of the bone in local or world space.
  48927. * @param yaw The rotation of the bone on the y axis.
  48928. * @param pitch The rotation of the bone on the x axis.
  48929. * @param roll The rotation of the bone on the z axis.
  48930. * @param space The space that the axes of rotation are in.
  48931. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48932. */
  48933. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  48934. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48935. var rotMat = Bone._tmpMats[0];
  48936. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  48937. var rotMatInv = Bone._tmpMats[1];
  48938. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  48939. rotMatInv.multiplyToRef(rotMat, rotMat);
  48940. this._rotateWithMatrix(rotMat, space, mesh);
  48941. };
  48942. /**
  48943. * Rotate the bone on an axis in local or world space.
  48944. * @param axis The axis to rotate the bone on.
  48945. * @param amount The amount to rotate the bone.
  48946. * @param space The space that the axis is in.
  48947. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48948. */
  48949. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  48950. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48951. var rmat = Bone._tmpMats[0];
  48952. rmat.m[12] = 0;
  48953. rmat.m[13] = 0;
  48954. rmat.m[14] = 0;
  48955. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  48956. this._rotateWithMatrix(rmat, space, mesh);
  48957. };
  48958. /**
  48959. * Set the rotation of the bone to a particular axis angle in local or world space.
  48960. * @param axis The axis to rotate the bone on.
  48961. * @param angle The angle that the bone should be rotated to.
  48962. * @param space The space that the axis is in.
  48963. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48964. */
  48965. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  48966. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48967. var rotMat = Bone._tmpMats[0];
  48968. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  48969. var rotMatInv = Bone._tmpMats[1];
  48970. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  48971. rotMatInv.multiplyToRef(rotMat, rotMat);
  48972. this._rotateWithMatrix(rotMat, space, mesh);
  48973. };
  48974. /**
  48975. * Set the euler rotation of the bone in local of world space.
  48976. * @param rotation The euler rotation that the bone should be set to.
  48977. * @param space The space that the rotation is in.
  48978. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48979. */
  48980. Bone.prototype.setRotation = function (rotation, space, mesh) {
  48981. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48982. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  48983. };
  48984. /**
  48985. * Set the quaternion rotation of the bone in local of world space.
  48986. * @param quat The quaternion rotation that the bone should be set to.
  48987. * @param space The space that the rotation is in.
  48988. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  48989. */
  48990. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  48991. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  48992. var rotMatInv = Bone._tmpMats[0];
  48993. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  48994. var rotMat = Bone._tmpMats[1];
  48995. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  48996. rotMatInv.multiplyToRef(rotMat, rotMat);
  48997. this._rotateWithMatrix(rotMat, space, mesh);
  48998. };
  48999. /**
  49000. * Set the rotation matrix of the bone in local of world space.
  49001. * @param rotMat The rotation matrix that the bone should be set to.
  49002. * @param space The space that the rotation is in.
  49003. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49004. */
  49005. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  49006. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49007. var rotMatInv = Bone._tmpMats[0];
  49008. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  49009. var rotMat2 = Bone._tmpMats[1];
  49010. rotMat2.copyFrom(rotMat);
  49011. rotMatInv.multiplyToRef(rotMat, rotMat2);
  49012. this._rotateWithMatrix(rotMat2, space, mesh);
  49013. };
  49014. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  49015. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49016. var lmat = this.getLocalMatrix();
  49017. var lx = lmat.m[12];
  49018. var ly = lmat.m[13];
  49019. var lz = lmat.m[14];
  49020. var parent = this.getParent();
  49021. var parentScale = Bone._tmpMats[3];
  49022. var parentScaleInv = Bone._tmpMats[4];
  49023. if (parent) {
  49024. if (space == BABYLON.Space.WORLD) {
  49025. if (mesh) {
  49026. parentScale.copyFrom(mesh.getWorldMatrix());
  49027. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  49028. }
  49029. else {
  49030. parentScale.copyFrom(parent.getAbsoluteTransform());
  49031. }
  49032. }
  49033. else {
  49034. parentScale = parent._scaleMatrix;
  49035. }
  49036. parentScaleInv.copyFrom(parentScale);
  49037. parentScaleInv.invert();
  49038. lmat.multiplyToRef(parentScale, lmat);
  49039. lmat.multiplyToRef(rmat, lmat);
  49040. lmat.multiplyToRef(parentScaleInv, lmat);
  49041. }
  49042. else {
  49043. if (space == BABYLON.Space.WORLD && mesh) {
  49044. parentScale.copyFrom(mesh.getWorldMatrix());
  49045. parentScaleInv.copyFrom(parentScale);
  49046. parentScaleInv.invert();
  49047. lmat.multiplyToRef(parentScale, lmat);
  49048. lmat.multiplyToRef(rmat, lmat);
  49049. lmat.multiplyToRef(parentScaleInv, lmat);
  49050. }
  49051. else {
  49052. lmat.multiplyToRef(rmat, lmat);
  49053. }
  49054. }
  49055. lmat.m[12] = lx;
  49056. lmat.m[13] = ly;
  49057. lmat.m[14] = lz;
  49058. this.computeAbsoluteTransforms();
  49059. this.markAsDirty();
  49060. };
  49061. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  49062. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49063. if (space == BABYLON.Space.WORLD) {
  49064. var scaleMatrix = Bone._tmpMats[2];
  49065. scaleMatrix.copyFrom(this._scaleMatrix);
  49066. rotMatInv.copyFrom(this.getAbsoluteTransform());
  49067. if (mesh) {
  49068. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  49069. var meshScale = Bone._tmpMats[3];
  49070. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  49071. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  49072. }
  49073. rotMatInv.invert();
  49074. scaleMatrix.m[0] *= this._scalingDeterminant;
  49075. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  49076. }
  49077. else {
  49078. rotMatInv.copyFrom(this.getLocalMatrix());
  49079. rotMatInv.invert();
  49080. var scaleMatrix = Bone._tmpMats[2];
  49081. scaleMatrix.copyFrom(this._scaleMatrix);
  49082. if (this._parent) {
  49083. var pscaleMatrix = Bone._tmpMats[3];
  49084. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  49085. pscaleMatrix.invert();
  49086. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  49087. }
  49088. else {
  49089. scaleMatrix.m[0] *= this._scalingDeterminant;
  49090. }
  49091. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  49092. }
  49093. };
  49094. /**
  49095. * Get the scale of the bone
  49096. * @returns the scale of the bone
  49097. */
  49098. Bone.prototype.getScale = function () {
  49099. return this._scaleVector.clone();
  49100. };
  49101. /**
  49102. * Copy the scale of the bone to a vector3.
  49103. * @param result The vector3 to copy the scale to
  49104. */
  49105. Bone.prototype.getScaleToRef = function (result) {
  49106. result.copyFrom(this._scaleVector);
  49107. };
  49108. /**
  49109. * Get the position of the bone in local or world space.
  49110. * @param space The space that the returned position is in.
  49111. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49112. * @returns The position of the bone
  49113. */
  49114. Bone.prototype.getPosition = function (space, mesh) {
  49115. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49116. var pos = BABYLON.Vector3.Zero();
  49117. this.getPositionToRef(space, mesh, pos);
  49118. return pos;
  49119. };
  49120. /**
  49121. * Copy the position of the bone to a vector3 in local or world space.
  49122. * @param space The space that the returned position is in.
  49123. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49124. * @param result The vector3 to copy the position to.
  49125. */
  49126. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  49127. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49128. if (space == BABYLON.Space.LOCAL) {
  49129. var lm = this.getLocalMatrix();
  49130. result.x = lm.m[12];
  49131. result.y = lm.m[13];
  49132. result.z = lm.m[14];
  49133. }
  49134. else {
  49135. var wm;
  49136. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49137. if (mesh) {
  49138. wm = mesh.getWorldMatrix();
  49139. }
  49140. this._skeleton.computeAbsoluteTransforms();
  49141. var tmat = Bone._tmpMats[0];
  49142. if (mesh) {
  49143. tmat.copyFrom(this.getAbsoluteTransform());
  49144. tmat.multiplyToRef(wm, tmat);
  49145. }
  49146. else {
  49147. tmat = this.getAbsoluteTransform();
  49148. }
  49149. result.x = tmat.m[12];
  49150. result.y = tmat.m[13];
  49151. result.z = tmat.m[14];
  49152. }
  49153. };
  49154. /**
  49155. * Get the absolute position of the bone (world space).
  49156. * @param mesh The mesh that this bone is attached to.
  49157. * @returns The absolute position of the bone
  49158. */
  49159. Bone.prototype.getAbsolutePosition = function (mesh) {
  49160. var pos = BABYLON.Vector3.Zero();
  49161. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  49162. return pos;
  49163. };
  49164. /**
  49165. * Copy the absolute position of the bone (world space) to the result param.
  49166. * @param mesh The mesh that this bone is attached to.
  49167. * @param result The vector3 to copy the absolute position to.
  49168. */
  49169. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  49170. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  49171. };
  49172. /**
  49173. * Compute the absolute transforms of this bone and its children.
  49174. */
  49175. Bone.prototype.computeAbsoluteTransforms = function () {
  49176. if (this._parent) {
  49177. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  49178. }
  49179. else {
  49180. this._absoluteTransform.copyFrom(this._localMatrix);
  49181. var poseMatrix = this._skeleton.getPoseMatrix();
  49182. if (poseMatrix) {
  49183. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  49184. }
  49185. }
  49186. var children = this.children;
  49187. var len = children.length;
  49188. for (var i = 0; i < len; i++) {
  49189. children[i].computeAbsoluteTransforms();
  49190. }
  49191. };
  49192. Bone.prototype._syncScaleVector = function () {
  49193. var lm = this.getLocalMatrix();
  49194. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  49195. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  49196. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  49197. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  49198. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  49199. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  49200. this._scaleVector.x = xs * Math.sqrt(xsq);
  49201. this._scaleVector.y = ys * Math.sqrt(ysq);
  49202. this._scaleVector.z = zs * Math.sqrt(zsq);
  49203. if (this._parent) {
  49204. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  49205. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  49206. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  49207. }
  49208. 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);
  49209. };
  49210. /**
  49211. * Get the world direction from an axis that is in the local space of the bone.
  49212. * @param localAxis The local direction that is used to compute the world direction.
  49213. * @param mesh The mesh that this bone is attached to.
  49214. * @returns The world direction
  49215. */
  49216. Bone.prototype.getDirection = function (localAxis, mesh) {
  49217. var result = BABYLON.Vector3.Zero();
  49218. this.getDirectionToRef(localAxis, mesh, result);
  49219. return result;
  49220. };
  49221. /**
  49222. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  49223. * @param localAxis The local direction that is used to compute the world direction.
  49224. * @param mesh The mesh that this bone is attached to.
  49225. * @param result The vector3 that the world direction will be copied to.
  49226. */
  49227. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  49228. var wm;
  49229. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49230. if (mesh) {
  49231. wm = mesh.getWorldMatrix();
  49232. }
  49233. this._skeleton.computeAbsoluteTransforms();
  49234. var mat = Bone._tmpMats[0];
  49235. mat.copyFrom(this.getAbsoluteTransform());
  49236. if (mesh) {
  49237. mat.multiplyToRef(wm, mat);
  49238. }
  49239. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  49240. result.normalize();
  49241. };
  49242. /**
  49243. * Get the euler rotation of the bone in local or world space.
  49244. * @param space The space that the rotation should be in.
  49245. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49246. * @returns The euler rotation
  49247. */
  49248. Bone.prototype.getRotation = function (space, mesh) {
  49249. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49250. var result = BABYLON.Vector3.Zero();
  49251. this.getRotationToRef(space, mesh, result);
  49252. return result;
  49253. };
  49254. /**
  49255. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  49256. * @param space The space that the rotation should be in.
  49257. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49258. * @param result The vector3 that the rotation should be copied to.
  49259. */
  49260. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  49261. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49262. var quat = Bone._tmpQuat;
  49263. this.getRotationQuaternionToRef(space, mesh, quat);
  49264. quat.toEulerAnglesToRef(result);
  49265. };
  49266. /**
  49267. * Get the quaternion rotation of the bone in either local or world space.
  49268. * @param space The space that the rotation should be in.
  49269. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49270. * @returns The quaternion rotation
  49271. */
  49272. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  49273. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49274. var result = BABYLON.Quaternion.Identity();
  49275. this.getRotationQuaternionToRef(space, mesh, result);
  49276. return result;
  49277. };
  49278. /**
  49279. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  49280. * @param space The space that the rotation should be in.
  49281. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49282. * @param result The quaternion that the rotation should be copied to.
  49283. */
  49284. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  49285. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49286. if (space == BABYLON.Space.LOCAL) {
  49287. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  49288. }
  49289. else {
  49290. var mat = Bone._tmpMats[0];
  49291. var amat = this.getAbsoluteTransform();
  49292. if (mesh) {
  49293. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  49294. }
  49295. else {
  49296. mat.copyFrom(amat);
  49297. }
  49298. mat.m[0] *= this._scalingDeterminant;
  49299. mat.m[1] *= this._scalingDeterminant;
  49300. mat.m[2] *= this._scalingDeterminant;
  49301. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  49302. }
  49303. };
  49304. /**
  49305. * Get the rotation matrix of the bone in local or world space.
  49306. * @param space The space that the rotation should be in.
  49307. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49308. * @returns The rotation matrix
  49309. */
  49310. Bone.prototype.getRotationMatrix = function (space, mesh) {
  49311. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49312. var result = BABYLON.Matrix.Identity();
  49313. this.getRotationMatrixToRef(space, mesh, result);
  49314. return result;
  49315. };
  49316. /**
  49317. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  49318. * @param space The space that the rotation should be in.
  49319. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  49320. * @param result The quaternion that the rotation should be copied to.
  49321. */
  49322. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  49323. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  49324. if (space == BABYLON.Space.LOCAL) {
  49325. this.getLocalMatrix().getRotationMatrixToRef(result);
  49326. }
  49327. else {
  49328. var mat = Bone._tmpMats[0];
  49329. var amat = this.getAbsoluteTransform();
  49330. if (mesh) {
  49331. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  49332. }
  49333. else {
  49334. mat.copyFrom(amat);
  49335. }
  49336. mat.m[0] *= this._scalingDeterminant;
  49337. mat.m[1] *= this._scalingDeterminant;
  49338. mat.m[2] *= this._scalingDeterminant;
  49339. mat.getRotationMatrixToRef(result);
  49340. }
  49341. };
  49342. /**
  49343. * Get the world position of a point that is in the local space of the bone.
  49344. * @param position The local position
  49345. * @param mesh The mesh that this bone is attached to.
  49346. * @returns The world position
  49347. */
  49348. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  49349. var result = BABYLON.Vector3.Zero();
  49350. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  49351. return result;
  49352. };
  49353. /**
  49354. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  49355. * @param position The local position
  49356. * @param mesh The mesh that this bone is attached to.
  49357. * @param result The vector3 that the world position should be copied to.
  49358. */
  49359. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  49360. var wm;
  49361. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49362. if (mesh) {
  49363. wm = mesh.getWorldMatrix();
  49364. }
  49365. this._skeleton.computeAbsoluteTransforms();
  49366. var tmat = Bone._tmpMats[0];
  49367. if (mesh) {
  49368. tmat.copyFrom(this.getAbsoluteTransform());
  49369. tmat.multiplyToRef(wm, tmat);
  49370. }
  49371. else {
  49372. tmat = this.getAbsoluteTransform();
  49373. }
  49374. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  49375. };
  49376. /**
  49377. * Get the local position of a point that is in world space.
  49378. * @param position The world position
  49379. * @param mesh The mesh that this bone is attached to.
  49380. * @returns The local position
  49381. */
  49382. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  49383. var result = BABYLON.Vector3.Zero();
  49384. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  49385. return result;
  49386. };
  49387. /**
  49388. * Get the local position of a point that is in world space and copy it to the result param.
  49389. * @param position The world position
  49390. * @param mesh The mesh that this bone is attached to.
  49391. * @param result The vector3 that the local position should be copied to.
  49392. */
  49393. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  49394. var wm;
  49395. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  49396. if (mesh) {
  49397. wm = mesh.getWorldMatrix();
  49398. }
  49399. this._skeleton.computeAbsoluteTransforms();
  49400. var tmat = Bone._tmpMats[0];
  49401. tmat.copyFrom(this.getAbsoluteTransform());
  49402. if (mesh) {
  49403. tmat.multiplyToRef(wm, tmat);
  49404. }
  49405. tmat.invert();
  49406. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  49407. };
  49408. return Bone;
  49409. }(BABYLON.Node));
  49410. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  49411. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  49412. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  49413. BABYLON.Bone = Bone;
  49414. })(BABYLON || (BABYLON = {}));
  49415. //# sourceMappingURL=babylon.bone.js.map
  49416. var BABYLON;
  49417. (function (BABYLON) {
  49418. var BoneIKController = (function () {
  49419. function BoneIKController(mesh, bone, options) {
  49420. this.targetPosition = BABYLON.Vector3.Zero();
  49421. this.poleTargetPosition = BABYLON.Vector3.Zero();
  49422. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  49423. this.poleAngle = 0;
  49424. this.slerpAmount = 1;
  49425. this._bone1Quat = BABYLON.Quaternion.Identity();
  49426. this._bone1Mat = BABYLON.Matrix.Identity();
  49427. this._bone2Ang = Math.PI;
  49428. this._maxAngle = Math.PI;
  49429. this._rightHandedSystem = false;
  49430. this._bendAxis = BABYLON.Vector3.Right();
  49431. this._slerping = false;
  49432. this._adjustRoll = 0;
  49433. this._bone2 = bone;
  49434. this._bone1 = bone.getParent();
  49435. this.mesh = mesh;
  49436. var bonePos = bone.getPosition();
  49437. if (bone.getAbsoluteTransform().determinant() > 0) {
  49438. this._rightHandedSystem = true;
  49439. this._bendAxis.x = 0;
  49440. this._bendAxis.y = 0;
  49441. this._bendAxis.z = -1;
  49442. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  49443. this._adjustRoll = Math.PI * .5;
  49444. this._bendAxis.z = 1;
  49445. }
  49446. }
  49447. if (this._bone1.length) {
  49448. var boneScale1 = this._bone1.getScale();
  49449. var boneScale2 = this._bone2.getScale();
  49450. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  49451. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  49452. }
  49453. else if (this._bone1.children[0]) {
  49454. mesh.computeWorldMatrix(true);
  49455. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  49456. var pos2 = this._bone2.getAbsolutePosition(mesh);
  49457. var pos3 = this._bone1.getAbsolutePosition(mesh);
  49458. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  49459. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  49460. }
  49461. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  49462. this.maxAngle = Math.PI;
  49463. if (options) {
  49464. if (options.targetMesh) {
  49465. this.targetMesh = options.targetMesh;
  49466. this.targetMesh.computeWorldMatrix(true);
  49467. }
  49468. if (options.poleTargetMesh) {
  49469. this.poleTargetMesh = options.poleTargetMesh;
  49470. this.poleTargetMesh.computeWorldMatrix(true);
  49471. }
  49472. else if (options.poleTargetBone) {
  49473. this.poleTargetBone = options.poleTargetBone;
  49474. }
  49475. else if (this._bone1.getParent()) {
  49476. this.poleTargetBone = this._bone1.getParent();
  49477. }
  49478. if (options.poleTargetLocalOffset) {
  49479. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  49480. }
  49481. if (options.poleAngle) {
  49482. this.poleAngle = options.poleAngle;
  49483. }
  49484. if (options.bendAxis) {
  49485. this._bendAxis.copyFrom(options.bendAxis);
  49486. }
  49487. if (options.maxAngle) {
  49488. this.maxAngle = options.maxAngle;
  49489. }
  49490. if (options.slerpAmount) {
  49491. this.slerpAmount = options.slerpAmount;
  49492. }
  49493. }
  49494. }
  49495. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  49496. get: function () {
  49497. return this._maxAngle;
  49498. },
  49499. set: function (value) {
  49500. this._setMaxAngle(value);
  49501. },
  49502. enumerable: true,
  49503. configurable: true
  49504. });
  49505. BoneIKController.prototype._setMaxAngle = function (ang) {
  49506. if (ang < 0) {
  49507. ang = 0;
  49508. }
  49509. if (ang > Math.PI || ang == undefined) {
  49510. ang = Math.PI;
  49511. }
  49512. this._maxAngle = ang;
  49513. var a = this._bone1Length;
  49514. var b = this._bone2Length;
  49515. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  49516. };
  49517. BoneIKController.prototype.update = function () {
  49518. var bone1 = this._bone1;
  49519. var target = this.targetPosition;
  49520. var poleTarget = this.poleTargetPosition;
  49521. var mat1 = BoneIKController._tmpMats[0];
  49522. var mat2 = BoneIKController._tmpMats[1];
  49523. if (this.targetMesh) {
  49524. target.copyFrom(this.targetMesh.getAbsolutePosition());
  49525. }
  49526. if (this.poleTargetBone) {
  49527. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  49528. }
  49529. else if (this.poleTargetMesh) {
  49530. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  49531. }
  49532. var bonePos = BoneIKController._tmpVecs[0];
  49533. var zaxis = BoneIKController._tmpVecs[1];
  49534. var xaxis = BoneIKController._tmpVecs[2];
  49535. var yaxis = BoneIKController._tmpVecs[3];
  49536. var upAxis = BoneIKController._tmpVecs[4];
  49537. var _tmpQuat = BoneIKController._tmpQuat;
  49538. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  49539. poleTarget.subtractToRef(bonePos, upAxis);
  49540. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  49541. upAxis.y = 1;
  49542. }
  49543. else {
  49544. upAxis.normalize();
  49545. }
  49546. target.subtractToRef(bonePos, yaxis);
  49547. yaxis.normalize();
  49548. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  49549. zaxis.normalize();
  49550. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  49551. xaxis.normalize();
  49552. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  49553. var a = this._bone1Length;
  49554. var b = this._bone2Length;
  49555. var c = BABYLON.Vector3.Distance(bonePos, target);
  49556. if (this._maxReach > 0) {
  49557. c = Math.min(this._maxReach, c);
  49558. }
  49559. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  49560. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  49561. if (acosa > 1) {
  49562. acosa = 1;
  49563. }
  49564. if (acosb > 1) {
  49565. acosb = 1;
  49566. }
  49567. if (acosa < -1) {
  49568. acosa = -1;
  49569. }
  49570. if (acosb < -1) {
  49571. acosb = -1;
  49572. }
  49573. var angA = Math.acos(acosa);
  49574. var angB = Math.acos(acosb);
  49575. var angC = -angA - angB;
  49576. if (this._rightHandedSystem) {
  49577. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  49578. mat2.multiplyToRef(mat1, mat1);
  49579. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  49580. mat2.multiplyToRef(mat1, mat1);
  49581. }
  49582. else {
  49583. var _tmpVec = BoneIKController._tmpVecs[5];
  49584. _tmpVec.copyFrom(this._bendAxis);
  49585. _tmpVec.x *= -1;
  49586. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  49587. mat2.multiplyToRef(mat1, mat1);
  49588. }
  49589. if (this.poleAngle) {
  49590. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  49591. mat1.multiplyToRef(mat2, mat1);
  49592. }
  49593. if (this.slerpAmount < 1) {
  49594. if (!this._slerping) {
  49595. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  49596. }
  49597. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  49598. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  49599. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  49600. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  49601. this._slerping = true;
  49602. }
  49603. else {
  49604. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  49605. this._bone1Mat.copyFrom(mat1);
  49606. this._slerping = false;
  49607. }
  49608. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  49609. this._bone2Ang = angC;
  49610. };
  49611. return BoneIKController;
  49612. }());
  49613. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  49614. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  49615. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  49616. BABYLON.BoneIKController = BoneIKController;
  49617. })(BABYLON || (BABYLON = {}));
  49618. //# sourceMappingURL=babylon.boneIKController.js.map
  49619. var BABYLON;
  49620. (function (BABYLON) {
  49621. var BoneLookController = (function () {
  49622. /**
  49623. * Create a BoneLookController
  49624. * @param mesh the mesh that the bone belongs to
  49625. * @param bone the bone that will be looking to the target
  49626. * @param target the target Vector3 to look at
  49627. * @param settings optional settings:
  49628. * - maxYaw: the maximum angle the bone will yaw to
  49629. * - minYaw: the minimum angle the bone will yaw to
  49630. * - maxPitch: the maximum angle the bone will pitch to
  49631. * - minPitch: the minimum angle the bone will yaw to
  49632. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  49633. * - upAxis: the up axis of the coordinate system
  49634. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  49635. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  49636. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  49637. * - adjustYaw: used to make an adjustment to the yaw of the bone
  49638. * - adjustPitch: used to make an adjustment to the pitch of the bone
  49639. * - adjustRoll: used to make an adjustment to the roll of the bone
  49640. **/
  49641. function BoneLookController(mesh, bone, target, options) {
  49642. /**
  49643. * The up axis of the coordinate system that is used when the bone is rotated.
  49644. */
  49645. this.upAxis = BABYLON.Vector3.Up();
  49646. /**
  49647. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  49648. */
  49649. this.upAxisSpace = BABYLON.Space.LOCAL;
  49650. /**
  49651. * Used to make an adjustment to the yaw of the bone.
  49652. */
  49653. this.adjustYaw = 0;
  49654. /**
  49655. * Used to make an adjustment to the pitch of the bone.
  49656. */
  49657. this.adjustPitch = 0;
  49658. /**
  49659. * Used to make an adjustment to the roll of the bone.
  49660. */
  49661. this.adjustRoll = 0;
  49662. /**
  49663. * 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).
  49664. */
  49665. this.slerpAmount = 1;
  49666. this._boneQuat = BABYLON.Quaternion.Identity();
  49667. this._slerping = false;
  49668. this._firstFrameSkipped = false;
  49669. this._fowardAxis = BABYLON.Vector3.Forward();
  49670. this.mesh = mesh;
  49671. this.bone = bone;
  49672. this.target = target;
  49673. if (options) {
  49674. if (options.adjustYaw) {
  49675. this.adjustYaw = options.adjustYaw;
  49676. }
  49677. if (options.adjustPitch) {
  49678. this.adjustPitch = options.adjustPitch;
  49679. }
  49680. if (options.adjustRoll) {
  49681. this.adjustRoll = options.adjustRoll;
  49682. }
  49683. if (options.maxYaw != null) {
  49684. this.maxYaw = options.maxYaw;
  49685. }
  49686. else {
  49687. this.maxYaw = Math.PI;
  49688. }
  49689. if (options.minYaw != null) {
  49690. this.minYaw = options.minYaw;
  49691. }
  49692. else {
  49693. this.minYaw = -Math.PI;
  49694. }
  49695. if (options.maxPitch != null) {
  49696. this.maxPitch = options.maxPitch;
  49697. }
  49698. else {
  49699. this.maxPitch = Math.PI;
  49700. }
  49701. if (options.minPitch != null) {
  49702. this.minPitch = options.minPitch;
  49703. }
  49704. else {
  49705. this.minPitch = -Math.PI;
  49706. }
  49707. if (options.slerpAmount != null) {
  49708. this.slerpAmount = options.slerpAmount;
  49709. }
  49710. if (options.upAxis != null) {
  49711. this.upAxis = options.upAxis;
  49712. }
  49713. if (options.upAxisSpace != null) {
  49714. this.upAxisSpace = options.upAxisSpace;
  49715. }
  49716. if (options.yawAxis != null || options.pitchAxis != null) {
  49717. var newYawAxis = BABYLON.Axis.Y;
  49718. var newPitchAxis = BABYLON.Axis.X;
  49719. if (options.yawAxis != null) {
  49720. newYawAxis = options.yawAxis.clone();
  49721. newYawAxis.normalize();
  49722. }
  49723. if (options.pitchAxis != null) {
  49724. newPitchAxis = options.pitchAxis.clone();
  49725. newPitchAxis.normalize();
  49726. }
  49727. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  49728. this._transformYawPitch = BABYLON.Matrix.Identity();
  49729. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  49730. this._transformYawPitchInv = this._transformYawPitch.clone();
  49731. this._transformYawPitch.invert();
  49732. }
  49733. }
  49734. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  49735. this.upAxisSpace = BABYLON.Space.LOCAL;
  49736. }
  49737. }
  49738. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  49739. /**
  49740. * Get/set the minimum yaw angle that the bone can look to.
  49741. */
  49742. get: function () {
  49743. return this._minYaw;
  49744. },
  49745. set: function (value) {
  49746. this._minYaw = value;
  49747. this._minYawSin = Math.sin(value);
  49748. this._minYawCos = Math.cos(value);
  49749. if (this._maxYaw != null) {
  49750. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  49751. this._yawRange = this._maxYaw - this._minYaw;
  49752. }
  49753. },
  49754. enumerable: true,
  49755. configurable: true
  49756. });
  49757. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  49758. /**
  49759. * Get/set the maximum yaw angle that the bone can look to.
  49760. */
  49761. get: function () {
  49762. return this._maxYaw;
  49763. },
  49764. set: function (value) {
  49765. this._maxYaw = value;
  49766. this._maxYawSin = Math.sin(value);
  49767. this._maxYawCos = Math.cos(value);
  49768. if (this._minYaw != null) {
  49769. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  49770. this._yawRange = this._maxYaw - this._minYaw;
  49771. }
  49772. },
  49773. enumerable: true,
  49774. configurable: true
  49775. });
  49776. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  49777. /**
  49778. * Get/set the minimum pitch angle that the bone can look to.
  49779. */
  49780. get: function () {
  49781. return this._minPitch;
  49782. },
  49783. set: function (value) {
  49784. this._minPitch = value;
  49785. this._minPitchTan = Math.tan(value);
  49786. },
  49787. enumerable: true,
  49788. configurable: true
  49789. });
  49790. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  49791. /**
  49792. * Get/set the maximum pitch angle that the bone can look to.
  49793. */
  49794. get: function () {
  49795. return this._maxPitch;
  49796. },
  49797. set: function (value) {
  49798. this._maxPitch = value;
  49799. this._maxPitchTan = Math.tan(value);
  49800. },
  49801. enumerable: true,
  49802. configurable: true
  49803. });
  49804. /**
  49805. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  49806. */
  49807. BoneLookController.prototype.update = function () {
  49808. //skip the first frame when slerping so that the mesh rotation is correct
  49809. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  49810. this._firstFrameSkipped = true;
  49811. return;
  49812. }
  49813. var bone = this.bone;
  49814. var bonePos = BoneLookController._tmpVecs[0];
  49815. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  49816. var target = this.target;
  49817. var _tmpMat1 = BoneLookController._tmpMats[0];
  49818. var _tmpMat2 = BoneLookController._tmpMats[1];
  49819. var mesh = this.mesh;
  49820. var parentBone = bone.getParent();
  49821. var upAxis = BoneLookController._tmpVecs[1];
  49822. upAxis.copyFrom(this.upAxis);
  49823. if (this.upAxisSpace == BABYLON.Space.BONE) {
  49824. if (this._transformYawPitch) {
  49825. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  49826. }
  49827. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  49828. }
  49829. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  49830. mesh.getDirectionToRef(upAxis, upAxis);
  49831. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  49832. upAxis.normalize();
  49833. }
  49834. }
  49835. var checkYaw = false;
  49836. var checkPitch = false;
  49837. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  49838. checkYaw = true;
  49839. }
  49840. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  49841. checkPitch = true;
  49842. }
  49843. if (checkYaw || checkPitch) {
  49844. var spaceMat = BoneLookController._tmpMats[2];
  49845. var spaceMatInv = BoneLookController._tmpMats[3];
  49846. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  49847. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  49848. }
  49849. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  49850. spaceMat.copyFrom(mesh.getWorldMatrix());
  49851. }
  49852. else {
  49853. var forwardAxis = BoneLookController._tmpVecs[2];
  49854. forwardAxis.copyFrom(this._fowardAxis);
  49855. if (this._transformYawPitch) {
  49856. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  49857. }
  49858. if (parentBone) {
  49859. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  49860. }
  49861. else {
  49862. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  49863. }
  49864. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  49865. rightAxis.normalize();
  49866. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  49867. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  49868. }
  49869. spaceMat.invertToRef(spaceMatInv);
  49870. var xzlen;
  49871. if (checkPitch) {
  49872. var localTarget = BoneLookController._tmpVecs[3];
  49873. target.subtractToRef(bonePos, localTarget);
  49874. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  49875. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  49876. var pitch = Math.atan2(localTarget.y, xzlen);
  49877. var newPitch = pitch;
  49878. if (pitch > this._maxPitch) {
  49879. localTarget.y = this._maxPitchTan * xzlen;
  49880. newPitch = this._maxPitch;
  49881. }
  49882. else if (pitch < this._minPitch) {
  49883. localTarget.y = this._minPitchTan * xzlen;
  49884. newPitch = this._minPitch;
  49885. }
  49886. if (pitch != newPitch) {
  49887. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  49888. localTarget.addInPlace(bonePos);
  49889. target = localTarget;
  49890. }
  49891. }
  49892. if (checkYaw) {
  49893. var localTarget = BoneLookController._tmpVecs[4];
  49894. target.subtractToRef(bonePos, localTarget);
  49895. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  49896. var yaw = Math.atan2(localTarget.x, localTarget.z);
  49897. var newYaw = yaw;
  49898. if (yaw > this._maxYaw || yaw < this._minYaw) {
  49899. if (xzlen == null) {
  49900. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  49901. }
  49902. if (this._yawRange > Math.PI) {
  49903. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  49904. localTarget.z = this._maxYawCos * xzlen;
  49905. localTarget.x = this._maxYawSin * xzlen;
  49906. newYaw = this._maxYaw;
  49907. }
  49908. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  49909. localTarget.z = this._minYawCos * xzlen;
  49910. localTarget.x = this._minYawSin * xzlen;
  49911. newYaw = this._minYaw;
  49912. }
  49913. }
  49914. else {
  49915. if (yaw > this._maxYaw) {
  49916. localTarget.z = this._maxYawCos * xzlen;
  49917. localTarget.x = this._maxYawSin * xzlen;
  49918. newYaw = this._maxYaw;
  49919. }
  49920. else if (yaw < this._minYaw) {
  49921. localTarget.z = this._minYawCos * xzlen;
  49922. localTarget.x = this._minYawSin * xzlen;
  49923. newYaw = this._minYaw;
  49924. }
  49925. }
  49926. }
  49927. if (this._slerping && this._yawRange > Math.PI) {
  49928. //are we going to be crossing into the min/max region?
  49929. var boneFwd = BoneLookController._tmpVecs[8];
  49930. boneFwd.copyFrom(BABYLON.Axis.Z);
  49931. if (this._transformYawPitch) {
  49932. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  49933. }
  49934. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  49935. this._boneQuat.toRotationMatrix(boneRotMat);
  49936. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  49937. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  49938. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  49939. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  49940. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  49941. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  49942. if (angBtwTar > angBtwMidYaw) {
  49943. if (xzlen == null) {
  49944. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  49945. }
  49946. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  49947. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  49948. if (angBtwMin < angBtwMax) {
  49949. newYaw = boneYaw + Math.PI * .75;
  49950. localTarget.z = Math.cos(newYaw) * xzlen;
  49951. localTarget.x = Math.sin(newYaw) * xzlen;
  49952. }
  49953. else {
  49954. newYaw = boneYaw - Math.PI * .75;
  49955. localTarget.z = Math.cos(newYaw) * xzlen;
  49956. localTarget.x = Math.sin(newYaw) * xzlen;
  49957. }
  49958. }
  49959. }
  49960. if (yaw != newYaw) {
  49961. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  49962. localTarget.addInPlace(bonePos);
  49963. target = localTarget;
  49964. }
  49965. }
  49966. }
  49967. var zaxis = BoneLookController._tmpVecs[5];
  49968. var xaxis = BoneLookController._tmpVecs[6];
  49969. var yaxis = BoneLookController._tmpVecs[7];
  49970. var _tmpQuat = BoneLookController._tmpQuat;
  49971. target.subtractToRef(bonePos, zaxis);
  49972. zaxis.normalize();
  49973. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  49974. xaxis.normalize();
  49975. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  49976. yaxis.normalize();
  49977. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  49978. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  49979. return;
  49980. }
  49981. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  49982. return;
  49983. }
  49984. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  49985. return;
  49986. }
  49987. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  49988. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  49989. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  49990. }
  49991. if (this.slerpAmount < 1) {
  49992. if (!this._slerping) {
  49993. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  49994. }
  49995. if (this._transformYawPitch) {
  49996. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  49997. }
  49998. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  49999. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  50000. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  50001. this._slerping = true;
  50002. }
  50003. else {
  50004. if (this._transformYawPitch) {
  50005. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  50006. }
  50007. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  50008. this._slerping = false;
  50009. }
  50010. };
  50011. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  50012. var angDiff = ang2 - ang1;
  50013. angDiff %= Math.PI * 2;
  50014. if (angDiff > Math.PI) {
  50015. angDiff -= Math.PI * 2;
  50016. }
  50017. else if (angDiff < -Math.PI) {
  50018. angDiff += Math.PI * 2;
  50019. }
  50020. return angDiff;
  50021. };
  50022. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  50023. ang1 %= (2 * Math.PI);
  50024. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  50025. ang2 %= (2 * Math.PI);
  50026. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  50027. var ab = 0;
  50028. if (ang1 < ang2) {
  50029. ab = ang2 - ang1;
  50030. }
  50031. else {
  50032. ab = ang1 - ang2;
  50033. }
  50034. if (ab > Math.PI) {
  50035. ab = Math.PI * 2 - ab;
  50036. }
  50037. return ab;
  50038. };
  50039. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  50040. ang %= (2 * Math.PI);
  50041. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  50042. ang1 %= (2 * Math.PI);
  50043. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  50044. ang2 %= (2 * Math.PI);
  50045. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  50046. if (ang1 < ang2) {
  50047. if (ang > ang1 && ang < ang2) {
  50048. return true;
  50049. }
  50050. }
  50051. else {
  50052. if (ang > ang2 && ang < ang1) {
  50053. return true;
  50054. }
  50055. }
  50056. return false;
  50057. };
  50058. return BoneLookController;
  50059. }());
  50060. 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()];
  50061. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  50062. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  50063. BABYLON.BoneLookController = BoneLookController;
  50064. })(BABYLON || (BABYLON = {}));
  50065. //# sourceMappingURL=babylon.boneLookController.js.map
  50066. var BABYLON;
  50067. (function (BABYLON) {
  50068. var Skeleton = (function () {
  50069. function Skeleton(name, id, scene) {
  50070. this.name = name;
  50071. this.id = id;
  50072. this.bones = new Array();
  50073. this.needInitialSkinMatrix = false;
  50074. this._isDirty = true;
  50075. this._meshesWithPoseMatrix = new Array();
  50076. this._identity = BABYLON.Matrix.Identity();
  50077. this._ranges = {};
  50078. this._lastAbsoluteTransformsUpdateId = -1;
  50079. // Events
  50080. /**
  50081. * An event triggered before computing the skeleton's matrices
  50082. * @type {BABYLON.Observable}
  50083. */
  50084. this.onBeforeComputeObservable = new BABYLON.Observable();
  50085. this.bones = [];
  50086. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50087. scene.skeletons.push(this);
  50088. //make sure it will recalculate the matrix next time prepare is called.
  50089. this._isDirty = true;
  50090. }
  50091. // Members
  50092. Skeleton.prototype.getTransformMatrices = function (mesh) {
  50093. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  50094. return mesh._bonesTransformMatrices;
  50095. }
  50096. if (!this._transformMatrices) {
  50097. this.prepare();
  50098. }
  50099. return this._transformMatrices;
  50100. };
  50101. Skeleton.prototype.getScene = function () {
  50102. return this._scene;
  50103. };
  50104. // Methods
  50105. /**
  50106. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  50107. */
  50108. Skeleton.prototype.toString = function (fullDetails) {
  50109. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  50110. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50111. if (fullDetails) {
  50112. ret += ", Ranges: {";
  50113. var first = true;
  50114. for (var name_1 in this._ranges) {
  50115. if (first) {
  50116. ret += ", ";
  50117. first = false;
  50118. }
  50119. ret += name_1;
  50120. }
  50121. ret += "}";
  50122. }
  50123. return ret;
  50124. };
  50125. /**
  50126. * Get bone's index searching by name
  50127. * @param {string} name is bone's name to search for
  50128. * @return {number} Indice of the bone. Returns -1 if not found
  50129. */
  50130. Skeleton.prototype.getBoneIndexByName = function (name) {
  50131. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  50132. if (this.bones[boneIndex].name === name) {
  50133. return boneIndex;
  50134. }
  50135. }
  50136. return -1;
  50137. };
  50138. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  50139. // check name not already in use
  50140. if (!this._ranges[name]) {
  50141. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  50142. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  50143. if (this.bones[i].animations[0]) {
  50144. this.bones[i].animations[0].createRange(name, from, to);
  50145. }
  50146. }
  50147. }
  50148. };
  50149. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  50150. if (deleteFrames === void 0) { deleteFrames = true; }
  50151. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  50152. if (this.bones[i].animations[0]) {
  50153. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  50154. }
  50155. }
  50156. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  50157. };
  50158. Skeleton.prototype.getAnimationRange = function (name) {
  50159. return this._ranges[name];
  50160. };
  50161. /**
  50162. * Returns as an Array, all AnimationRanges defined on this skeleton
  50163. */
  50164. Skeleton.prototype.getAnimationRanges = function () {
  50165. var animationRanges = [];
  50166. var name;
  50167. var i = 0;
  50168. for (name in this._ranges) {
  50169. animationRanges[i] = this._ranges[name];
  50170. i++;
  50171. }
  50172. return animationRanges;
  50173. };
  50174. /**
  50175. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  50176. */
  50177. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  50178. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  50179. if (this._ranges[name] || !source.getAnimationRange(name)) {
  50180. return false;
  50181. }
  50182. var ret = true;
  50183. var frameOffset = this._getHighestAnimationFrame() + 1;
  50184. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  50185. var boneDict = {};
  50186. var sourceBones = source.bones;
  50187. var nBones;
  50188. var i;
  50189. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  50190. boneDict[sourceBones[i].name] = sourceBones[i];
  50191. }
  50192. if (this.bones.length !== sourceBones.length) {
  50193. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  50194. ret = false;
  50195. }
  50196. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  50197. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  50198. var boneName = this.bones[i].name;
  50199. var sourceBone = boneDict[boneName];
  50200. if (sourceBone) {
  50201. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  50202. }
  50203. else {
  50204. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  50205. ret = false;
  50206. }
  50207. }
  50208. // do not call createAnimationRange(), since it also is done to bones, which was already done
  50209. var range = source.getAnimationRange(name);
  50210. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  50211. return ret;
  50212. };
  50213. Skeleton.prototype.returnToRest = function () {
  50214. for (var index = 0; index < this.bones.length; index++) {
  50215. this.bones[index].returnToRest();
  50216. }
  50217. };
  50218. Skeleton.prototype._getHighestAnimationFrame = function () {
  50219. var ret = 0;
  50220. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  50221. if (this.bones[i].animations[0]) {
  50222. var highest = this.bones[i].animations[0].getHighestFrame();
  50223. if (ret < highest) {
  50224. ret = highest;
  50225. }
  50226. }
  50227. }
  50228. return ret;
  50229. };
  50230. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  50231. var range = this.getAnimationRange(name);
  50232. if (!range) {
  50233. return null;
  50234. }
  50235. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  50236. };
  50237. Skeleton.prototype._markAsDirty = function () {
  50238. this._isDirty = true;
  50239. };
  50240. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  50241. this._meshesWithPoseMatrix.push(mesh);
  50242. };
  50243. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  50244. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  50245. if (index > -1) {
  50246. this._meshesWithPoseMatrix.splice(index, 1);
  50247. }
  50248. };
  50249. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  50250. this.onBeforeComputeObservable.notifyObservers(this);
  50251. for (var index = 0; index < this.bones.length; index++) {
  50252. var bone = this.bones[index];
  50253. var parentBone = bone.getParent();
  50254. if (parentBone) {
  50255. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  50256. }
  50257. else {
  50258. if (initialSkinMatrix) {
  50259. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  50260. }
  50261. else {
  50262. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  50263. }
  50264. }
  50265. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  50266. }
  50267. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  50268. };
  50269. Skeleton.prototype.prepare = function () {
  50270. if (!this._isDirty) {
  50271. return;
  50272. }
  50273. if (this.needInitialSkinMatrix) {
  50274. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  50275. var mesh = this._meshesWithPoseMatrix[index];
  50276. var poseMatrix = mesh.getPoseMatrix();
  50277. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  50278. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  50279. }
  50280. if (this._synchronizedWithMesh !== mesh) {
  50281. this._synchronizedWithMesh = mesh;
  50282. // Prepare bones
  50283. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  50284. var bone = this.bones[boneIndex];
  50285. if (!bone.getParent()) {
  50286. var matrix = bone.getBaseMatrix();
  50287. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  50288. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  50289. }
  50290. }
  50291. }
  50292. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  50293. }
  50294. }
  50295. else {
  50296. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  50297. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  50298. }
  50299. this._computeTransformMatrices(this._transformMatrices, null);
  50300. }
  50301. this._isDirty = false;
  50302. this._scene._activeBones.addCount(this.bones.length, false);
  50303. };
  50304. Skeleton.prototype.getAnimatables = function () {
  50305. if (!this._animatables || this._animatables.length !== this.bones.length) {
  50306. this._animatables = [];
  50307. for (var index = 0; index < this.bones.length; index++) {
  50308. this._animatables.push(this.bones[index]);
  50309. }
  50310. }
  50311. return this._animatables;
  50312. };
  50313. Skeleton.prototype.clone = function (name, id) {
  50314. var result = new Skeleton(name, id || name, this._scene);
  50315. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  50316. for (var index = 0; index < this.bones.length; index++) {
  50317. var source = this.bones[index];
  50318. var parentBone = null;
  50319. if (source.getParent()) {
  50320. var parentIndex = this.bones.indexOf(source.getParent());
  50321. parentBone = result.bones[parentIndex];
  50322. }
  50323. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  50324. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  50325. }
  50326. if (this._ranges) {
  50327. result._ranges = {};
  50328. for (var rangeName in this._ranges) {
  50329. result._ranges[rangeName] = this._ranges[rangeName].clone();
  50330. }
  50331. }
  50332. this._isDirty = true;
  50333. return result;
  50334. };
  50335. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  50336. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  50337. this.bones.forEach(function (bone) {
  50338. bone.animations.forEach(function (animation) {
  50339. animation.enableBlending = true;
  50340. animation.blendingSpeed = blendingSpeed;
  50341. });
  50342. });
  50343. };
  50344. Skeleton.prototype.dispose = function () {
  50345. this._meshesWithPoseMatrix = [];
  50346. // Animations
  50347. this.getScene().stopAnimation(this);
  50348. // Remove from scene
  50349. this.getScene().removeSkeleton(this);
  50350. };
  50351. Skeleton.prototype.serialize = function () {
  50352. var serializationObject = {};
  50353. serializationObject.name = this.name;
  50354. serializationObject.id = this.id;
  50355. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  50356. serializationObject.bones = [];
  50357. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  50358. for (var index = 0; index < this.bones.length; index++) {
  50359. var bone = this.bones[index];
  50360. var serializedBone = {
  50361. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  50362. name: bone.name,
  50363. matrix: bone.getBaseMatrix().toArray(),
  50364. rest: bone.getRestPose().toArray()
  50365. };
  50366. serializationObject.bones.push(serializedBone);
  50367. if (bone.length) {
  50368. serializedBone.length = bone.length;
  50369. }
  50370. if (bone.animations && bone.animations.length > 0) {
  50371. serializedBone.animation = bone.animations[0].serialize();
  50372. }
  50373. serializationObject.ranges = [];
  50374. for (var name in this._ranges) {
  50375. var range = {};
  50376. range.name = name;
  50377. range.from = this._ranges[name].from;
  50378. range.to = this._ranges[name].to;
  50379. serializationObject.ranges.push(range);
  50380. }
  50381. }
  50382. return serializationObject;
  50383. };
  50384. Skeleton.Parse = function (parsedSkeleton, scene) {
  50385. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  50386. if (parsedSkeleton.dimensionsAtRest) {
  50387. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  50388. }
  50389. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  50390. var index;
  50391. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  50392. var parsedBone = parsedSkeleton.bones[index];
  50393. var parentBone = null;
  50394. if (parsedBone.parentBoneIndex > -1) {
  50395. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  50396. }
  50397. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  50398. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  50399. if (parsedBone.length) {
  50400. bone.length = parsedBone.length;
  50401. }
  50402. if (parsedBone.animation) {
  50403. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  50404. }
  50405. }
  50406. // placed after bones, so createAnimationRange can cascade down
  50407. if (parsedSkeleton.ranges) {
  50408. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  50409. var data = parsedSkeleton.ranges[index];
  50410. skeleton.createAnimationRange(data.name, data.from, data.to);
  50411. }
  50412. }
  50413. return skeleton;
  50414. };
  50415. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  50416. if (forceUpdate === void 0) { forceUpdate = false; }
  50417. var renderId = this._scene.getRenderId();
  50418. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  50419. this.bones[0].computeAbsoluteTransforms();
  50420. this._lastAbsoluteTransformsUpdateId = renderId;
  50421. }
  50422. };
  50423. Skeleton.prototype.getPoseMatrix = function () {
  50424. var poseMatrix;
  50425. if (this._meshesWithPoseMatrix.length > 0) {
  50426. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  50427. }
  50428. return poseMatrix;
  50429. };
  50430. return Skeleton;
  50431. }());
  50432. BABYLON.Skeleton = Skeleton;
  50433. })(BABYLON || (BABYLON = {}));
  50434. //# sourceMappingURL=babylon.skeleton.js.map
  50435. var BABYLON;
  50436. (function (BABYLON) {
  50437. var Internals;
  50438. (function (Internals) {
  50439. var FileFaceOrientation = (function () {
  50440. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  50441. this.name = name;
  50442. this.worldAxisForNormal = worldAxisForNormal;
  50443. this.worldAxisForFileX = worldAxisForFileX;
  50444. this.worldAxisForFileY = worldAxisForFileY;
  50445. }
  50446. return FileFaceOrientation;
  50447. }());
  50448. ;
  50449. /**
  50450. * Helper class dealing with the extraction of spherical polynomial dataArray
  50451. * from a cube map.
  50452. */
  50453. var CubeMapToSphericalPolynomialTools = (function () {
  50454. function CubeMapToSphericalPolynomialTools() {
  50455. }
  50456. /**
  50457. * Converts a cubemap to the according Spherical Polynomial data.
  50458. * This extracts the first 3 orders only as they are the only one used in the lighting.
  50459. *
  50460. * @param cubeInfo The Cube map to extract the information from.
  50461. * @return The Spherical Polynomial data.
  50462. */
  50463. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  50464. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  50465. var totalSolidAngle = 0.0;
  50466. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  50467. var du = 2.0 / cubeInfo.size;
  50468. var dv = du;
  50469. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  50470. var minUV = du * 0.5 - 1.0;
  50471. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50472. var fileFace = this.FileFaces[faceIndex];
  50473. var dataArray = cubeInfo[fileFace.name];
  50474. var v = minUV;
  50475. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  50476. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  50477. // Because SP is still linear, so summation is fine in that basis.
  50478. for (var y = 0; y < cubeInfo.size; y++) {
  50479. var u = minUV;
  50480. for (var x = 0; x < cubeInfo.size; x++) {
  50481. // World direction (not normalised)
  50482. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  50483. worldDirection.normalize();
  50484. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  50485. if (1) {
  50486. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  50487. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  50488. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  50489. var color = new BABYLON.Color3(r, g, b);
  50490. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50491. }
  50492. else {
  50493. if (faceIndex == 0) {
  50494. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50495. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50496. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50497. }
  50498. else if (faceIndex == 1) {
  50499. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50500. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50501. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50502. }
  50503. else if (faceIndex == 2) {
  50504. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50505. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50506. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50507. }
  50508. else if (faceIndex == 3) {
  50509. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50510. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50511. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50512. }
  50513. else if (faceIndex == 4) {
  50514. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50515. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50516. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50517. }
  50518. else if (faceIndex == 5) {
  50519. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50520. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50521. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50522. }
  50523. 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]);
  50524. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50525. }
  50526. totalSolidAngle += deltaSolidAngle;
  50527. u += du;
  50528. }
  50529. v += dv;
  50530. }
  50531. }
  50532. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  50533. var correction = correctSolidAngle / totalSolidAngle;
  50534. sphericalHarmonics.scale(correction);
  50535. // Additionally scale by pi -- audit needed
  50536. sphericalHarmonics.scale(1.0 / Math.PI);
  50537. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  50538. };
  50539. return CubeMapToSphericalPolynomialTools;
  50540. }());
  50541. CubeMapToSphericalPolynomialTools.FileFaces = [
  50542. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  50543. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  50544. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  50545. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  50546. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  50547. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  50548. ];
  50549. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  50550. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50551. })(BABYLON || (BABYLON = {}));
  50552. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  50553. var BABYLON;
  50554. (function (BABYLON) {
  50555. var Internals;
  50556. (function (Internals) {
  50557. /**
  50558. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  50559. */
  50560. var PanoramaToCubeMapTools = (function () {
  50561. function PanoramaToCubeMapTools() {
  50562. }
  50563. /**
  50564. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  50565. *
  50566. * @param float32Array The source data.
  50567. * @param inputWidth The width of the input panorama.
  50568. * @param inputhHeight The height of the input panorama.
  50569. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  50570. * @return The cubemap data
  50571. */
  50572. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  50573. if (!float32Array) {
  50574. throw "ConvertPanoramaToCubemap: input cannot be null";
  50575. }
  50576. if (float32Array.length != inputWidth * inputHeight * 3) {
  50577. throw "ConvertPanoramaToCubemap: input size is wrong";
  50578. }
  50579. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  50580. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  50581. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  50582. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  50583. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  50584. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  50585. return {
  50586. front: textureFront,
  50587. back: textureBack,
  50588. left: textureLeft,
  50589. right: textureRight,
  50590. up: textureUp,
  50591. down: textureDown,
  50592. size: size
  50593. };
  50594. };
  50595. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  50596. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  50597. var textureArray = new Float32Array(buffer);
  50598. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  50599. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  50600. var dy = 1 / texSize;
  50601. var fy = 0;
  50602. for (var y = 0; y < texSize; y++) {
  50603. var xv1 = faceData[0];
  50604. var xv2 = faceData[2];
  50605. for (var x = 0; x < texSize; x++) {
  50606. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  50607. v.normalize();
  50608. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  50609. // 3 channels per pixels
  50610. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  50611. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  50612. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  50613. xv1 = xv1.add(rotDX1);
  50614. xv2 = xv2.add(rotDX2);
  50615. }
  50616. fy += dy;
  50617. }
  50618. return textureArray;
  50619. };
  50620. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  50621. var theta = Math.atan2(vDir.z, vDir.x);
  50622. var phi = Math.acos(vDir.y);
  50623. while (theta < -Math.PI)
  50624. theta += 2 * Math.PI;
  50625. while (theta > Math.PI)
  50626. theta -= 2 * Math.PI;
  50627. var dx = theta / Math.PI;
  50628. var dy = phi / Math.PI;
  50629. // recenter.
  50630. dx = dx * 0.5 + 0.5;
  50631. var px = Math.round(dx * inputWidth);
  50632. if (px < 0)
  50633. px = 0;
  50634. else if (px >= inputWidth)
  50635. px = inputWidth - 1;
  50636. var py = Math.round(dy * inputHeight);
  50637. if (py < 0)
  50638. py = 0;
  50639. else if (py >= inputHeight)
  50640. py = inputHeight - 1;
  50641. var inputY = (inputHeight - py - 1);
  50642. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  50643. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  50644. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  50645. return {
  50646. r: r,
  50647. g: g,
  50648. b: b
  50649. };
  50650. };
  50651. return PanoramaToCubeMapTools;
  50652. }());
  50653. PanoramaToCubeMapTools.FACE_FRONT = [
  50654. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50655. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50656. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50657. new BABYLON.Vector3(1.0, 1.0, -1.0)
  50658. ];
  50659. PanoramaToCubeMapTools.FACE_BACK = [
  50660. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50661. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50662. new BABYLON.Vector3(1.0, 1.0, 1.0),
  50663. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  50664. ];
  50665. PanoramaToCubeMapTools.FACE_RIGHT = [
  50666. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50667. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50668. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50669. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50670. ];
  50671. PanoramaToCubeMapTools.FACE_LEFT = [
  50672. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50673. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50674. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50675. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  50676. ];
  50677. PanoramaToCubeMapTools.FACE_DOWN = [
  50678. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50679. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50680. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50681. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50682. ];
  50683. PanoramaToCubeMapTools.FACE_UP = [
  50684. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50685. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50686. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50687. new BABYLON.Vector3(1.0, -1.0, -1.0)
  50688. ];
  50689. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  50690. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50691. })(BABYLON || (BABYLON = {}));
  50692. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  50693. var BABYLON;
  50694. (function (BABYLON) {
  50695. var Internals;
  50696. (function (Internals) {
  50697. ;
  50698. /**
  50699. * This groups tools to convert HDR texture to native colors array.
  50700. */
  50701. var HDRTools = (function () {
  50702. function HDRTools() {
  50703. }
  50704. HDRTools.Ldexp = function (mantissa, exponent) {
  50705. if (exponent > 1023) {
  50706. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  50707. }
  50708. if (exponent < -1074) {
  50709. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  50710. }
  50711. return mantissa * Math.pow(2, exponent);
  50712. };
  50713. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  50714. if (exponent > 0) {
  50715. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  50716. float32array[index + 0] = red * exponent;
  50717. float32array[index + 1] = green * exponent;
  50718. float32array[index + 2] = blue * exponent;
  50719. }
  50720. else {
  50721. float32array[index + 0] = 0;
  50722. float32array[index + 1] = 0;
  50723. float32array[index + 2] = 0;
  50724. }
  50725. };
  50726. HDRTools.readStringLine = function (uint8array, startIndex) {
  50727. var line = "";
  50728. var character = "";
  50729. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  50730. character = String.fromCharCode(uint8array[i]);
  50731. if (character == "\n") {
  50732. break;
  50733. }
  50734. line += character;
  50735. }
  50736. return line;
  50737. };
  50738. /**
  50739. * Reads header information from an RGBE texture stored in a native array.
  50740. * More information on this format are available here:
  50741. * https://en.wikipedia.org/wiki/RGBE_image_format
  50742. *
  50743. * @param uint8array The binary file stored in native array.
  50744. * @return The header information.
  50745. */
  50746. HDRTools.RGBE_ReadHeader = function (uint8array) {
  50747. var height = 0;
  50748. var width = 0;
  50749. var line = this.readStringLine(uint8array, 0);
  50750. if (line[0] != '#' || line[1] != '?') {
  50751. throw "Bad HDR Format.";
  50752. }
  50753. var endOfHeader = false;
  50754. var findFormat = false;
  50755. var lineIndex = 0;
  50756. do {
  50757. lineIndex += (line.length + 1);
  50758. line = this.readStringLine(uint8array, lineIndex);
  50759. if (line == "FORMAT=32-bit_rle_rgbe") {
  50760. findFormat = true;
  50761. }
  50762. else if (line.length == 0) {
  50763. endOfHeader = true;
  50764. }
  50765. } while (!endOfHeader);
  50766. if (!findFormat) {
  50767. throw "HDR Bad header format, unsupported FORMAT";
  50768. }
  50769. lineIndex += (line.length + 1);
  50770. line = this.readStringLine(uint8array, lineIndex);
  50771. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  50772. var match = sizeRegexp.exec(line);
  50773. // TODO. Support +Y and -X if needed.
  50774. if (match.length < 3) {
  50775. throw "HDR Bad header format, no size";
  50776. }
  50777. width = parseInt(match[2]);
  50778. height = parseInt(match[1]);
  50779. if (width < 8 || width > 0x7fff) {
  50780. throw "HDR Bad header format, unsupported size";
  50781. }
  50782. lineIndex += (line.length + 1);
  50783. return {
  50784. height: height,
  50785. width: width,
  50786. dataPosition: lineIndex
  50787. };
  50788. };
  50789. /**
  50790. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  50791. * This RGBE texture needs to store the information as a panorama.
  50792. *
  50793. * More information on this format are available here:
  50794. * https://en.wikipedia.org/wiki/RGBE_image_format
  50795. *
  50796. * @param buffer The binary file stored in an array buffer.
  50797. * @param size The expected size of the extracted cubemap.
  50798. * @return The Cube Map information.
  50799. */
  50800. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  50801. var uint8array = new Uint8Array(buffer);
  50802. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  50803. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50804. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  50805. return cubeMapData;
  50806. };
  50807. /**
  50808. * Returns the pixels data extracted from an RGBE texture.
  50809. * This pixels will be stored left to right up to down in the R G B order in one array.
  50810. *
  50811. * More information on this format are available here:
  50812. * https://en.wikipedia.org/wiki/RGBE_image_format
  50813. *
  50814. * @param uint8array The binary file stored in an array buffer.
  50815. * @param hdrInfo The header information of the file.
  50816. * @return The pixels data in RGB right to left up to down order.
  50817. */
  50818. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  50819. // Keep for multi format supports.
  50820. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50821. };
  50822. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  50823. var num_scanlines = hdrInfo.height;
  50824. var scanline_width = hdrInfo.width;
  50825. var a, b, c, d, count;
  50826. var dataIndex = hdrInfo.dataPosition;
  50827. var index = 0, endIndex = 0, i = 0;
  50828. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  50829. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  50830. // 3 channels of 4 bytes per pixel in float.
  50831. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  50832. var resultArray = new Float32Array(resultBuffer);
  50833. // read in each successive scanline
  50834. while (num_scanlines > 0) {
  50835. a = uint8array[dataIndex++];
  50836. b = uint8array[dataIndex++];
  50837. c = uint8array[dataIndex++];
  50838. d = uint8array[dataIndex++];
  50839. if (a != 2 || b != 2 || (c & 0x80)) {
  50840. // this file is not run length encoded
  50841. throw "HDR Bad header format, not RLE";
  50842. }
  50843. if (((c << 8) | d) != scanline_width) {
  50844. throw "HDR Bad header format, wrong scan line width";
  50845. }
  50846. index = 0;
  50847. // read each of the four channels for the scanline into the buffer
  50848. for (i = 0; i < 4; i++) {
  50849. endIndex = (i + 1) * scanline_width;
  50850. while (index < endIndex) {
  50851. a = uint8array[dataIndex++];
  50852. b = uint8array[dataIndex++];
  50853. if (a > 128) {
  50854. // a run of the same value
  50855. count = a - 128;
  50856. if ((count == 0) || (count > endIndex - index)) {
  50857. throw "HDR Bad Format, bad scanline data (run)";
  50858. }
  50859. while (count-- > 0) {
  50860. scanLineArray[index++] = b;
  50861. }
  50862. }
  50863. else {
  50864. // a non-run
  50865. count = a;
  50866. if ((count == 0) || (count > endIndex - index)) {
  50867. throw "HDR Bad Format, bad scanline data (non-run)";
  50868. }
  50869. scanLineArray[index++] = b;
  50870. if (--count > 0) {
  50871. for (var j = 0; j < count; j++) {
  50872. scanLineArray[index++] = uint8array[dataIndex++];
  50873. }
  50874. }
  50875. }
  50876. }
  50877. }
  50878. // now convert data from buffer into floats
  50879. for (i = 0; i < scanline_width; i++) {
  50880. a = scanLineArray[i];
  50881. b = scanLineArray[i + scanline_width];
  50882. c = scanLineArray[i + 2 * scanline_width];
  50883. d = scanLineArray[i + 3 * scanline_width];
  50884. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  50885. }
  50886. num_scanlines--;
  50887. }
  50888. return resultArray;
  50889. };
  50890. return HDRTools;
  50891. }());
  50892. Internals.HDRTools = HDRTools;
  50893. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50894. })(BABYLON || (BABYLON = {}));
  50895. //# sourceMappingURL=babylon.hdr.js.map
  50896. //_______________________________________________________________
  50897. // Extracted from CubeMapGen:
  50898. // https://code.google.com/archive/p/cubemapgen/
  50899. //
  50900. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50901. //_______________________________________________________________
  50902. var BABYLON;
  50903. (function (BABYLON) {
  50904. var Internals;
  50905. (function (Internals) {
  50906. /**
  50907. * The bounding box information used during the conversion process.
  50908. */
  50909. var CMGBoundinBox = (function () {
  50910. function CMGBoundinBox() {
  50911. this.min = new BABYLON.Vector3(0, 0, 0);
  50912. this.max = new BABYLON.Vector3(0, 0, 0);
  50913. this.clear();
  50914. }
  50915. CMGBoundinBox.prototype.clear = function () {
  50916. this.min.x = CMGBoundinBox.MAX;
  50917. this.min.y = CMGBoundinBox.MAX;
  50918. this.min.z = CMGBoundinBox.MAX;
  50919. this.max.x = CMGBoundinBox.MIN;
  50920. this.max.y = CMGBoundinBox.MIN;
  50921. this.max.z = CMGBoundinBox.MIN;
  50922. };
  50923. CMGBoundinBox.prototype.augment = function (x, y, z) {
  50924. this.min.x = Math.min(this.min.x, x);
  50925. this.min.y = Math.min(this.min.y, y);
  50926. this.min.z = Math.min(this.min.z, z);
  50927. this.max.x = Math.max(this.max.x, x);
  50928. this.max.y = Math.max(this.max.y, y);
  50929. this.max.z = Math.max(this.max.z, z);
  50930. };
  50931. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  50932. this.min.x = Math.max(this.min.x, x);
  50933. this.min.y = Math.max(this.min.y, y);
  50934. this.min.z = Math.max(this.min.z, z);
  50935. };
  50936. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  50937. this.max.x = Math.min(this.max.x, x);
  50938. this.max.y = Math.min(this.max.y, y);
  50939. this.max.z = Math.min(this.max.z, z);
  50940. };
  50941. CMGBoundinBox.prototype.empty = function () {
  50942. if ((this.min.x > this.max.y) ||
  50943. (this.min.y > this.max.y) ||
  50944. (this.min.z > this.max.y)) {
  50945. return true;
  50946. }
  50947. else {
  50948. return false;
  50949. }
  50950. };
  50951. return CMGBoundinBox;
  50952. }());
  50953. CMGBoundinBox.MAX = Number.MAX_VALUE;
  50954. CMGBoundinBox.MIN = Number.MIN_VALUE;
  50955. /**
  50956. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  50957. * required by the glossinees of a material.
  50958. *
  50959. * This only supports the cosine drop power as well as Warp fixup generation method.
  50960. *
  50961. * This is using the process from CubeMapGen described here:
  50962. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50963. */
  50964. var PMREMGenerator = (function () {
  50965. /**
  50966. * Constructor of the generator.
  50967. *
  50968. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  50969. * @param inputSize The size of the cubemap faces
  50970. * @param outputSize The size of the output cubemap faces
  50971. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  50972. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  50973. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  50974. * @param specularPower The max specular level of the desired cubemap
  50975. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  50976. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  50977. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  50978. */
  50979. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  50980. this.input = input;
  50981. this.inputSize = inputSize;
  50982. this.outputSize = outputSize;
  50983. this.maxNumMipLevels = maxNumMipLevels;
  50984. this.numChannels = numChannels;
  50985. this.isFloat = isFloat;
  50986. this.specularPower = specularPower;
  50987. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  50988. this.excludeBase = excludeBase;
  50989. this.fixup = fixup;
  50990. this._outputSurface = [];
  50991. this._numMipLevels = 0;
  50992. }
  50993. /**
  50994. * Launches the filter process and return the result.
  50995. *
  50996. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  50997. */
  50998. PMREMGenerator.prototype.filterCubeMap = function () {
  50999. // Init cubemap processor
  51000. this.init();
  51001. // Filters the cubemap
  51002. this.filterCubeMapMipChain();
  51003. // Returns the filtered mips.
  51004. return this._outputSurface;
  51005. };
  51006. PMREMGenerator.prototype.init = function () {
  51007. var i;
  51008. var j;
  51009. var mipLevelSize;
  51010. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  51011. if (this.maxNumMipLevels == 0) {
  51012. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  51013. }
  51014. //first miplevel size
  51015. mipLevelSize = this.outputSize;
  51016. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  51017. for (j = 0; j < this.maxNumMipLevels; j++) {
  51018. this._outputSurface.length++;
  51019. this._outputSurface[j] = [];
  51020. //Iterate over faces for output images
  51021. for (i = 0; i < 6; i++) {
  51022. this._outputSurface[j].length++;
  51023. // Initializes a new array for the output.
  51024. if (this.isFloat) {
  51025. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51026. }
  51027. else {
  51028. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51029. }
  51030. }
  51031. //next mip level is half size
  51032. mipLevelSize >>= 1;
  51033. this._numMipLevels++;
  51034. //terminate if mip chain becomes too small
  51035. if (mipLevelSize == 0) {
  51036. this.maxNumMipLevels = j;
  51037. return;
  51038. }
  51039. }
  51040. };
  51041. //--------------------------------------------------------------------------------------
  51042. //Cube map filtering and mip chain generation.
  51043. // the cube map filtereing is specified using a number of parameters:
  51044. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  51045. // indicates the region of the hemisphere to filter over for each tap.
  51046. //
  51047. // Note that the top mip level is also a filtered version of the original input images
  51048. // as well in order to create mip chains for diffuse environment illumination.
  51049. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  51050. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  51051. //
  51052. // Then the mip angle used to genreate the next level of the mip chain from the first level
  51053. // is a_InitialMipAngle
  51054. //
  51055. // The angle for the subsequent levels of the mip chain are specified by their parents
  51056. // filtering angle and a per-level scale and bias
  51057. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  51058. //
  51059. //--------------------------------------------------------------------------------------
  51060. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  51061. // First, take count of the lighting model to modify SpecularPower
  51062. // 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;
  51063. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  51064. //Cone angle start (for generating subsequent mip levels)
  51065. var currentSpecularPower = this.specularPower;
  51066. //Build filter lookup tables based on the source miplevel size
  51067. this.precomputeFilterLookupTables(this.inputSize);
  51068. // Note that we need to filter the first level before generating mipmap
  51069. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  51070. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  51071. // TODO : Write a function to copy and scale the base mipmap in output
  51072. // I am just lazy here and just put a high specular power value, and do some if.
  51073. if (this.excludeBase && (levelIndex == 0)) {
  51074. // 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).
  51075. currentSpecularPower = 100000.0;
  51076. }
  51077. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  51078. var srcCubeImage = this.input;
  51079. var dstCubeImage = this._outputSurface[levelIndex];
  51080. var dstSize = this.outputSize >> levelIndex;
  51081. // Compute required angle.
  51082. var angle = this.getBaseFilterAngle(currentSpecularPower);
  51083. // filter cube surfaces
  51084. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  51085. // fix seams
  51086. if (this.fixup) {
  51087. this.fixupCubeEdges(dstCubeImage, dstSize);
  51088. }
  51089. // Decrease the specular power to generate the mipmap chain
  51090. // TODO : Use another method for Exclude (see first comment at start of the function
  51091. if (this.excludeBase && (levelIndex == 0)) {
  51092. currentSpecularPower = this.specularPower;
  51093. }
  51094. currentSpecularPower *= this.cosinePowerDropPerMip;
  51095. }
  51096. };
  51097. //--------------------------------------------------------------------------------------
  51098. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  51099. // It allow to optimize the texel to access base on the specular power.
  51100. //--------------------------------------------------------------------------------------
  51101. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  51102. // We want to find the alpha such that:
  51103. // cos(alpha)^cosinePower = epsilon
  51104. // That's: acos(epsilon^(1/cosinePower))
  51105. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  51106. var angle = 180.0;
  51107. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  51108. angle *= 180.0 / Math.PI; // Convert to degree
  51109. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  51110. return angle;
  51111. };
  51112. //--------------------------------------------------------------------------------------
  51113. //Builds the following lookup tables prior to filtering:
  51114. // -normalizer cube map
  51115. // -tap weight lookup table
  51116. //
  51117. //--------------------------------------------------------------------------------------
  51118. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  51119. var srcTexelAngle;
  51120. var iCubeFace;
  51121. //clear pre-existing normalizer cube map
  51122. this._normCubeMap = [];
  51123. //Normalized vectors per cubeface and per-texel solid angle
  51124. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  51125. };
  51126. //--------------------------------------------------------------------------------------
  51127. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  51128. //
  51129. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  51130. //
  51131. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  51132. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  51133. // below
  51134. //--------------------------------------------------------------------------------------
  51135. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  51136. var iCubeFace;
  51137. var u;
  51138. var v;
  51139. //iterate over cube faces
  51140. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51141. //First three channels for norm cube, and last channel for solid angle
  51142. this._normCubeMap.push(new Float32Array(size * size * 4));
  51143. //fast texture walk, build normalizer cube map
  51144. var facesData = this.input[iCubeFace];
  51145. for (v = 0; v < size; v++) {
  51146. for (u = 0; u < size; u++) {
  51147. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  51148. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  51149. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  51150. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  51151. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  51152. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  51153. }
  51154. }
  51155. }
  51156. };
  51157. //--------------------------------------------------------------------------------------
  51158. // Convert cubemap face texel coordinates and face idx to 3D vector
  51159. // note the U and V coords are integer coords and range from 0 to size-1
  51160. // this routine can be used to generate a normalizer cube map
  51161. //--------------------------------------------------------------------------------------
  51162. // SL BEGIN
  51163. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  51164. var nvcU;
  51165. var nvcV;
  51166. var tempVec;
  51167. // Change from original AMD code
  51168. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51169. // + 0.5f is for texel center addressing
  51170. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  51171. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  51172. // warp fixup
  51173. if (fixup && size > 1) {
  51174. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  51175. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  51176. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  51177. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  51178. }
  51179. // Get current vector
  51180. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  51181. // U contribution
  51182. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51183. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  51184. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  51185. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  51186. // V contribution and Sum
  51187. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51188. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  51189. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  51190. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  51191. //add face axis
  51192. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  51193. PMREMGenerator._vectorTemp.x += faceAxis[0];
  51194. PMREMGenerator._vectorTemp.y += faceAxis[1];
  51195. PMREMGenerator._vectorTemp.z += faceAxis[2];
  51196. //normalize vector
  51197. PMREMGenerator._vectorTemp.normalize();
  51198. return PMREMGenerator._vectorTemp;
  51199. };
  51200. //--------------------------------------------------------------------------------------
  51201. // Convert 3D vector to cubemap face texel coordinates and face idx
  51202. // note the U and V coords are integer coords and range from 0 to size-1
  51203. // this routine can be used to generate a normalizer cube map
  51204. //
  51205. // returns face IDX and texel coords
  51206. //--------------------------------------------------------------------------------------
  51207. // SL BEGIN
  51208. /*
  51209. Mapping Texture Coordinates to Cube Map Faces
  51210. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  51211. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  51212. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  51213. map arrangement in Pixar's RenderMan package.
  51214. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  51215. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  51216. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  51217. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  51218. the major axis direction). The target column in the table below explains how the major axis direction
  51219. maps to the 2D image of a particular cube map target.
  51220. major axis
  51221. direction target sc tc ma
  51222. ---------- --------------------------------- --- --- ---
  51223. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  51224. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  51225. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  51226. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  51227. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  51228. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  51229. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  51230. an updated (s,t) is calculated as follows
  51231. s = ( sc/|ma| + 1 ) / 2
  51232. t = ( tc/|ma| + 1 ) / 2
  51233. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  51234. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  51235. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  51236. */
  51237. // Note this method return U and V in range from 0 to size-1
  51238. // SL END
  51239. // Store the information in vector3 for convenience (faceindex, u, v)
  51240. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  51241. var maxCoord;
  51242. var faceIdx;
  51243. //absolute value 3
  51244. var absX = Math.abs(x);
  51245. var absY = Math.abs(y);
  51246. var absZ = Math.abs(z);
  51247. if (absX >= absY && absX >= absZ) {
  51248. maxCoord = absX;
  51249. if (x >= 0) {
  51250. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  51251. }
  51252. else {
  51253. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51254. }
  51255. }
  51256. else if (absY >= absX && absY >= absZ) {
  51257. maxCoord = absY;
  51258. if (y >= 0) {
  51259. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51260. }
  51261. else {
  51262. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51263. }
  51264. }
  51265. else {
  51266. maxCoord = absZ;
  51267. if (z >= 0) {
  51268. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51269. }
  51270. else {
  51271. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51272. }
  51273. }
  51274. //divide through by max coord so face vector lies on cube face
  51275. var scale = 1 / maxCoord;
  51276. x *= scale;
  51277. y *= scale;
  51278. z *= scale;
  51279. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51280. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  51281. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51282. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  51283. // Modify original AMD code to return value from 0 to Size - 1
  51284. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  51285. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  51286. PMREMGenerator._vectorTemp.x = faceIdx;
  51287. PMREMGenerator._vectorTemp.y = u;
  51288. PMREMGenerator._vectorTemp.z = v;
  51289. return PMREMGenerator._vectorTemp;
  51290. };
  51291. //--------------------------------------------------------------------------------------
  51292. //Original code from Ignacio CastaÒo
  51293. // This formula is from Manne ÷hrstrˆm's thesis.
  51294. // Take two coordiantes in the range [-1, 1] that define a portion of a
  51295. // cube face and return the area of the projection of that portion on the
  51296. // surface of the sphere.
  51297. //--------------------------------------------------------------------------------------
  51298. PMREMGenerator.prototype.areaElement = function (x, y) {
  51299. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  51300. };
  51301. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  51302. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51303. // (+ 0.5f is for texel center addressing)
  51304. u = (2.0 * (u + 0.5) / size) - 1.0;
  51305. v = (2.0 * (v + 0.5) / size) - 1.0;
  51306. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  51307. var invResolution = 1.0 / size;
  51308. // U and V are the -1..1 texture coordinate on the current face.
  51309. // Get projected area for this texel
  51310. var x0 = u - invResolution;
  51311. var y0 = v - invResolution;
  51312. var x1 = u + invResolution;
  51313. var y1 = v + invResolution;
  51314. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  51315. return solidAngle;
  51316. };
  51317. //--------------------------------------------------------------------------------------
  51318. //The key to the speed of these filtering routines is to quickly define a per-face
  51319. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  51320. // Later these pixels are selectively processed based on their dot products to see if
  51321. // they reside within the filtering cone.
  51322. //
  51323. //This is done by computing the smallest per-texel angle to get a conservative estimate
  51324. // of the number of texels needed to be covered in width and height order to filter the
  51325. // region. the bounding box for the center taps face is defined first, and if the
  51326. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  51327. // defined next
  51328. //--------------------------------------------------------------------------------------
  51329. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  51330. // note that pixels within these regions may be rejected
  51331. // based on the anlge
  51332. var iCubeFace;
  51333. var u;
  51334. var v;
  51335. // bounding box per face to specify region to process
  51336. var filterExtents = [];
  51337. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51338. filterExtents.push(new CMGBoundinBox());
  51339. }
  51340. // min angle a src texel can cover (in degrees)
  51341. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  51342. // angle about center tap to define filter cone
  51343. // filter angle is 1/2 the cone angle
  51344. var filterAngle = filterConeAngle / 2.0;
  51345. //ensure filter angle is larger than a texel
  51346. if (filterAngle < srcTexelAngle) {
  51347. filterAngle = srcTexelAngle;
  51348. }
  51349. //ensure filter cone is always smaller than the hemisphere
  51350. if (filterAngle > 90.0) {
  51351. filterAngle = 90.0;
  51352. }
  51353. // the maximum number of texels in 1D the filter cone angle will cover
  51354. // used to determine bounding box size for filter extents
  51355. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  51356. // ensure conservative region always covers at least one texel
  51357. if (filterSize < 1) {
  51358. filterSize = 1;
  51359. }
  51360. // dotProdThresh threshold based on cone angle to determine whether or not taps
  51361. // reside within the cone angle
  51362. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  51363. // process required faces
  51364. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51365. //iterate over dst cube map face texel
  51366. for (v = 0; v < dstSize; v++) {
  51367. for (u = 0; u < dstSize; u++) {
  51368. //get center tap direction
  51369. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  51370. //clear old per-face filter extents
  51371. this.clearFilterExtents(filterExtents);
  51372. //define per-face filter extents
  51373. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  51374. //perform filtering of src faces using filter extents
  51375. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  51376. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  51377. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  51378. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  51379. }
  51380. }
  51381. }
  51382. };
  51383. //--------------------------------------------------------------------------------------
  51384. //Clear filter extents for the 6 cube map faces
  51385. //--------------------------------------------------------------------------------------
  51386. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  51387. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  51388. filterExtents[iCubeFaces].clear();
  51389. }
  51390. };
  51391. //--------------------------------------------------------------------------------------
  51392. //Define per-face bounding box filter extents
  51393. //
  51394. // These define conservative texel regions in each of the faces the filter can possibly
  51395. // process. When the pixels in the regions are actually processed, the dot product
  51396. // between the tap vector and the center tap vector is used to determine the weight of
  51397. // the tap and whether or not the tap is within the cone.
  51398. //
  51399. //--------------------------------------------------------------------------------------
  51400. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  51401. //neighboring face and bleed over amount, and width of BBOX for
  51402. // left, right, top, and bottom edges of this face
  51403. var bleedOverAmount = [0, 0, 0, 0];
  51404. var bleedOverBBoxMin = [0, 0, 0, 0];
  51405. var bleedOverBBoxMax = [0, 0, 0, 0];
  51406. var neighborFace;
  51407. var neighborEdge;
  51408. var oppositeFaceIdx;
  51409. //get face idx, and u, v info from center tap dir
  51410. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  51411. var faceIdx = result.x;
  51412. var u = result.y;
  51413. var v = result.z;
  51414. //define bbox size within face
  51415. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  51416. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  51417. filterExtents[faceIdx].clampMin(0, 0, 0);
  51418. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  51419. //u and v extent in face corresponding to center tap
  51420. var minU = filterExtents[faceIdx].min.x;
  51421. var minV = filterExtents[faceIdx].min.y;
  51422. var maxU = filterExtents[faceIdx].max.x;
  51423. var maxV = filterExtents[faceIdx].max.y;
  51424. //bleed over amounts for face across u=0 edge (left)
  51425. bleedOverAmount[0] = (bboxSize - u);
  51426. bleedOverBBoxMin[0] = minV;
  51427. bleedOverBBoxMax[0] = maxV;
  51428. //bleed over amounts for face across u=1 edge (right)
  51429. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  51430. bleedOverBBoxMin[1] = minV;
  51431. bleedOverBBoxMax[1] = maxV;
  51432. //bleed over to face across v=0 edge (up)
  51433. bleedOverAmount[2] = (bboxSize - v);
  51434. bleedOverBBoxMin[2] = minU;
  51435. bleedOverBBoxMax[2] = maxU;
  51436. //bleed over to face across v=1 edge (down)
  51437. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  51438. bleedOverBBoxMin[3] = minU;
  51439. bleedOverBBoxMax[3] = maxU;
  51440. //compute bleed over regions in neighboring faces
  51441. for (var i = 0; i < 4; i++) {
  51442. if (bleedOverAmount[i] > 0) {
  51443. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  51444. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  51445. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  51446. // be flipped: the cases are
  51447. // if a left edge mates with a left or bottom edge on the neighbor
  51448. // if a top edge mates with a top or right edge on the neighbor
  51449. // if a right edge mates with a right or top edge on the neighbor
  51450. // if a bottom edge mates with a bottom or left edge on the neighbor
  51451. //Seeing as the edges are enumerated as follows
  51452. // left =0
  51453. // right =1
  51454. // top =2
  51455. // bottom =3
  51456. //
  51457. // so if the edge enums are the same, or the sum of the enums == 3,
  51458. // the bbox needs to be flipped
  51459. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  51460. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  51461. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  51462. }
  51463. //The way the bounding box is extended onto the neighboring face
  51464. // depends on which edge of neighboring face abuts with this one
  51465. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  51466. case PMREMGenerator.CP_EDGE_LEFT:
  51467. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  51468. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51469. break;
  51470. case PMREMGenerator.CP_EDGE_RIGHT:
  51471. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  51472. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51473. break;
  51474. case PMREMGenerator.CP_EDGE_TOP:
  51475. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  51476. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  51477. break;
  51478. case PMREMGenerator.CP_EDGE_BOTTOM:
  51479. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  51480. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  51481. break;
  51482. }
  51483. //clamp filter extents in non-center tap faces to remain within surface
  51484. filterExtents[neighborFace].clampMin(0, 0, 0);
  51485. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  51486. }
  51487. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  51488. // from the center tap face, then process the opposite face entirely for now.
  51489. //Note that the cases in which this happens, what usually happens is that
  51490. // more than one edge bleeds onto the opposite face, and the bounding box
  51491. // encompasses the entire cube map face.
  51492. if (bleedOverAmount[i] > srcSize) {
  51493. //determine opposite face
  51494. switch (faceIdx) {
  51495. case PMREMGenerator.CP_FACE_X_POS:
  51496. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51497. break;
  51498. case PMREMGenerator.CP_FACE_X_NEG:
  51499. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  51500. break;
  51501. case PMREMGenerator.CP_FACE_Y_POS:
  51502. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51503. break;
  51504. case PMREMGenerator.CP_FACE_Y_NEG:
  51505. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51506. break;
  51507. case PMREMGenerator.CP_FACE_Z_POS:
  51508. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51509. break;
  51510. case PMREMGenerator.CP_FACE_Z_NEG:
  51511. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51512. break;
  51513. default:
  51514. break;
  51515. }
  51516. //just encompass entire face for now
  51517. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  51518. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  51519. }
  51520. }
  51521. };
  51522. //--------------------------------------------------------------------------------------
  51523. //ProcessFilterExtents
  51524. // Process bounding box in each cube face
  51525. //
  51526. //--------------------------------------------------------------------------------------
  51527. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  51528. //accumulators are 64-bit floats in order to have the precision needed
  51529. // over a summation of a large number of pixels
  51530. var dstAccum = [0, 0, 0, 0];
  51531. var weightAccum = 0;
  51532. var k = 0;
  51533. var nSrcChannels = this.numChannels;
  51534. // norm cube map and srcCubeMap have same face width
  51535. var faceWidth = srcSize;
  51536. //amount to add to pointer to move to next scanline in images
  51537. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  51538. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  51539. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  51540. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  51541. // iterate over cubefaces
  51542. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  51543. //if bbox is non empty
  51544. if (!filterExtents[iFaceIdx].empty()) {
  51545. var uStart = filterExtents[iFaceIdx].min.x;
  51546. var vStart = filterExtents[iFaceIdx].min.y;
  51547. var uEnd = filterExtents[iFaceIdx].max.x;
  51548. var vEnd = filterExtents[iFaceIdx].max.y;
  51549. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  51550. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  51551. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  51552. for (var v = vStart; v <= vEnd; v++) {
  51553. var normCubeRowWalk = 0;
  51554. var srcCubeRowWalk = 0;
  51555. for (var u = uStart; u <= uEnd; u++) {
  51556. //pointer to direction in cube map associated with texel
  51557. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  51558. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  51559. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  51560. //check dot product to see if texel is within cone
  51561. var tapDotProd = texelVectX * centerTapDir.x +
  51562. texelVectY * centerTapDir.y +
  51563. texelVectZ * centerTapDir.z;
  51564. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  51565. //solid angle stored in 4th channel of normalizer/solid angle cube map
  51566. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  51567. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  51568. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  51569. // so just adding one to specularpower do the trick.
  51570. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  51571. //iterate over channels
  51572. for (k = 0; k < nSrcChannels; k++) {
  51573. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  51574. srcCubeRowWalk++;
  51575. }
  51576. weightAccum += weight; //accumulate weight
  51577. }
  51578. else {
  51579. //step across source pixel
  51580. srcCubeRowWalk += nSrcChannels;
  51581. }
  51582. normCubeRowWalk += 4; // 4 channels per norm cube map.
  51583. }
  51584. startIndexNormCubeMap += normCubePitch;
  51585. startIndexSrcCubeMap += srcCubePitch;
  51586. }
  51587. }
  51588. }
  51589. //divide through by weights if weight is non zero
  51590. if (weightAccum != 0.0) {
  51591. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  51592. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  51593. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  51594. if (this.numChannels > 3) {
  51595. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  51596. }
  51597. }
  51598. else {
  51599. // otherwise sample nearest
  51600. // get face idx and u, v texel coordinate in face
  51601. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  51602. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  51603. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  51604. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  51605. if (this.numChannels > 3) {
  51606. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  51607. }
  51608. }
  51609. return PMREMGenerator._vectorTemp;
  51610. };
  51611. //--------------------------------------------------------------------------------------
  51612. // Fixup cube edges
  51613. //
  51614. // average texels on cube map faces across the edges
  51615. // WARP/BENT Method Only.
  51616. //--------------------------------------------------------------------------------------
  51617. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  51618. var k;
  51619. var j;
  51620. var i;
  51621. var iFace;
  51622. var iCorner = 0;
  51623. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  51624. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  51625. // note that if functionality to filter across the three texels for each corner, then
  51626. //indexed by corner and face idx. the array contains the face the start points belongs to.
  51627. var cornerPtr = [
  51628. [[], [], []],
  51629. [[], [], []],
  51630. [[], [], []],
  51631. [[], [], []],
  51632. [[], [], []],
  51633. [[], [], []],
  51634. [[], [], []],
  51635. [[], [], []]
  51636. ];
  51637. //if there is no fixup, or fixup width = 0, do nothing
  51638. if (cubeMapSize < 1) {
  51639. return;
  51640. }
  51641. //special case 1x1 cubemap, average face colors
  51642. if (cubeMapSize == 1) {
  51643. //iterate over channels
  51644. for (k = 0; k < this.numChannels; k++) {
  51645. var accum = 0.0;
  51646. //iterate over faces to accumulate face colors
  51647. for (iFace = 0; iFace < 6; iFace++) {
  51648. accum += cubeMap[iFace][k];
  51649. }
  51650. //compute average over 6 face colors
  51651. accum /= 6.0;
  51652. //iterate over faces to distribute face colors
  51653. for (iFace = 0; iFace < 6; iFace++) {
  51654. cubeMap[iFace][k] = accum;
  51655. }
  51656. }
  51657. return;
  51658. }
  51659. //iterate over faces to collect list of corner texel pointers
  51660. for (iFace = 0; iFace < 6; iFace++) {
  51661. //the 4 corner pointers for this face
  51662. faceCornerStartIndicies[0] = [iFace, 0];
  51663. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  51664. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  51665. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  51666. //iterate over face corners to collect cube corner pointers
  51667. for (iCorner = 0; iCorner < 4; iCorner++) {
  51668. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  51669. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  51670. cornerNumPtrs[corner]++;
  51671. }
  51672. }
  51673. //iterate over corners to average across corner tap values
  51674. for (iCorner = 0; iCorner < 8; iCorner++) {
  51675. for (k = 0; k < this.numChannels; k++) {
  51676. var cornerTapAccum = 0.0;
  51677. //iterate over corner texels and average results
  51678. for (i = 0; i < 3; i++) {
  51679. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  51680. }
  51681. //divide by 3 to compute average of corner tap values
  51682. cornerTapAccum *= (1.0 / 3.0);
  51683. //iterate over corner texels and average results
  51684. for (i = 0; i < 3; i++) {
  51685. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  51686. }
  51687. }
  51688. }
  51689. //iterate over the twelve edges of the cube to average across edges
  51690. for (i = 0; i < 12; i++) {
  51691. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  51692. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  51693. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  51694. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  51695. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  51696. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  51697. var edgeWalk = 0;
  51698. var neighborEdgeWalk = 0;
  51699. //Determine walking pointers based on edge type
  51700. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  51701. switch (edge) {
  51702. case PMREMGenerator.CP_EDGE_LEFT:
  51703. // no change to faceEdgeStartPtr
  51704. edgeWalk = this.numChannels * cubeMapSize;
  51705. break;
  51706. case PMREMGenerator.CP_EDGE_RIGHT:
  51707. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51708. edgeWalk = this.numChannels * cubeMapSize;
  51709. break;
  51710. case PMREMGenerator.CP_EDGE_TOP:
  51711. // no change to faceEdgeStartPtr
  51712. edgeWalk = this.numChannels;
  51713. break;
  51714. case PMREMGenerator.CP_EDGE_BOTTOM:
  51715. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51716. edgeWalk = this.numChannels;
  51717. break;
  51718. }
  51719. //For certain types of edge abutments, the neighbor edge walk needs 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. //If the edge enums are the same, or the sum of the enums == 3,
  51732. // the neighbor edge walk needs to be flipped
  51733. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  51734. switch (neighborEdge) {
  51735. case PMREMGenerator.CP_EDGE_LEFT:
  51736. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  51737. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51738. break;
  51739. case PMREMGenerator.CP_EDGE_RIGHT:
  51740. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51741. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51742. break;
  51743. case PMREMGenerator.CP_EDGE_TOP:
  51744. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51745. neighborEdgeWalk = -this.numChannels;
  51746. break;
  51747. case PMREMGenerator.CP_EDGE_BOTTOM:
  51748. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51749. neighborEdgeWalk = -this.numChannels;
  51750. break;
  51751. }
  51752. }
  51753. else {
  51754. //swapped direction neighbor edge walk
  51755. switch (neighborEdge) {
  51756. case PMREMGenerator.CP_EDGE_LEFT:
  51757. //no change to neighborEdgeStartPtr for this case since it points
  51758. // to the upper left corner already
  51759. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51760. break;
  51761. case PMREMGenerator.CP_EDGE_RIGHT:
  51762. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51763. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51764. break;
  51765. case PMREMGenerator.CP_EDGE_TOP:
  51766. //no change to neighborEdgeStartPtr for this case since it points
  51767. // to the upper left corner already
  51768. neighborEdgeWalk = this.numChannels;
  51769. break;
  51770. case PMREMGenerator.CP_EDGE_BOTTOM:
  51771. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51772. neighborEdgeWalk = this.numChannels;
  51773. break;
  51774. }
  51775. }
  51776. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  51777. //nearby neighborhood
  51778. //step ahead one texel on edge
  51779. edgeStartIndex += edgeWalk;
  51780. neighborEdgeStartIndex += neighborEdgeWalk;
  51781. // note that this loop does not process the corner texels, since they have already been
  51782. // averaged across faces across earlier
  51783. for (j = 1; j < (cubeMapSize - 1); j++) {
  51784. //for each set of taps along edge, average them
  51785. // and rewrite the results into the edges
  51786. for (k = 0; k < this.numChannels; k++) {
  51787. var edgeTap = cubeMap[face][edgeStartIndex + k];
  51788. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  51789. //compute average of tap intensity values
  51790. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  51791. //propagate average of taps to edge taps
  51792. cubeMap[face][edgeStartIndex + k] = avgTap;
  51793. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  51794. }
  51795. edgeStartIndex += edgeWalk;
  51796. neighborEdgeStartIndex += neighborEdgeWalk;
  51797. }
  51798. }
  51799. };
  51800. return PMREMGenerator;
  51801. }());
  51802. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  51803. PMREMGenerator.CP_UDIR = 0;
  51804. PMREMGenerator.CP_VDIR = 1;
  51805. PMREMGenerator.CP_FACEAXIS = 2;
  51806. //used to index cube faces
  51807. PMREMGenerator.CP_FACE_X_POS = 0;
  51808. PMREMGenerator.CP_FACE_X_NEG = 1;
  51809. PMREMGenerator.CP_FACE_Y_POS = 2;
  51810. PMREMGenerator.CP_FACE_Y_NEG = 3;
  51811. PMREMGenerator.CP_FACE_Z_POS = 4;
  51812. PMREMGenerator.CP_FACE_Z_NEG = 5;
  51813. //used to index image edges
  51814. // NOTE.. the actual number corresponding to the edge is important
  51815. // do not change these, or the code will break
  51816. //
  51817. // CP_EDGE_LEFT is u = 0
  51818. // CP_EDGE_RIGHT is u = width-1
  51819. // CP_EDGE_TOP is v = 0
  51820. // CP_EDGE_BOTTOM is v = height-1
  51821. PMREMGenerator.CP_EDGE_LEFT = 0;
  51822. PMREMGenerator.CP_EDGE_RIGHT = 1;
  51823. PMREMGenerator.CP_EDGE_TOP = 2;
  51824. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  51825. //corners of CUBE map (P or N specifys if it corresponds to the
  51826. // positive or negative direction each of X, Y, and Z
  51827. PMREMGenerator.CP_CORNER_NNN = 0;
  51828. PMREMGenerator.CP_CORNER_NNP = 1;
  51829. PMREMGenerator.CP_CORNER_NPN = 2;
  51830. PMREMGenerator.CP_CORNER_NPP = 3;
  51831. PMREMGenerator.CP_CORNER_PNN = 4;
  51832. PMREMGenerator.CP_CORNER_PNP = 5;
  51833. PMREMGenerator.CP_CORNER_PPN = 6;
  51834. PMREMGenerator.CP_CORNER_PPP = 7;
  51835. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  51836. //3x2 matrices that map cube map indexing vectors in 3d
  51837. // (after face selection and divide through by the
  51838. // _ABSOLUTE VALUE_ of the max coord)
  51839. // into NVC space
  51840. //Note this currently assumes the D3D cube face ordering and orientation
  51841. PMREMGenerator._sgFace2DMapping = [
  51842. //XPOS face
  51843. [[0, 0, -1],
  51844. [0, -1, 0],
  51845. [1, 0, 0]],
  51846. //XNEG face
  51847. [[0, 0, 1],
  51848. [0, -1, 0],
  51849. [-1, 0, 0]],
  51850. //YPOS face
  51851. [[1, 0, 0],
  51852. [0, 0, 1],
  51853. [0, 1, 0]],
  51854. //YNEG face
  51855. [[1, 0, 0],
  51856. [0, 0, -1],
  51857. [0, -1, 0]],
  51858. //ZPOS face
  51859. [[1, 0, 0],
  51860. [0, -1, 0],
  51861. [0, 0, 1]],
  51862. //ZNEG face
  51863. [[-1, 0, 0],
  51864. [0, -1, 0],
  51865. [0, 0, -1]],
  51866. ];
  51867. //------------------------------------------------------------------------------
  51868. // D3D cube map face specification
  51869. // mapping from 3D x,y,z cube map lookup coordinates
  51870. // to 2D within face u,v coordinates
  51871. //
  51872. // --------------------> U direction
  51873. // | (within-face texture space)
  51874. // | _____
  51875. // | | |
  51876. // | | +Y |
  51877. // | _____|_____|_____ _____
  51878. // | | | | | |
  51879. // | | -X | +Z | +X | -Z |
  51880. // | |_____|_____|_____|_____|
  51881. // | | |
  51882. // | | -Y |
  51883. // | |_____|
  51884. // |
  51885. // v V direction
  51886. // (within-face texture space)
  51887. //------------------------------------------------------------------------------
  51888. //Information about neighbors and how texture coorrdinates change across faces
  51889. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  51890. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  51891. //Note this currently assumes the D3D cube face ordering and orientation
  51892. PMREMGenerator._sgCubeNgh = [
  51893. //XPOS face
  51894. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51895. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51896. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51897. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  51898. //XNEG face
  51899. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51900. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  51901. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  51902. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  51903. //YPOS face
  51904. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51905. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51906. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51907. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  51908. //YNEG face
  51909. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51910. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51911. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51912. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  51913. //ZPOS face
  51914. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51915. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51916. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51917. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  51918. //ZNEG face
  51919. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51920. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51921. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  51922. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  51923. ];
  51924. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  51925. // this table is used to average over the edges.
  51926. PMREMGenerator._sgCubeEdgeList = [
  51927. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51928. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51929. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51930. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51931. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51932. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51933. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51934. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51935. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  51936. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51937. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51938. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  51939. ];
  51940. //Information about which of the 8 cube corners are correspond to the
  51941. // the 4 corners in each cube face
  51942. // the order is upper left, upper right, lower left, lower right
  51943. PMREMGenerator._sgCubeCornerList = [
  51944. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  51945. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  51946. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  51947. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  51948. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  51949. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  51950. ];
  51951. Internals.PMREMGenerator = PMREMGenerator;
  51952. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51953. })(BABYLON || (BABYLON = {}));
  51954. //# sourceMappingURL=babylon.pmremgenerator.js.map
  51955. var BABYLON;
  51956. (function (BABYLON) {
  51957. /**
  51958. * This represents a texture coming from an HDR input.
  51959. *
  51960. * The only supported format is currently panorama picture stored in RGBE format.
  51961. * Example of such files can be found on HDRLib: http://hdrlib.com/
  51962. */
  51963. var HDRCubeTexture = (function (_super) {
  51964. __extends(HDRCubeTexture, _super);
  51965. /**
  51966. * Instantiates an HDRTexture from the following parameters.
  51967. *
  51968. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  51969. * @param scene The scene the texture will be used in
  51970. * @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.
  51971. * @param noMipmap Forces to not generate the mipmap if true
  51972. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  51973. * @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)
  51974. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  51975. */
  51976. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  51977. if (noMipmap === void 0) { noMipmap = false; }
  51978. if (generateHarmonics === void 0) { generateHarmonics = true; }
  51979. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  51980. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  51981. if (onLoad === void 0) { onLoad = null; }
  51982. if (onError === void 0) { onError = null; }
  51983. var _this = _super.call(this, scene) || this;
  51984. _this._useInGammaSpace = false;
  51985. _this._generateHarmonics = true;
  51986. _this._isBABYLONPreprocessed = false;
  51987. _this._onLoad = null;
  51988. _this._onError = null;
  51989. /**
  51990. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  51991. */
  51992. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51993. /**
  51994. * The spherical polynomial data extracted from the texture.
  51995. */
  51996. _this.sphericalPolynomial = null;
  51997. /**
  51998. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  51999. * This is usefull at run time to apply the good shader.
  52000. */
  52001. _this.isPMREM = false;
  52002. if (!url) {
  52003. return _this;
  52004. }
  52005. _this.name = url;
  52006. _this.url = url;
  52007. _this.hasAlpha = false;
  52008. _this.isCube = true;
  52009. _this._textureMatrix = BABYLON.Matrix.Identity();
  52010. _this._onLoad = onLoad;
  52011. _this._onError = onError;
  52012. if (size) {
  52013. _this._isBABYLONPreprocessed = false;
  52014. _this._noMipmap = noMipmap;
  52015. _this._size = size;
  52016. _this._useInGammaSpace = useInGammaSpace;
  52017. _this._usePMREMGenerator = usePMREMGenerator &&
  52018. scene.getEngine().getCaps().textureLOD &&
  52019. _this.getScene().getEngine().getCaps().textureFloat &&
  52020. !_this._useInGammaSpace;
  52021. }
  52022. else {
  52023. _this._isBABYLONPreprocessed = true;
  52024. _this._noMipmap = false;
  52025. _this._useInGammaSpace = false;
  52026. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  52027. _this.getScene().getEngine().getCaps().textureFloat &&
  52028. !_this._useInGammaSpace;
  52029. }
  52030. _this.isPMREM = _this._usePMREMGenerator;
  52031. _this._texture = _this._getFromCache(url, _this._noMipmap);
  52032. if (!_this._texture) {
  52033. if (!scene.useDelayedTextureLoading) {
  52034. _this.loadTexture();
  52035. }
  52036. else {
  52037. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52038. }
  52039. }
  52040. return _this;
  52041. }
  52042. /**
  52043. * Occurs when the file is a preprocessed .babylon.hdr file.
  52044. */
  52045. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  52046. var _this = this;
  52047. var mipLevels = 0;
  52048. var floatArrayView = null;
  52049. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  52050. var mips = [];
  52051. var startIndex = 30;
  52052. for (var level = 0; level < mipLevels; level++) {
  52053. mips.push([]);
  52054. // Fill each pixel of the mip level.
  52055. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  52056. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52057. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  52058. mips[level].push(faceData);
  52059. startIndex += faceSize;
  52060. }
  52061. }
  52062. return mips;
  52063. } : null;
  52064. var callback = function (buffer) {
  52065. // Create Native Array Views
  52066. var intArrayView = new Int32Array(buffer);
  52067. floatArrayView = new Float32Array(buffer);
  52068. // Fill header.
  52069. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  52070. _this._size = intArrayView[1]; // CubeMap max mip face size.
  52071. // Update Texture Information.
  52072. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  52073. // Fill polynomial information.
  52074. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  52075. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  52076. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  52077. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  52078. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  52079. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  52080. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  52081. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  52082. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  52083. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  52084. // Fill pixel data.
  52085. mipLevels = intArrayView[29]; // Number of mip levels.
  52086. var startIndex = 30;
  52087. var data = [];
  52088. var faceSize = Math.pow(_this._size, 2) * 3;
  52089. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52090. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  52091. startIndex += faceSize;
  52092. }
  52093. var results = [];
  52094. var byteArray = null;
  52095. // Push each faces.
  52096. for (var k = 0; k < 6; k++) {
  52097. var dataFace = null;
  52098. // If special cases.
  52099. if (!mipmapGenerator) {
  52100. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  52101. dataFace = data[j];
  52102. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52103. // 3 channels of 1 bytes per pixel in bytes.
  52104. var byteBuffer = new ArrayBuffer(faceSize);
  52105. byteArray = new Uint8Array(byteBuffer);
  52106. }
  52107. for (var i = 0; i < _this._size * _this._size; i++) {
  52108. // Put in gamma space if requested.
  52109. if (_this._useInGammaSpace) {
  52110. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52111. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52112. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52113. }
  52114. // Convert to int texture for fallback.
  52115. if (byteArray) {
  52116. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52117. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52118. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52119. // May use luminance instead if the result is not accurate.
  52120. var max = Math.max(Math.max(r, g), b);
  52121. if (max > 255) {
  52122. var scale = 255 / max;
  52123. r *= scale;
  52124. g *= scale;
  52125. b *= scale;
  52126. }
  52127. byteArray[(i * 3) + 0] = r;
  52128. byteArray[(i * 3) + 1] = g;
  52129. byteArray[(i * 3) + 2] = b;
  52130. }
  52131. }
  52132. }
  52133. else {
  52134. dataFace = data[k];
  52135. }
  52136. // Fill the array accordingly.
  52137. if (byteArray) {
  52138. results.push(byteArray);
  52139. }
  52140. else {
  52141. results.push(dataFace);
  52142. }
  52143. }
  52144. return results;
  52145. };
  52146. 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);
  52147. };
  52148. /**
  52149. * Occurs when the file is raw .hdr file.
  52150. */
  52151. HDRCubeTexture.prototype.loadHDRTexture = function () {
  52152. var _this = this;
  52153. var callback = function (buffer) {
  52154. // Extract the raw linear data.
  52155. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  52156. // Generate harmonics if needed.
  52157. if (_this._generateHarmonics) {
  52158. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  52159. }
  52160. var results = [];
  52161. var byteArray = null;
  52162. // Push each faces.
  52163. for (var j = 0; j < 6; j++) {
  52164. // Create uintarray fallback.
  52165. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52166. // 3 channels of 1 bytes per pixel in bytes.
  52167. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  52168. byteArray = new Uint8Array(byteBuffer);
  52169. }
  52170. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  52171. // If special cases.
  52172. if (_this._useInGammaSpace || byteArray) {
  52173. for (var i = 0; i < _this._size * _this._size; i++) {
  52174. // Put in gamma space if requested.
  52175. if (_this._useInGammaSpace) {
  52176. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52177. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52178. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52179. }
  52180. // Convert to int texture for fallback.
  52181. if (byteArray) {
  52182. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52183. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52184. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52185. // May use luminance instead if the result is not accurate.
  52186. var max = Math.max(Math.max(r, g), b);
  52187. if (max > 255) {
  52188. var scale = 255 / max;
  52189. r *= scale;
  52190. g *= scale;
  52191. b *= scale;
  52192. }
  52193. byteArray[(i * 3) + 0] = r;
  52194. byteArray[(i * 3) + 1] = g;
  52195. byteArray[(i * 3) + 2] = b;
  52196. }
  52197. }
  52198. }
  52199. if (byteArray) {
  52200. results.push(byteArray);
  52201. }
  52202. else {
  52203. results.push(dataFace);
  52204. }
  52205. }
  52206. return results;
  52207. };
  52208. var mipmapGenerator = null;
  52209. if (!this._noMipmap &&
  52210. this._usePMREMGenerator) {
  52211. mipmapGenerator = function (data) {
  52212. // Custom setup of the generator matching with the PBR shader values.
  52213. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  52214. return generator.filterCubeMap();
  52215. };
  52216. }
  52217. 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);
  52218. };
  52219. /**
  52220. * Starts the loading process of the texture.
  52221. */
  52222. HDRCubeTexture.prototype.loadTexture = function () {
  52223. if (this._isBABYLONPreprocessed) {
  52224. this.loadBabylonTexture();
  52225. }
  52226. else {
  52227. this.loadHDRTexture();
  52228. }
  52229. };
  52230. HDRCubeTexture.prototype.clone = function () {
  52231. var size = this._isBABYLONPreprocessed ? null : this._size;
  52232. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  52233. // Base texture
  52234. newTexture.level = this.level;
  52235. newTexture.wrapU = this.wrapU;
  52236. newTexture.wrapV = this.wrapV;
  52237. newTexture.coordinatesIndex = this.coordinatesIndex;
  52238. newTexture.coordinatesMode = this.coordinatesMode;
  52239. return newTexture;
  52240. };
  52241. // Methods
  52242. HDRCubeTexture.prototype.delayLoad = function () {
  52243. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52244. return;
  52245. }
  52246. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52247. this._texture = this._getFromCache(this.url, this._noMipmap);
  52248. if (!this._texture) {
  52249. this.loadTexture();
  52250. }
  52251. };
  52252. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  52253. return this._textureMatrix;
  52254. };
  52255. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52256. var texture = null;
  52257. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52258. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  52259. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  52260. texture.name = parsedTexture.name;
  52261. texture.hasAlpha = parsedTexture.hasAlpha;
  52262. texture.level = parsedTexture.level;
  52263. texture.coordinatesMode = parsedTexture.coordinatesMode;
  52264. }
  52265. return texture;
  52266. };
  52267. HDRCubeTexture.prototype.serialize = function () {
  52268. if (!this.name) {
  52269. return null;
  52270. }
  52271. var serializationObject = {};
  52272. serializationObject.name = this.name;
  52273. serializationObject.hasAlpha = this.hasAlpha;
  52274. serializationObject.isCube = true;
  52275. serializationObject.level = this.level;
  52276. serializationObject.size = this._size;
  52277. serializationObject.coordinatesMode = this.coordinatesMode;
  52278. serializationObject.useInGammaSpace = this._useInGammaSpace;
  52279. serializationObject.generateHarmonics = this._generateHarmonics;
  52280. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  52281. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  52282. serializationObject.customType = "BABYLON.HDRCubeTexture";
  52283. serializationObject.noMipmap = this._noMipmap;
  52284. return serializationObject;
  52285. };
  52286. /**
  52287. * Saves as a file the data contained in the texture in a binary format.
  52288. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52289. * as the spherical used in the lighting.
  52290. * @param url The HDR file url.
  52291. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52292. * @param onError Method called if any error happens during download.
  52293. * @return The packed binary data.
  52294. */
  52295. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  52296. if (onError === void 0) { onError = null; }
  52297. var callback = function (buffer) {
  52298. var data = new Blob([buffer], { type: 'application/octet-stream' });
  52299. // Returns a URL you can use as a href.
  52300. var objUrl = window.URL.createObjectURL(data);
  52301. // Simulates a link to it and click to dowload.
  52302. var a = document.createElement("a");
  52303. document.body.appendChild(a);
  52304. a.style.display = "none";
  52305. a.href = objUrl;
  52306. a.download = "envmap.babylon.hdr";
  52307. a.click();
  52308. };
  52309. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  52310. };
  52311. /**
  52312. * Serializes the data contained in the texture in a binary format.
  52313. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52314. * as the spherical used in the lighting.
  52315. * @param url The HDR file url.
  52316. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52317. * @param onError Method called if any error happens during download.
  52318. * @return The packed binary data.
  52319. */
  52320. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  52321. if (onError === void 0) { onError = null; }
  52322. // Needs the url tho create the texture.
  52323. if (!url) {
  52324. return null;
  52325. }
  52326. // Check Power of two size.
  52327. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  52328. return null;
  52329. }
  52330. var getDataCallback = function (dataBuffer) {
  52331. // Extract the raw linear data.
  52332. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  52333. // Generate harmonics if needed.
  52334. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  52335. // Generate seamless faces
  52336. var mipGeneratorArray = [];
  52337. // Data are known to be in +X +Y +Z -X -Y -Z
  52338. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  52339. mipGeneratorArray.push(cubeData.right); // +X
  52340. mipGeneratorArray.push(cubeData.left); // -X
  52341. mipGeneratorArray.push(cubeData.up); // +Y
  52342. mipGeneratorArray.push(cubeData.down); // -Y
  52343. mipGeneratorArray.push(cubeData.front); // +Z
  52344. mipGeneratorArray.push(cubeData.back); // -Z
  52345. // Custom setup of the generator matching with the PBR shader values.
  52346. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  52347. var mippedData = generator.filterCubeMap();
  52348. // Compute required byte length.
  52349. var byteLength = 1 * 4; // Raw Data Version int32.
  52350. byteLength += 4; // CubeMap max mip face size int32.
  52351. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  52352. // Add data size.
  52353. byteLength += 4; // Number of mip levels int32.
  52354. for (var level = 0; level < mippedData.length; level++) {
  52355. var mipSize = size >> level;
  52356. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  52357. }
  52358. // Prepare binary structure.
  52359. var buffer = new ArrayBuffer(byteLength);
  52360. var intArrayView = new Int32Array(buffer);
  52361. var floatArrayView = new Float32Array(buffer);
  52362. // Fill header.
  52363. intArrayView[0] = 1; // Version 1.
  52364. intArrayView[1] = size; // CubeMap max mip face size.
  52365. // Fill polynomial information.
  52366. sphericalPolynomial.x.toArray(floatArrayView, 2);
  52367. sphericalPolynomial.y.toArray(floatArrayView, 5);
  52368. sphericalPolynomial.z.toArray(floatArrayView, 8);
  52369. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  52370. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  52371. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  52372. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  52373. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  52374. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  52375. // Fill pixel data.
  52376. intArrayView[29] = mippedData.length; // Number of mip levels.
  52377. var startIndex = 30;
  52378. for (var level = 0; level < mippedData.length; level++) {
  52379. // Fill each pixel of the mip level.
  52380. var faceSize = Math.pow(size >> level, 2) * 3;
  52381. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52382. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  52383. startIndex += faceSize;
  52384. }
  52385. }
  52386. // Callback.
  52387. callback(buffer);
  52388. };
  52389. // Download and process.
  52390. BABYLON.Tools.LoadFile(url, function (data) {
  52391. getDataCallback(data);
  52392. }, null, null, true, onError);
  52393. };
  52394. return HDRCubeTexture;
  52395. }(BABYLON.BaseTexture));
  52396. HDRCubeTexture._facesMapping = [
  52397. "right",
  52398. "up",
  52399. "front",
  52400. "left",
  52401. "down",
  52402. "back"
  52403. ];
  52404. BABYLON.HDRCubeTexture = HDRCubeTexture;
  52405. })(BABYLON || (BABYLON = {}));
  52406. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  52407. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  52408. // Huge respect for a such great lib.
  52409. // Earcut license:
  52410. // Copyright (c) 2016, Mapbox
  52411. //
  52412. // Permission to use, copy, modify, and/or distribute this software for any purpose
  52413. // with or without fee is hereby granted, provided that the above copyright notice
  52414. // and this permission notice appear in all copies.
  52415. //
  52416. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  52417. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  52418. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  52419. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  52420. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  52421. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  52422. // THIS SOFTWARE.
  52423. var Earcut;
  52424. (function (Earcut) {
  52425. /**
  52426. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  52427. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  52428. * @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).
  52429. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  52430. */
  52431. function earcut(data, holeIndices, dim) {
  52432. dim = dim || 2;
  52433. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  52434. if (!outerNode)
  52435. return triangles;
  52436. var minX, minY, maxX, maxY, x, y, size;
  52437. if (hasHoles)
  52438. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  52439. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  52440. if (data.length > 80 * dim) {
  52441. minX = maxX = data[0];
  52442. minY = maxY = data[1];
  52443. for (var i = dim; i < outerLen; i += dim) {
  52444. x = data[i];
  52445. y = data[i + 1];
  52446. if (x < minX)
  52447. minX = x;
  52448. if (y < minY)
  52449. minY = y;
  52450. if (x > maxX)
  52451. maxX = x;
  52452. if (y > maxY)
  52453. maxY = y;
  52454. }
  52455. // minX, minY and size are later used to transform coords into integers for z-order calculation
  52456. size = Math.max(maxX - minX, maxY - minY);
  52457. }
  52458. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  52459. return triangles;
  52460. }
  52461. Earcut.earcut = earcut;
  52462. // create a circular doubly linked list from polygon points in the specified winding order
  52463. function linkedList(data, start, end, dim, clockwise) {
  52464. var i, last;
  52465. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  52466. for (i = start; i < end; i += dim)
  52467. last = insertNode(i, data[i], data[i + 1], last);
  52468. }
  52469. else {
  52470. for (i = end - dim; i >= start; i -= dim)
  52471. last = insertNode(i, data[i], data[i + 1], last);
  52472. }
  52473. if (last && equals(last, last.next)) {
  52474. removeNode(last);
  52475. last = last.next;
  52476. }
  52477. return last;
  52478. }
  52479. // eliminate colinear or duplicate points
  52480. function filterPoints(start, end) {
  52481. if (!start)
  52482. return start;
  52483. if (!end)
  52484. end = start;
  52485. var p = start, again;
  52486. do {
  52487. again = false;
  52488. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  52489. removeNode(p);
  52490. p = end = p.prev;
  52491. if (p === p.next)
  52492. return null;
  52493. again = true;
  52494. }
  52495. else {
  52496. p = p.next;
  52497. }
  52498. } while (again || p !== end);
  52499. return end;
  52500. }
  52501. // main ear slicing loop which triangulates a polygon (given as a linked list)
  52502. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  52503. if (!ear)
  52504. return;
  52505. // interlink polygon nodes in z-order
  52506. if (!pass && size)
  52507. indexCurve(ear, minX, minY, size);
  52508. var stop = ear, prev, next;
  52509. // iterate through ears, slicing them one by one
  52510. while (ear.prev !== ear.next) {
  52511. prev = ear.prev;
  52512. next = ear.next;
  52513. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  52514. // cut off the triangle
  52515. triangles.push(prev.i / dim);
  52516. triangles.push(ear.i / dim);
  52517. triangles.push(next.i / dim);
  52518. removeNode(ear);
  52519. // skipping the next vertice leads to less sliver triangles
  52520. ear = next.next;
  52521. stop = next.next;
  52522. continue;
  52523. }
  52524. ear = next;
  52525. // if we looped through the whole remaining polygon and can't find any more ears
  52526. if (ear === stop) {
  52527. // try filtering points and slicing again
  52528. if (!pass) {
  52529. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  52530. // if this didn't work, try curing all small self-intersections locally
  52531. }
  52532. else if (pass === 1) {
  52533. ear = cureLocalIntersections(ear, triangles, dim);
  52534. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  52535. // as a last resort, try splitting the remaining polygon into two
  52536. }
  52537. else if (pass === 2) {
  52538. splitEarcut(ear, triangles, dim, minX, minY, size);
  52539. }
  52540. break;
  52541. }
  52542. }
  52543. }
  52544. // check whether a polygon node forms a valid ear with adjacent nodes
  52545. function isEar(ear) {
  52546. var a = ear.prev, b = ear, c = ear.next;
  52547. if (area(a, b, c) >= 0)
  52548. return false; // reflex, can't be an ear
  52549. // now make sure we don't have other points inside the potential ear
  52550. var p = ear.next.next;
  52551. while (p !== ear.prev) {
  52552. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  52553. area(p.prev, p, p.next) >= 0)
  52554. return false;
  52555. p = p.next;
  52556. }
  52557. return true;
  52558. }
  52559. function isEarHashed(ear, minX, minY, size) {
  52560. var a = ear.prev, b = ear, c = ear.next;
  52561. if (area(a, b, c) >= 0)
  52562. return false; // reflex, can't be an ear
  52563. // triangle bbox; min & max are calculated like this for speed
  52564. 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);
  52565. // z-order range for the current triangle bbox;
  52566. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  52567. // first look for points inside the triangle in increasing z-order
  52568. var p = ear.nextZ;
  52569. while (p && p.z <= maxZ) {
  52570. if (p !== ear.prev &&
  52571. p !== ear.next &&
  52572. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  52573. area(p.prev, p, p.next) >= 0)
  52574. return false;
  52575. p = p.nextZ;
  52576. }
  52577. // then look for points in decreasing z-order
  52578. p = ear.prevZ;
  52579. while (p && p.z >= minZ) {
  52580. if (p !== ear.prev &&
  52581. p !== ear.next &&
  52582. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  52583. area(p.prev, p, p.next) >= 0)
  52584. return false;
  52585. p = p.prevZ;
  52586. }
  52587. return true;
  52588. }
  52589. // go through all polygon nodes and cure small local self-intersections
  52590. function cureLocalIntersections(start, triangles, dim) {
  52591. var p = start;
  52592. do {
  52593. var a = p.prev, b = p.next.next;
  52594. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  52595. triangles.push(a.i / dim);
  52596. triangles.push(p.i / dim);
  52597. triangles.push(b.i / dim);
  52598. // remove two nodes involved
  52599. removeNode(p);
  52600. removeNode(p.next);
  52601. p = start = b;
  52602. }
  52603. p = p.next;
  52604. } while (p !== start);
  52605. return p;
  52606. }
  52607. // try splitting polygon into two and triangulate them independently
  52608. function splitEarcut(start, triangles, dim, minX, minY, size) {
  52609. // look for a valid diagonal that divides the polygon into two
  52610. var a = start;
  52611. do {
  52612. var b = a.next.next;
  52613. while (b !== a.prev) {
  52614. if (a.i !== b.i && isValidDiagonal(a, b)) {
  52615. // split the polygon in two by the diagonal
  52616. var c = splitPolygon(a, b);
  52617. // filter colinear points around the cuts
  52618. a = filterPoints(a, a.next);
  52619. c = filterPoints(c, c.next);
  52620. // run earcut on each half
  52621. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  52622. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  52623. return;
  52624. }
  52625. b = b.next;
  52626. }
  52627. a = a.next;
  52628. } while (a !== start);
  52629. }
  52630. // link every hole into the outer loop, producing a single-ring polygon without holes
  52631. function eliminateHoles(data, holeIndices, outerNode, dim) {
  52632. var queue = [], i, len, start, end, list;
  52633. for (i = 0, len = holeIndices.length; i < len; i++) {
  52634. start = holeIndices[i] * dim;
  52635. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  52636. list = linkedList(data, start, end, dim, false);
  52637. if (list === list.next)
  52638. list.steiner = true;
  52639. queue.push(getLeftmost(list));
  52640. }
  52641. queue.sort(compareX);
  52642. // process holes from left to right
  52643. for (i = 0; i < queue.length; i++) {
  52644. eliminateHole(queue[i], outerNode);
  52645. outerNode = filterPoints(outerNode, outerNode.next);
  52646. }
  52647. return outerNode;
  52648. }
  52649. function compareX(a, b) {
  52650. return a.x - b.x;
  52651. }
  52652. // find a bridge between vertices that connects hole with an outer ring and and link it
  52653. function eliminateHole(hole, outerNode) {
  52654. outerNode = findHoleBridge(hole, outerNode);
  52655. if (outerNode) {
  52656. var b = splitPolygon(outerNode, hole);
  52657. filterPoints(b, b.next);
  52658. }
  52659. }
  52660. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  52661. function findHoleBridge(hole, outerNode) {
  52662. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  52663. // find a segment intersected by a ray from the hole's leftmost point to the left;
  52664. // segment's endpoint with lesser x will be potential connection point
  52665. do {
  52666. if (hy <= p.y && hy >= p.next.y) {
  52667. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  52668. if (x <= hx && x > qx) {
  52669. qx = x;
  52670. if (x === hx) {
  52671. if (hy === p.y)
  52672. return p;
  52673. if (hy === p.next.y)
  52674. return p.next;
  52675. }
  52676. m = p.x < p.next.x ? p : p.next;
  52677. }
  52678. }
  52679. p = p.next;
  52680. } while (p !== outerNode);
  52681. if (!m)
  52682. return null;
  52683. if (hx === qx)
  52684. return m.prev; // hole touches outer segment; pick lower endpoint
  52685. // look for points inside the triangle of hole point, segment intersection and endpoint;
  52686. // if there are no points found, we have a valid connection;
  52687. // otherwise choose the point of the minimum angle with the ray as connection point
  52688. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  52689. p = m.next;
  52690. while (p !== stop) {
  52691. if (hx >= p.x &&
  52692. p.x >= mx &&
  52693. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  52694. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  52695. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  52696. m = p;
  52697. tanMin = tan;
  52698. }
  52699. }
  52700. p = p.next;
  52701. }
  52702. return m;
  52703. }
  52704. // interlink polygon nodes in z-order
  52705. function indexCurve(start, minX, minY, size) {
  52706. var p = start;
  52707. do {
  52708. if (p.z === null)
  52709. p.z = zOrder(p.x, p.y, minX, minY, size);
  52710. p.prevZ = p.prev;
  52711. p.nextZ = p.next;
  52712. p = p.next;
  52713. } while (p !== start);
  52714. p.prevZ.nextZ = null;
  52715. p.prevZ = null;
  52716. sortLinked(p);
  52717. }
  52718. // Simon Tatham's linked list merge sort algorithm
  52719. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  52720. function sortLinked(list) {
  52721. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  52722. do {
  52723. p = list;
  52724. list = null;
  52725. tail = null;
  52726. numMerges = 0;
  52727. while (p) {
  52728. numMerges++;
  52729. q = p;
  52730. pSize = 0;
  52731. for (i = 0; i < inSize; i++) {
  52732. pSize++;
  52733. q = q.nextZ;
  52734. if (!q)
  52735. break;
  52736. }
  52737. qSize = inSize;
  52738. while (pSize > 0 || (qSize > 0 && q)) {
  52739. if (pSize === 0) {
  52740. e = q;
  52741. q = q.nextZ;
  52742. qSize--;
  52743. }
  52744. else if (qSize === 0 || !q) {
  52745. e = p;
  52746. p = p.nextZ;
  52747. pSize--;
  52748. }
  52749. else if (p.z <= q.z) {
  52750. e = p;
  52751. p = p.nextZ;
  52752. pSize--;
  52753. }
  52754. else {
  52755. e = q;
  52756. q = q.nextZ;
  52757. qSize--;
  52758. }
  52759. if (tail)
  52760. tail.nextZ = e;
  52761. else
  52762. list = e;
  52763. e.prevZ = tail;
  52764. tail = e;
  52765. }
  52766. p = q;
  52767. }
  52768. tail.nextZ = null;
  52769. inSize *= 2;
  52770. } while (numMerges > 1);
  52771. return list;
  52772. }
  52773. // z-order of a point given coords and size of the data bounding box
  52774. function zOrder(x, y, minX, minY, size) {
  52775. // coords are transformed into non-negative 15-bit integer range
  52776. x = 32767 * (x - minX) / size;
  52777. y = 32767 * (y - minY) / size;
  52778. x = (x | (x << 8)) & 0x00FF00FF;
  52779. x = (x | (x << 4)) & 0x0F0F0F0F;
  52780. x = (x | (x << 2)) & 0x33333333;
  52781. x = (x | (x << 1)) & 0x55555555;
  52782. y = (y | (y << 8)) & 0x00FF00FF;
  52783. y = (y | (y << 4)) & 0x0F0F0F0F;
  52784. y = (y | (y << 2)) & 0x33333333;
  52785. y = (y | (y << 1)) & 0x55555555;
  52786. return x | (y << 1);
  52787. }
  52788. // find the leftmost node of a polygon ring
  52789. function getLeftmost(start) {
  52790. var p = start, leftmost = start;
  52791. do {
  52792. if (p.x < leftmost.x)
  52793. leftmost = p;
  52794. p = p.next;
  52795. } while (p !== start);
  52796. return leftmost;
  52797. }
  52798. // check if a point lies within a convex triangle
  52799. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  52800. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  52801. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  52802. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  52803. }
  52804. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  52805. function isValidDiagonal(a, b) {
  52806. return a.next.i !== b.i &&
  52807. a.prev.i !== b.i &&
  52808. !intersectsPolygon(a, b) &&
  52809. locallyInside(a, b) &&
  52810. locallyInside(b, a) &&
  52811. middleInside(a, b);
  52812. }
  52813. // signed area of a triangle
  52814. function area(p, q, r) {
  52815. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  52816. }
  52817. // check if two points are equal
  52818. function equals(p1, p2) {
  52819. return p1.x === p2.x && p1.y === p2.y;
  52820. }
  52821. // check if two segments intersect
  52822. function intersects(p1, q1, p2, q2) {
  52823. if ((equals(p1, q1) && equals(p2, q2)) ||
  52824. (equals(p1, q2) && equals(p2, q1)))
  52825. return true;
  52826. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  52827. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  52828. }
  52829. // check if a polygon diagonal intersects any polygon segments
  52830. function intersectsPolygon(a, b) {
  52831. var p = a;
  52832. do {
  52833. if (p.i !== a.i &&
  52834. p.next.i !== a.i &&
  52835. p.i !== b.i &&
  52836. p.next.i !== b.i &&
  52837. intersects(p, p.next, a, b))
  52838. return true;
  52839. p = p.next;
  52840. } while (p !== a);
  52841. return false;
  52842. }
  52843. // check if a polygon diagonal is locally inside the polygon
  52844. function locallyInside(a, b) {
  52845. return area(a.prev, a, a.next) < 0
  52846. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  52847. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  52848. }
  52849. // check if the middle point of a polygon diagonal is inside the polygon
  52850. function middleInside(a, b) {
  52851. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  52852. do {
  52853. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  52854. inside = !inside;
  52855. p = p.next;
  52856. } while (p !== a);
  52857. return inside;
  52858. }
  52859. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  52860. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  52861. function splitPolygon(a, b) {
  52862. 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;
  52863. a.next = b;
  52864. b.prev = a;
  52865. a2.next = an;
  52866. an.prev = a2;
  52867. b2.next = a2;
  52868. a2.prev = b2;
  52869. bp.next = b2;
  52870. b2.prev = bp;
  52871. return b2;
  52872. }
  52873. // create a node and optionally link it with previous one (in a circular doubly linked list)
  52874. function insertNode(i, x, y, last) {
  52875. var p = new Node(i, x, y);
  52876. if (!last) {
  52877. p.prev = p;
  52878. p.next = p;
  52879. }
  52880. else {
  52881. p.next = last.next;
  52882. p.prev = last;
  52883. last.next.prev = p;
  52884. last.next = p;
  52885. }
  52886. return p;
  52887. }
  52888. function removeNode(p) {
  52889. p.next.prev = p.prev;
  52890. p.prev.next = p.next;
  52891. if (p.prevZ)
  52892. p.prevZ.nextZ = p.nextZ;
  52893. if (p.nextZ)
  52894. p.nextZ.prevZ = p.prevZ;
  52895. }
  52896. function Node(i, x, y) {
  52897. // vertice index in coordinates array
  52898. this.i = i;
  52899. // vertex coordinates
  52900. this.x = x;
  52901. this.y = y;
  52902. // previous and next vertice nodes in a polygon ring
  52903. this.prev = null;
  52904. this.next = null;
  52905. // z-order curve value
  52906. this.z = null;
  52907. // previous and next nodes in z-order
  52908. this.prevZ = null;
  52909. this.nextZ = null;
  52910. // indicates whether this is a steiner point
  52911. this.steiner = false;
  52912. }
  52913. /**
  52914. * return a percentage difference between the polygon area and its triangulation area;
  52915. * used to verify correctness of triangulation
  52916. */
  52917. function deviation(data, holeIndices, dim, triangles) {
  52918. var hasHoles = holeIndices && holeIndices.length;
  52919. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  52920. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  52921. if (hasHoles) {
  52922. for (var i = 0, len = holeIndices.length; i < len; i++) {
  52923. var start = holeIndices[i] * dim;
  52924. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  52925. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  52926. }
  52927. }
  52928. var trianglesArea = 0;
  52929. for (i = 0; i < triangles.length; i += 3) {
  52930. var a = triangles[i] * dim;
  52931. var b = triangles[i + 1] * dim;
  52932. var c = triangles[i + 2] * dim;
  52933. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  52934. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  52935. }
  52936. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  52937. }
  52938. Earcut.deviation = deviation;
  52939. ;
  52940. function signedArea(data, start, end, dim) {
  52941. var sum = 0;
  52942. for (var i = start, j = end - dim; i < end; i += dim) {
  52943. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  52944. j = i;
  52945. }
  52946. return sum;
  52947. }
  52948. /**
  52949. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  52950. */
  52951. function flatten(data) {
  52952. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  52953. for (var i = 0; i < data.length; i++) {
  52954. for (var j = 0; j < data[i].length; j++) {
  52955. for (var d = 0; d < dim; d++)
  52956. result.vertices.push(data[i][j][d]);
  52957. }
  52958. if (i > 0) {
  52959. holeIndex += data[i - 1].length;
  52960. result.holes.push(holeIndex);
  52961. }
  52962. }
  52963. return result;
  52964. }
  52965. Earcut.flatten = flatten;
  52966. ;
  52967. })(Earcut || (Earcut = {}));
  52968. //# sourceMappingURL=babylon.earcut.js.map
  52969. /// <reference path="..\Math\babylon.math.ts" />
  52970. var BABYLON;
  52971. (function (BABYLON) {
  52972. var IndexedVector2 = (function (_super) {
  52973. __extends(IndexedVector2, _super);
  52974. function IndexedVector2(original, index) {
  52975. var _this = _super.call(this, original.x, original.y) || this;
  52976. _this.index = index;
  52977. return _this;
  52978. }
  52979. return IndexedVector2;
  52980. }(BABYLON.Vector2));
  52981. var PolygonPoints = (function () {
  52982. function PolygonPoints() {
  52983. this.elements = new Array();
  52984. }
  52985. PolygonPoints.prototype.add = function (originalPoints) {
  52986. var _this = this;
  52987. var result = new Array();
  52988. originalPoints.forEach(function (point) {
  52989. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  52990. var newPoint = new IndexedVector2(point, _this.elements.length);
  52991. result.push(newPoint);
  52992. _this.elements.push(newPoint);
  52993. }
  52994. });
  52995. return result;
  52996. };
  52997. PolygonPoints.prototype.computeBounds = function () {
  52998. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  52999. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53000. this.elements.forEach(function (point) {
  53001. // x
  53002. if (point.x < lmin.x) {
  53003. lmin.x = point.x;
  53004. }
  53005. else if (point.x > lmax.x) {
  53006. lmax.x = point.x;
  53007. }
  53008. // y
  53009. if (point.y < lmin.y) {
  53010. lmin.y = point.y;
  53011. }
  53012. else if (point.y > lmax.y) {
  53013. lmax.y = point.y;
  53014. }
  53015. });
  53016. return {
  53017. min: lmin,
  53018. max: lmax,
  53019. width: lmax.x - lmin.x,
  53020. height: lmax.y - lmin.y
  53021. };
  53022. };
  53023. return PolygonPoints;
  53024. }());
  53025. var Polygon = (function () {
  53026. function Polygon() {
  53027. }
  53028. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  53029. return [
  53030. new BABYLON.Vector2(xmin, ymin),
  53031. new BABYLON.Vector2(xmax, ymin),
  53032. new BABYLON.Vector2(xmax, ymax),
  53033. new BABYLON.Vector2(xmin, ymax)
  53034. ];
  53035. };
  53036. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  53037. if (cx === void 0) { cx = 0; }
  53038. if (cy === void 0) { cy = 0; }
  53039. if (numberOfSides === void 0) { numberOfSides = 32; }
  53040. var result = new Array();
  53041. var angle = 0;
  53042. var increment = (Math.PI * 2) / numberOfSides;
  53043. for (var i = 0; i < numberOfSides; i++) {
  53044. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  53045. angle -= increment;
  53046. }
  53047. return result;
  53048. };
  53049. Polygon.Parse = function (input) {
  53050. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  53051. var i, result = [];
  53052. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  53053. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  53054. }
  53055. return result;
  53056. };
  53057. Polygon.StartingAt = function (x, y) {
  53058. return BABYLON.Path2.StartingAt(x, y);
  53059. };
  53060. return Polygon;
  53061. }());
  53062. BABYLON.Polygon = Polygon;
  53063. var PolygonMeshBuilder = (function () {
  53064. function PolygonMeshBuilder(name, contours, scene) {
  53065. this._points = new PolygonPoints();
  53066. this._outlinepoints = new PolygonPoints();
  53067. this._holes = [];
  53068. this._epoints = new Array();
  53069. this._eholes = new Array();
  53070. this._name = name;
  53071. this._scene = scene;
  53072. var points;
  53073. if (contours instanceof BABYLON.Path2) {
  53074. points = contours.getPoints();
  53075. }
  53076. else {
  53077. points = contours;
  53078. }
  53079. this._addToepoint(points);
  53080. this._points.add(points);
  53081. this._outlinepoints.add(points);
  53082. }
  53083. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  53084. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  53085. var p = points_1[_i];
  53086. this._epoints.push(p.x, p.y);
  53087. }
  53088. };
  53089. PolygonMeshBuilder.prototype.addHole = function (hole) {
  53090. this._points.add(hole);
  53091. var holepoints = new PolygonPoints();
  53092. holepoints.add(hole);
  53093. this._holes.push(holepoints);
  53094. this._eholes.push(this._epoints.length / 2);
  53095. this._addToepoint(hole);
  53096. return this;
  53097. };
  53098. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  53099. var _this = this;
  53100. if (updatable === void 0) { updatable = false; }
  53101. var result = new BABYLON.Mesh(this._name, this._scene);
  53102. var normals = [];
  53103. var positions = [];
  53104. var uvs = [];
  53105. var bounds = this._points.computeBounds();
  53106. this._points.elements.forEach(function (p) {
  53107. normals.push(0, 1.0, 0);
  53108. positions.push(p.x, 0, p.y);
  53109. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  53110. });
  53111. var indices = [];
  53112. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  53113. for (var i = 0; i < res.length; i++) {
  53114. indices.push(res[i]);
  53115. }
  53116. if (depth > 0) {
  53117. var positionscount = (positions.length / 3); //get the current pointcount
  53118. this._points.elements.forEach(function (p) {
  53119. normals.push(0, -1.0, 0);
  53120. positions.push(p.x, -depth, p.y);
  53121. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  53122. });
  53123. var totalCount = indices.length;
  53124. for (var i = 0; i < totalCount; i += 3) {
  53125. var i0 = indices[i + 0];
  53126. var i1 = indices[i + 1];
  53127. var i2 = indices[i + 2];
  53128. indices.push(i2 + positionscount);
  53129. indices.push(i1 + positionscount);
  53130. indices.push(i0 + positionscount);
  53131. }
  53132. //Add the sides
  53133. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  53134. this._holes.forEach(function (hole) {
  53135. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  53136. });
  53137. }
  53138. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  53139. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  53140. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  53141. result.setIndices(indices);
  53142. return result;
  53143. };
  53144. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  53145. var StartIndex = positions.length / 3;
  53146. var ulength = 0;
  53147. for (var i = 0; i < points.elements.length; i++) {
  53148. var p = points.elements[i];
  53149. var p1;
  53150. if ((i + 1) > points.elements.length - 1) {
  53151. p1 = points.elements[0];
  53152. }
  53153. else {
  53154. p1 = points.elements[i + 1];
  53155. }
  53156. positions.push(p.x, 0, p.y);
  53157. positions.push(p.x, -depth, p.y);
  53158. positions.push(p1.x, 0, p1.y);
  53159. positions.push(p1.x, -depth, p1.y);
  53160. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  53161. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  53162. var v3 = v2.subtract(v1);
  53163. var v4 = new BABYLON.Vector3(0, 1, 0);
  53164. var vn = BABYLON.Vector3.Cross(v3, v4);
  53165. vn = vn.normalize();
  53166. uvs.push(ulength / bounds.width, 0);
  53167. uvs.push(ulength / bounds.width, 1);
  53168. ulength += v3.length();
  53169. uvs.push((ulength / bounds.width), 0);
  53170. uvs.push((ulength / bounds.width), 1);
  53171. if (!flip) {
  53172. normals.push(-vn.x, -vn.y, -vn.z);
  53173. normals.push(-vn.x, -vn.y, -vn.z);
  53174. normals.push(-vn.x, -vn.y, -vn.z);
  53175. normals.push(-vn.x, -vn.y, -vn.z);
  53176. indices.push(StartIndex);
  53177. indices.push(StartIndex + 1);
  53178. indices.push(StartIndex + 2);
  53179. indices.push(StartIndex + 1);
  53180. indices.push(StartIndex + 3);
  53181. indices.push(StartIndex + 2);
  53182. }
  53183. else {
  53184. normals.push(vn.x, vn.y, vn.z);
  53185. normals.push(vn.x, vn.y, vn.z);
  53186. normals.push(vn.x, vn.y, vn.z);
  53187. normals.push(vn.x, vn.y, vn.z);
  53188. indices.push(StartIndex);
  53189. indices.push(StartIndex + 2);
  53190. indices.push(StartIndex + 1);
  53191. indices.push(StartIndex + 1);
  53192. indices.push(StartIndex + 2);
  53193. indices.push(StartIndex + 3);
  53194. }
  53195. StartIndex += 4;
  53196. }
  53197. ;
  53198. };
  53199. return PolygonMeshBuilder;
  53200. }());
  53201. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  53202. })(BABYLON || (BABYLON = {}));
  53203. //# sourceMappingURL=babylon.polygonMesh.js.map
  53204. var BABYLON;
  53205. (function (BABYLON) {
  53206. // Unique ID when we import meshes from Babylon to CSG
  53207. var currentCSGMeshId = 0;
  53208. // # class Vertex
  53209. // Represents a vertex of a polygon. Use your own vertex class instead of this
  53210. // one to provide additional features like texture coordinates and vertex
  53211. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  53212. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  53213. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  53214. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  53215. // is not used anywhere else.
  53216. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  53217. var Vertex = (function () {
  53218. function Vertex(pos, normal, uv) {
  53219. this.pos = pos;
  53220. this.normal = normal;
  53221. this.uv = uv;
  53222. }
  53223. Vertex.prototype.clone = function () {
  53224. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  53225. };
  53226. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  53227. // orientation of a polygon is flipped.
  53228. Vertex.prototype.flip = function () {
  53229. this.normal = this.normal.scale(-1);
  53230. };
  53231. // Create a new vertex between this vertex and `other` by linearly
  53232. // interpolating all properties using a parameter of `t`. Subclasses should
  53233. // override this to interpolate additional properties.
  53234. Vertex.prototype.interpolate = function (other, t) {
  53235. 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));
  53236. };
  53237. return Vertex;
  53238. }());
  53239. // # class Plane
  53240. // Represents a plane in 3D space.
  53241. var Plane = (function () {
  53242. function Plane(normal, w) {
  53243. this.normal = normal;
  53244. this.w = w;
  53245. }
  53246. Plane.FromPoints = function (a, b, c) {
  53247. var v0 = c.subtract(a);
  53248. var v1 = b.subtract(a);
  53249. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  53250. return null;
  53251. }
  53252. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  53253. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  53254. };
  53255. Plane.prototype.clone = function () {
  53256. return new Plane(this.normal.clone(), this.w);
  53257. };
  53258. Plane.prototype.flip = function () {
  53259. this.normal.scaleInPlace(-1);
  53260. this.w = -this.w;
  53261. };
  53262. // Split `polygon` by this plane if needed, then put the polygon or polygon
  53263. // fragments in the appropriate lists. Coplanar polygons go into either
  53264. // `coplanarFront` or `coplanarBack` depending on their orientation with
  53265. // respect to this plane. Polygons in front or in back of this plane go into
  53266. // either `front` or `back`.
  53267. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  53268. var COPLANAR = 0;
  53269. var FRONT = 1;
  53270. var BACK = 2;
  53271. var SPANNING = 3;
  53272. // Classify each point as well as the entire polygon into one of the above
  53273. // four classes.
  53274. var polygonType = 0;
  53275. var types = [];
  53276. var i;
  53277. var t;
  53278. for (i = 0; i < polygon.vertices.length; i++) {
  53279. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  53280. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  53281. polygonType |= type;
  53282. types.push(type);
  53283. }
  53284. // Put the polygon in the correct list, splitting it when necessary.
  53285. switch (polygonType) {
  53286. case COPLANAR:
  53287. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  53288. break;
  53289. case FRONT:
  53290. front.push(polygon);
  53291. break;
  53292. case BACK:
  53293. back.push(polygon);
  53294. break;
  53295. case SPANNING:
  53296. var f = [], b = [];
  53297. for (i = 0; i < polygon.vertices.length; i++) {
  53298. var j = (i + 1) % polygon.vertices.length;
  53299. var ti = types[i], tj = types[j];
  53300. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  53301. if (ti !== BACK)
  53302. f.push(vi);
  53303. if (ti !== FRONT)
  53304. b.push(ti !== BACK ? vi.clone() : vi);
  53305. if ((ti | tj) === SPANNING) {
  53306. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  53307. var v = vi.interpolate(vj, t);
  53308. f.push(v);
  53309. b.push(v.clone());
  53310. }
  53311. }
  53312. var poly;
  53313. if (f.length >= 3) {
  53314. poly = new Polygon(f, polygon.shared);
  53315. if (poly.plane)
  53316. front.push(poly);
  53317. }
  53318. if (b.length >= 3) {
  53319. poly = new Polygon(b, polygon.shared);
  53320. if (poly.plane)
  53321. back.push(poly);
  53322. }
  53323. break;
  53324. }
  53325. };
  53326. return Plane;
  53327. }());
  53328. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  53329. // point is on the plane.
  53330. Plane.EPSILON = 1e-5;
  53331. // # class Polygon
  53332. // Represents a convex polygon. The vertices used to initialize a polygon must
  53333. // be coplanar and form a convex loop.
  53334. //
  53335. // Each convex polygon has a `shared` property, which is shared between all
  53336. // polygons that are clones of each other or were split from the same polygon.
  53337. // This can be used to define per-polygon properties (such as surface color).
  53338. var Polygon = (function () {
  53339. function Polygon(vertices, shared) {
  53340. this.vertices = vertices;
  53341. this.shared = shared;
  53342. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  53343. }
  53344. Polygon.prototype.clone = function () {
  53345. var vertices = this.vertices.map(function (v) { return v.clone(); });
  53346. return new Polygon(vertices, this.shared);
  53347. };
  53348. Polygon.prototype.flip = function () {
  53349. this.vertices.reverse().map(function (v) { v.flip(); });
  53350. this.plane.flip();
  53351. };
  53352. return Polygon;
  53353. }());
  53354. // # class Node
  53355. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  53356. // by picking a polygon to split along. That polygon (and all other coplanar
  53357. // polygons) are added directly to that node and the other polygons are added to
  53358. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  53359. // no distinction between internal and leaf nodes.
  53360. var Node = (function () {
  53361. function Node(polygons) {
  53362. this.plane = null;
  53363. this.front = null;
  53364. this.back = null;
  53365. this.polygons = [];
  53366. if (polygons) {
  53367. this.build(polygons);
  53368. }
  53369. }
  53370. Node.prototype.clone = function () {
  53371. var node = new Node();
  53372. node.plane = this.plane && this.plane.clone();
  53373. node.front = this.front && this.front.clone();
  53374. node.back = this.back && this.back.clone();
  53375. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  53376. return node;
  53377. };
  53378. // Convert solid space to empty space and empty space to solid space.
  53379. Node.prototype.invert = function () {
  53380. for (var i = 0; i < this.polygons.length; i++) {
  53381. this.polygons[i].flip();
  53382. }
  53383. if (this.plane) {
  53384. this.plane.flip();
  53385. }
  53386. if (this.front) {
  53387. this.front.invert();
  53388. }
  53389. if (this.back) {
  53390. this.back.invert();
  53391. }
  53392. var temp = this.front;
  53393. this.front = this.back;
  53394. this.back = temp;
  53395. };
  53396. // Recursively remove all polygons in `polygons` that are inside this BSP
  53397. // tree.
  53398. Node.prototype.clipPolygons = function (polygons) {
  53399. if (!this.plane)
  53400. return polygons.slice();
  53401. var front = [], back = [];
  53402. for (var i = 0; i < polygons.length; i++) {
  53403. this.plane.splitPolygon(polygons[i], front, back, front, back);
  53404. }
  53405. if (this.front) {
  53406. front = this.front.clipPolygons(front);
  53407. }
  53408. if (this.back) {
  53409. back = this.back.clipPolygons(back);
  53410. }
  53411. else {
  53412. back = [];
  53413. }
  53414. return front.concat(back);
  53415. };
  53416. // Remove all polygons in this BSP tree that are inside the other BSP tree
  53417. // `bsp`.
  53418. Node.prototype.clipTo = function (bsp) {
  53419. this.polygons = bsp.clipPolygons(this.polygons);
  53420. if (this.front)
  53421. this.front.clipTo(bsp);
  53422. if (this.back)
  53423. this.back.clipTo(bsp);
  53424. };
  53425. // Return a list of all polygons in this BSP tree.
  53426. Node.prototype.allPolygons = function () {
  53427. var polygons = this.polygons.slice();
  53428. if (this.front)
  53429. polygons = polygons.concat(this.front.allPolygons());
  53430. if (this.back)
  53431. polygons = polygons.concat(this.back.allPolygons());
  53432. return polygons;
  53433. };
  53434. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  53435. // new polygons are filtered down to the bottom of the tree and become new
  53436. // nodes there. Each set of polygons is partitioned using the first polygon
  53437. // (no heuristic is used to pick a good split).
  53438. Node.prototype.build = function (polygons) {
  53439. if (!polygons.length)
  53440. return;
  53441. if (!this.plane)
  53442. this.plane = polygons[0].plane.clone();
  53443. var front = [], back = [];
  53444. for (var i = 0; i < polygons.length; i++) {
  53445. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  53446. }
  53447. if (front.length) {
  53448. if (!this.front)
  53449. this.front = new Node();
  53450. this.front.build(front);
  53451. }
  53452. if (back.length) {
  53453. if (!this.back)
  53454. this.back = new Node();
  53455. this.back.build(back);
  53456. }
  53457. };
  53458. return Node;
  53459. }());
  53460. var CSG = (function () {
  53461. function CSG() {
  53462. this.polygons = new Array();
  53463. }
  53464. // Convert BABYLON.Mesh to BABYLON.CSG
  53465. CSG.FromMesh = function (mesh) {
  53466. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  53467. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  53468. if (mesh instanceof BABYLON.Mesh) {
  53469. mesh.computeWorldMatrix(true);
  53470. matrix = mesh.getWorldMatrix();
  53471. meshPosition = mesh.position.clone();
  53472. meshRotation = mesh.rotation.clone();
  53473. if (mesh.rotationQuaternion) {
  53474. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  53475. }
  53476. meshScaling = mesh.scaling.clone();
  53477. }
  53478. else {
  53479. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  53480. }
  53481. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53482. var subMeshes = mesh.subMeshes;
  53483. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  53484. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  53485. vertices = [];
  53486. for (var j = 0; j < 3; j++) {
  53487. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  53488. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  53489. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  53490. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  53491. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  53492. vertex = new Vertex(position, normal, uv);
  53493. vertices.push(vertex);
  53494. }
  53495. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  53496. // To handle the case of degenerated triangle
  53497. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  53498. if (polygon.plane)
  53499. polygons.push(polygon);
  53500. }
  53501. }
  53502. var csg = CSG.FromPolygons(polygons);
  53503. csg.matrix = matrix;
  53504. csg.position = meshPosition;
  53505. csg.rotation = meshRotation;
  53506. csg.scaling = meshScaling;
  53507. csg.rotationQuaternion = meshRotationQuaternion;
  53508. currentCSGMeshId++;
  53509. return csg;
  53510. };
  53511. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  53512. CSG.FromPolygons = function (polygons) {
  53513. var csg = new CSG();
  53514. csg.polygons = polygons;
  53515. return csg;
  53516. };
  53517. CSG.prototype.clone = function () {
  53518. var csg = new CSG();
  53519. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  53520. csg.copyTransformAttributes(this);
  53521. return csg;
  53522. };
  53523. CSG.prototype.toPolygons = function () {
  53524. return this.polygons;
  53525. };
  53526. CSG.prototype.union = function (csg) {
  53527. var a = new Node(this.clone().polygons);
  53528. var b = new Node(csg.clone().polygons);
  53529. a.clipTo(b);
  53530. b.clipTo(a);
  53531. b.invert();
  53532. b.clipTo(a);
  53533. b.invert();
  53534. a.build(b.allPolygons());
  53535. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  53536. };
  53537. CSG.prototype.unionInPlace = function (csg) {
  53538. var a = new Node(this.polygons);
  53539. var b = new Node(csg.polygons);
  53540. a.clipTo(b);
  53541. b.clipTo(a);
  53542. b.invert();
  53543. b.clipTo(a);
  53544. b.invert();
  53545. a.build(b.allPolygons());
  53546. this.polygons = a.allPolygons();
  53547. };
  53548. CSG.prototype.subtract = function (csg) {
  53549. var a = new Node(this.clone().polygons);
  53550. var b = new Node(csg.clone().polygons);
  53551. a.invert();
  53552. a.clipTo(b);
  53553. b.clipTo(a);
  53554. b.invert();
  53555. b.clipTo(a);
  53556. b.invert();
  53557. a.build(b.allPolygons());
  53558. a.invert();
  53559. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  53560. };
  53561. CSG.prototype.subtractInPlace = function (csg) {
  53562. var a = new Node(this.polygons);
  53563. var b = new Node(csg.polygons);
  53564. a.invert();
  53565. a.clipTo(b);
  53566. b.clipTo(a);
  53567. b.invert();
  53568. b.clipTo(a);
  53569. b.invert();
  53570. a.build(b.allPolygons());
  53571. a.invert();
  53572. this.polygons = a.allPolygons();
  53573. };
  53574. CSG.prototype.intersect = function (csg) {
  53575. var a = new Node(this.clone().polygons);
  53576. var b = new Node(csg.clone().polygons);
  53577. a.invert();
  53578. b.clipTo(a);
  53579. b.invert();
  53580. a.clipTo(b);
  53581. b.clipTo(a);
  53582. a.build(b.allPolygons());
  53583. a.invert();
  53584. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  53585. };
  53586. CSG.prototype.intersectInPlace = function (csg) {
  53587. var a = new Node(this.polygons);
  53588. var b = new Node(csg.polygons);
  53589. a.invert();
  53590. b.clipTo(a);
  53591. b.invert();
  53592. a.clipTo(b);
  53593. b.clipTo(a);
  53594. a.build(b.allPolygons());
  53595. a.invert();
  53596. this.polygons = a.allPolygons();
  53597. };
  53598. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  53599. // not modified.
  53600. CSG.prototype.inverse = function () {
  53601. var csg = this.clone();
  53602. csg.inverseInPlace();
  53603. return csg;
  53604. };
  53605. CSG.prototype.inverseInPlace = function () {
  53606. this.polygons.map(function (p) { p.flip(); });
  53607. };
  53608. // This is used to keep meshes transformations so they can be restored
  53609. // when we build back a Babylon Mesh
  53610. // NB : All CSG operations are performed in world coordinates
  53611. CSG.prototype.copyTransformAttributes = function (csg) {
  53612. this.matrix = csg.matrix;
  53613. this.position = csg.position;
  53614. this.rotation = csg.rotation;
  53615. this.scaling = csg.scaling;
  53616. this.rotationQuaternion = csg.rotationQuaternion;
  53617. return this;
  53618. };
  53619. // Build Raw mesh from CSG
  53620. // Coordinates here are in world space
  53621. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  53622. var matrix = this.matrix.clone();
  53623. matrix.invert();
  53624. 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;
  53625. if (keepSubMeshes) {
  53626. // Sort Polygons, since subMeshes are indices range
  53627. polygons.sort(function (a, b) {
  53628. if (a.shared.meshId === b.shared.meshId) {
  53629. return a.shared.subMeshId - b.shared.subMeshId;
  53630. }
  53631. else {
  53632. return a.shared.meshId - b.shared.meshId;
  53633. }
  53634. });
  53635. }
  53636. for (var i = 0, il = polygons.length; i < il; i++) {
  53637. polygon = polygons[i];
  53638. // Building SubMeshes
  53639. if (!subMesh_dict[polygon.shared.meshId]) {
  53640. subMesh_dict[polygon.shared.meshId] = {};
  53641. }
  53642. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  53643. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  53644. indexStart: +Infinity,
  53645. indexEnd: -Infinity,
  53646. materialIndex: polygon.shared.materialIndex
  53647. };
  53648. }
  53649. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  53650. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  53651. polygonIndices[0] = 0;
  53652. polygonIndices[1] = j - 1;
  53653. polygonIndices[2] = j;
  53654. for (var k = 0; k < 3; k++) {
  53655. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  53656. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  53657. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  53658. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  53659. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  53660. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  53661. // Check if 2 points can be merged
  53662. if (!(typeof vertex_idx !== 'undefined' &&
  53663. normals[vertex_idx * 3] === localNormal.x &&
  53664. normals[vertex_idx * 3 + 1] === localNormal.y &&
  53665. normals[vertex_idx * 3 + 2] === localNormal.z &&
  53666. uvs[vertex_idx * 2] === uv.x &&
  53667. uvs[vertex_idx * 2 + 1] === uv.y)) {
  53668. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  53669. uvs.push(uv.x, uv.y);
  53670. normals.push(normal.x, normal.y, normal.z);
  53671. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  53672. }
  53673. indices.push(vertex_idx);
  53674. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  53675. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  53676. currentIndex++;
  53677. }
  53678. }
  53679. }
  53680. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  53681. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  53682. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  53683. mesh.setIndices(indices);
  53684. if (keepSubMeshes) {
  53685. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  53686. var materialIndexOffset = 0, materialMaxIndex;
  53687. mesh.subMeshes = new Array();
  53688. for (var m in subMesh_dict) {
  53689. materialMaxIndex = -1;
  53690. for (var sm in subMesh_dict[m]) {
  53691. subMesh_obj = subMesh_dict[m][sm];
  53692. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  53693. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  53694. }
  53695. materialIndexOffset += ++materialMaxIndex;
  53696. }
  53697. }
  53698. return mesh;
  53699. };
  53700. // Build Mesh from CSG taking material and transforms into account
  53701. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  53702. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  53703. mesh.material = material;
  53704. mesh.position.copyFrom(this.position);
  53705. mesh.rotation.copyFrom(this.rotation);
  53706. if (this.rotationQuaternion) {
  53707. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  53708. }
  53709. mesh.scaling.copyFrom(this.scaling);
  53710. mesh.computeWorldMatrix(true);
  53711. return mesh;
  53712. };
  53713. return CSG;
  53714. }());
  53715. BABYLON.CSG = CSG;
  53716. })(BABYLON || (BABYLON = {}));
  53717. //# sourceMappingURL=babylon.csg.js.map
  53718. var BABYLON;
  53719. (function (BABYLON) {
  53720. var LensFlare = (function () {
  53721. function LensFlare(size, position, color, imgUrl, system) {
  53722. this.size = size;
  53723. this.position = position;
  53724. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  53725. this.dispose = function () {
  53726. if (this.texture) {
  53727. this.texture.dispose();
  53728. }
  53729. // Remove from scene
  53730. var index = this._system.lensFlares.indexOf(this);
  53731. this._system.lensFlares.splice(index, 1);
  53732. };
  53733. this.color = color || new BABYLON.Color3(1, 1, 1);
  53734. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  53735. this._system = system;
  53736. system.lensFlares.push(this);
  53737. }
  53738. return LensFlare;
  53739. }());
  53740. BABYLON.LensFlare = LensFlare;
  53741. })(BABYLON || (BABYLON = {}));
  53742. //# sourceMappingURL=babylon.lensFlare.js.map
  53743. var BABYLON;
  53744. (function (BABYLON) {
  53745. var LensFlareSystem = (function () {
  53746. function LensFlareSystem(name, emitter, scene) {
  53747. this.name = name;
  53748. this.lensFlares = new Array();
  53749. this.borderLimit = 300;
  53750. this.viewportBorder = 0;
  53751. this.layerMask = 0x0FFFFFFF;
  53752. this._vertexBuffers = {};
  53753. this._isEnabled = true;
  53754. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53755. this._emitter = emitter;
  53756. this.id = name;
  53757. scene.lensFlareSystems.push(this);
  53758. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  53759. var engine = scene.getEngine();
  53760. // VBO
  53761. var vertices = [];
  53762. vertices.push(1, 1);
  53763. vertices.push(-1, 1);
  53764. vertices.push(-1, -1);
  53765. vertices.push(1, -1);
  53766. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  53767. // Indices
  53768. var indices = [];
  53769. indices.push(0);
  53770. indices.push(1);
  53771. indices.push(2);
  53772. indices.push(0);
  53773. indices.push(2);
  53774. indices.push(3);
  53775. this._indexBuffer = engine.createIndexBuffer(indices);
  53776. // Effects
  53777. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  53778. }
  53779. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  53780. get: function () {
  53781. return this._isEnabled;
  53782. },
  53783. set: function (value) {
  53784. this._isEnabled = value;
  53785. },
  53786. enumerable: true,
  53787. configurable: true
  53788. });
  53789. LensFlareSystem.prototype.getScene = function () {
  53790. return this._scene;
  53791. };
  53792. LensFlareSystem.prototype.getEmitter = function () {
  53793. return this._emitter;
  53794. };
  53795. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  53796. this._emitter = newEmitter;
  53797. };
  53798. LensFlareSystem.prototype.getEmitterPosition = function () {
  53799. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  53800. };
  53801. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  53802. var position = this.getEmitterPosition();
  53803. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  53804. this._positionX = position.x;
  53805. this._positionY = position.y;
  53806. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  53807. if (this.viewportBorder > 0) {
  53808. globalViewport.x -= this.viewportBorder;
  53809. globalViewport.y -= this.viewportBorder;
  53810. globalViewport.width += this.viewportBorder * 2;
  53811. globalViewport.height += this.viewportBorder * 2;
  53812. position.x += this.viewportBorder;
  53813. position.y += this.viewportBorder;
  53814. this._positionX += this.viewportBorder;
  53815. this._positionY += this.viewportBorder;
  53816. }
  53817. if (position.z > 0) {
  53818. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  53819. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  53820. return true;
  53821. }
  53822. return true;
  53823. }
  53824. return false;
  53825. };
  53826. LensFlareSystem.prototype._isVisible = function () {
  53827. if (!this._isEnabled) {
  53828. return false;
  53829. }
  53830. var emitterPosition = this.getEmitterPosition();
  53831. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  53832. var distance = direction.length();
  53833. direction.normalize();
  53834. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  53835. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  53836. return !pickInfo.hit || pickInfo.distance > distance;
  53837. };
  53838. LensFlareSystem.prototype.render = function () {
  53839. if (!this._effect.isReady())
  53840. return false;
  53841. var engine = this._scene.getEngine();
  53842. var viewport = this._scene.activeCamera.viewport;
  53843. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  53844. // Position
  53845. if (!this.computeEffectivePosition(globalViewport)) {
  53846. return false;
  53847. }
  53848. // Visibility
  53849. if (!this._isVisible()) {
  53850. return false;
  53851. }
  53852. // Intensity
  53853. var awayX;
  53854. var awayY;
  53855. if (this._positionX < this.borderLimit + globalViewport.x) {
  53856. awayX = this.borderLimit + globalViewport.x - this._positionX;
  53857. }
  53858. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  53859. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  53860. }
  53861. else {
  53862. awayX = 0;
  53863. }
  53864. if (this._positionY < this.borderLimit + globalViewport.y) {
  53865. awayY = this.borderLimit + globalViewport.y - this._positionY;
  53866. }
  53867. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  53868. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  53869. }
  53870. else {
  53871. awayY = 0;
  53872. }
  53873. var away = (awayX > awayY) ? awayX : awayY;
  53874. away -= this.viewportBorder;
  53875. if (away > this.borderLimit) {
  53876. away = this.borderLimit;
  53877. }
  53878. var intensity = 1.0 - (away / this.borderLimit);
  53879. if (intensity < 0) {
  53880. return false;
  53881. }
  53882. if (intensity > 1.0) {
  53883. intensity = 1.0;
  53884. }
  53885. if (this.viewportBorder > 0) {
  53886. globalViewport.x += this.viewportBorder;
  53887. globalViewport.y += this.viewportBorder;
  53888. globalViewport.width -= this.viewportBorder * 2;
  53889. globalViewport.height -= this.viewportBorder * 2;
  53890. this._positionX -= this.viewportBorder;
  53891. this._positionY -= this.viewportBorder;
  53892. }
  53893. // Position
  53894. var centerX = globalViewport.x + globalViewport.width / 2;
  53895. var centerY = globalViewport.y + globalViewport.height / 2;
  53896. var distX = centerX - this._positionX;
  53897. var distY = centerY - this._positionY;
  53898. // Effects
  53899. engine.enableEffect(this._effect);
  53900. engine.setState(false);
  53901. engine.setDepthBuffer(false);
  53902. // VBOs
  53903. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  53904. // Flares
  53905. for (var index = 0; index < this.lensFlares.length; index++) {
  53906. var flare = this.lensFlares[index];
  53907. engine.setAlphaMode(flare.alphaMode);
  53908. var x = centerX - (distX * flare.position);
  53909. var y = centerY - (distY * flare.position);
  53910. var cw = flare.size;
  53911. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  53912. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  53913. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  53914. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  53915. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  53916. // Texture
  53917. this._effect.setTexture("textureSampler", flare.texture);
  53918. // Color
  53919. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  53920. // Draw order
  53921. engine.draw(true, 0, 6);
  53922. }
  53923. engine.setDepthBuffer(true);
  53924. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53925. return true;
  53926. };
  53927. LensFlareSystem.prototype.dispose = function () {
  53928. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  53929. if (vertexBuffer) {
  53930. vertexBuffer.dispose();
  53931. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  53932. }
  53933. if (this._indexBuffer) {
  53934. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53935. this._indexBuffer = null;
  53936. }
  53937. while (this.lensFlares.length) {
  53938. this.lensFlares[0].dispose();
  53939. }
  53940. // Remove from scene
  53941. var index = this._scene.lensFlareSystems.indexOf(this);
  53942. this._scene.lensFlareSystems.splice(index, 1);
  53943. };
  53944. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  53945. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  53946. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  53947. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  53948. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  53949. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  53950. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  53951. var parsedFlare = parsedLensFlareSystem.flares[index];
  53952. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  53953. }
  53954. return lensFlareSystem;
  53955. };
  53956. LensFlareSystem.prototype.serialize = function () {
  53957. var serializationObject = {};
  53958. serializationObject.id = this.id;
  53959. serializationObject.name = this.name;
  53960. serializationObject.emitterId = this.getEmitter().id;
  53961. serializationObject.borderLimit = this.borderLimit;
  53962. serializationObject.flares = [];
  53963. for (var index = 0; index < this.lensFlares.length; index++) {
  53964. var flare = this.lensFlares[index];
  53965. serializationObject.flares.push({
  53966. size: flare.size,
  53967. position: flare.position,
  53968. color: flare.color.asArray(),
  53969. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  53970. });
  53971. }
  53972. return serializationObject;
  53973. };
  53974. return LensFlareSystem;
  53975. }());
  53976. BABYLON.LensFlareSystem = LensFlareSystem;
  53977. })(BABYLON || (BABYLON = {}));
  53978. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  53979. var BABYLON;
  53980. (function (BABYLON) {
  53981. /**
  53982. * This is a holder class for the physics joint created by the physics plugin.
  53983. * It holds a set of functions to control the underlying joint.
  53984. */
  53985. var PhysicsJoint = (function () {
  53986. function PhysicsJoint(type, jointData) {
  53987. this.type = type;
  53988. this.jointData = jointData;
  53989. jointData.nativeParams = jointData.nativeParams || {};
  53990. }
  53991. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  53992. get: function () {
  53993. return this._physicsJoint;
  53994. },
  53995. set: function (newJoint) {
  53996. if (this._physicsJoint) {
  53997. //remove from the wolrd
  53998. }
  53999. this._physicsJoint = newJoint;
  54000. },
  54001. enumerable: true,
  54002. configurable: true
  54003. });
  54004. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  54005. set: function (physicsPlugin) {
  54006. this._physicsPlugin = physicsPlugin;
  54007. },
  54008. enumerable: true,
  54009. configurable: true
  54010. });
  54011. /**
  54012. * Execute a function that is physics-plugin specific.
  54013. * @param {Function} func the function that will be executed.
  54014. * It accepts two parameters: the physics world and the physics joint.
  54015. */
  54016. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  54017. func(this._physicsPlugin.world, this._physicsJoint);
  54018. };
  54019. return PhysicsJoint;
  54020. }());
  54021. //TODO check if the native joints are the same
  54022. //Joint Types
  54023. PhysicsJoint.DistanceJoint = 0;
  54024. PhysicsJoint.HingeJoint = 1;
  54025. PhysicsJoint.BallAndSocketJoint = 2;
  54026. PhysicsJoint.WheelJoint = 3;
  54027. PhysicsJoint.SliderJoint = 4;
  54028. //OIMO
  54029. PhysicsJoint.PrismaticJoint = 5;
  54030. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  54031. PhysicsJoint.UniversalJoint = 6;
  54032. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  54033. //Cannon
  54034. //Similar to a Ball-Joint. Different in params
  54035. PhysicsJoint.PointToPointJoint = 8;
  54036. //Cannon only at the moment
  54037. PhysicsJoint.SpringJoint = 9;
  54038. PhysicsJoint.LockJoint = 10;
  54039. BABYLON.PhysicsJoint = PhysicsJoint;
  54040. /**
  54041. * A class representing a physics distance joint.
  54042. */
  54043. var DistanceJoint = (function (_super) {
  54044. __extends(DistanceJoint, _super);
  54045. function DistanceJoint(jointData) {
  54046. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  54047. }
  54048. /**
  54049. * Update the predefined distance.
  54050. */
  54051. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  54052. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  54053. };
  54054. return DistanceJoint;
  54055. }(PhysicsJoint));
  54056. BABYLON.DistanceJoint = DistanceJoint;
  54057. var MotorEnabledJoint = (function (_super) {
  54058. __extends(MotorEnabledJoint, _super);
  54059. function MotorEnabledJoint(type, jointData) {
  54060. return _super.call(this, type, jointData) || this;
  54061. }
  54062. /**
  54063. * Set the motor values.
  54064. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54065. * @param {number} force the force to apply
  54066. * @param {number} maxForce max force for this motor.
  54067. */
  54068. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  54069. this._physicsPlugin.setMotor(this, force, maxForce);
  54070. };
  54071. /**
  54072. * Set the motor's limits.
  54073. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54074. */
  54075. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  54076. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  54077. };
  54078. return MotorEnabledJoint;
  54079. }(PhysicsJoint));
  54080. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  54081. /**
  54082. * This class represents a single hinge physics joint
  54083. */
  54084. var HingeJoint = (function (_super) {
  54085. __extends(HingeJoint, _super);
  54086. function HingeJoint(jointData) {
  54087. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  54088. }
  54089. /**
  54090. * Set the motor values.
  54091. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54092. * @param {number} force the force to apply
  54093. * @param {number} maxForce max force for this motor.
  54094. */
  54095. HingeJoint.prototype.setMotor = function (force, maxForce) {
  54096. this._physicsPlugin.setMotor(this, force, maxForce);
  54097. };
  54098. /**
  54099. * Set the motor's limits.
  54100. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54101. */
  54102. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  54103. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  54104. };
  54105. return HingeJoint;
  54106. }(MotorEnabledJoint));
  54107. BABYLON.HingeJoint = HingeJoint;
  54108. /**
  54109. * This class represents a dual hinge physics joint (same as wheel joint)
  54110. */
  54111. var Hinge2Joint = (function (_super) {
  54112. __extends(Hinge2Joint, _super);
  54113. function Hinge2Joint(jointData) {
  54114. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  54115. }
  54116. /**
  54117. * Set the motor values.
  54118. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54119. * @param {number} force the force to apply
  54120. * @param {number} maxForce max force for this motor.
  54121. * @param {motorIndex} the motor's index, 0 or 1.
  54122. */
  54123. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  54124. if (motorIndex === void 0) { motorIndex = 0; }
  54125. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  54126. };
  54127. /**
  54128. * Set the motor limits.
  54129. * Attention, this function is plugin specific. Engines won't react 100% the same.
  54130. * @param {number} upperLimit the upper limit
  54131. * @param {number} lowerLimit lower limit
  54132. * @param {motorIndex} the motor's index, 0 or 1.
  54133. */
  54134. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  54135. if (motorIndex === void 0) { motorIndex = 0; }
  54136. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  54137. };
  54138. return Hinge2Joint;
  54139. }(MotorEnabledJoint));
  54140. BABYLON.Hinge2Joint = Hinge2Joint;
  54141. })(BABYLON || (BABYLON = {}));
  54142. //# sourceMappingURL=babylon.physicsJoint.js.map
  54143. var BABYLON;
  54144. (function (BABYLON) {
  54145. var PhysicsImpostor = (function () {
  54146. function PhysicsImpostor(object, type, _options, _scene) {
  54147. if (_options === void 0) { _options = { mass: 0 }; }
  54148. var _this = this;
  54149. this.object = object;
  54150. this.type = type;
  54151. this._options = _options;
  54152. this._scene = _scene;
  54153. this._bodyUpdateRequired = false;
  54154. this._onBeforePhysicsStepCallbacks = new Array();
  54155. this._onAfterPhysicsStepCallbacks = new Array();
  54156. this._onPhysicsCollideCallbacks = [];
  54157. this._deltaPosition = BABYLON.Vector3.Zero();
  54158. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  54159. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  54160. /**
  54161. * this function is executed by the physics engine.
  54162. */
  54163. this.beforeStep = function () {
  54164. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  54165. //conjugate deltaRotation
  54166. if (_this._deltaRotationConjugated) {
  54167. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  54168. }
  54169. else {
  54170. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  54171. }
  54172. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  54173. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  54174. func(_this);
  54175. });
  54176. };
  54177. /**
  54178. * this function is executed by the physics engine.
  54179. */
  54180. this.afterStep = function () {
  54181. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  54182. func(_this);
  54183. });
  54184. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  54185. _this.object.position.addInPlace(_this._deltaPosition);
  54186. if (_this._deltaRotation) {
  54187. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  54188. }
  54189. };
  54190. /**
  54191. * Legacy collision detection event support
  54192. */
  54193. this.onCollideEvent = null;
  54194. //event and body object due to cannon's event-based architecture.
  54195. this.onCollide = function (e) {
  54196. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  54197. return;
  54198. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  54199. if (otherImpostor) {
  54200. // Legacy collision detection event support
  54201. if (_this.onCollideEvent) {
  54202. _this.onCollideEvent(_this, otherImpostor);
  54203. }
  54204. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  54205. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  54206. }).forEach(function (obj) {
  54207. obj.callback(_this, otherImpostor);
  54208. });
  54209. }
  54210. };
  54211. //sanity check!
  54212. if (!this.object) {
  54213. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  54214. return;
  54215. }
  54216. //legacy support for old syntax.
  54217. if (!this._scene && object.getScene) {
  54218. this._scene = object.getScene();
  54219. }
  54220. this._physicsEngine = this._scene.getPhysicsEngine();
  54221. if (!this._physicsEngine) {
  54222. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  54223. }
  54224. else {
  54225. //set the object's quaternion, if not set
  54226. if (!this.object.rotationQuaternion) {
  54227. if (this.object.rotation) {
  54228. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  54229. }
  54230. else {
  54231. this.object.rotationQuaternion = new BABYLON.Quaternion();
  54232. }
  54233. }
  54234. //default options params
  54235. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  54236. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  54237. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  54238. this._joints = [];
  54239. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  54240. if (!this.object.parent) {
  54241. this._init();
  54242. }
  54243. }
  54244. }
  54245. /**
  54246. * This function will completly initialize this impostor.
  54247. * It will create a new body - but only if this mesh has no parent.
  54248. * If it has, this impostor will not be used other than to define the impostor
  54249. * of the child mesh.
  54250. */
  54251. PhysicsImpostor.prototype._init = function () {
  54252. this._physicsEngine.removeImpostor(this);
  54253. this.physicsBody = null;
  54254. this._parent = this._parent || this._getPhysicsParent();
  54255. if (!this.parent) {
  54256. this._physicsEngine.addImpostor(this);
  54257. }
  54258. };
  54259. PhysicsImpostor.prototype._getPhysicsParent = function () {
  54260. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  54261. var parentMesh = this.object.parent;
  54262. return parentMesh.physicsImpostor;
  54263. }
  54264. return;
  54265. };
  54266. /**
  54267. * Should a new body be generated.
  54268. */
  54269. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  54270. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  54271. };
  54272. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  54273. this.forceUpdate();
  54274. };
  54275. /**
  54276. * Force a regeneration of this or the parent's impostor's body.
  54277. * Use under cautious - This will remove all joints already implemented.
  54278. */
  54279. PhysicsImpostor.prototype.forceUpdate = function () {
  54280. this._init();
  54281. if (this.parent) {
  54282. this.parent.forceUpdate();
  54283. }
  54284. };
  54285. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  54286. /*public get mesh(): AbstractMesh {
  54287. return this._mesh;
  54288. }*/
  54289. /**
  54290. * Gets the body that holds this impostor. Either its own, or its parent.
  54291. */
  54292. get: function () {
  54293. return this._parent ? this._parent.physicsBody : this._physicsBody;
  54294. },
  54295. /**
  54296. * Set the physics body. Used mainly by the physics engine/plugin
  54297. */
  54298. set: function (physicsBody) {
  54299. if (this._physicsBody) {
  54300. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  54301. }
  54302. this._physicsBody = physicsBody;
  54303. this.resetUpdateFlags();
  54304. },
  54305. enumerable: true,
  54306. configurable: true
  54307. });
  54308. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  54309. get: function () {
  54310. return this._parent;
  54311. },
  54312. set: function (value) {
  54313. this._parent = value;
  54314. },
  54315. enumerable: true,
  54316. configurable: true
  54317. });
  54318. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  54319. this._bodyUpdateRequired = false;
  54320. };
  54321. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  54322. if (this.object.getBoundingInfo) {
  54323. var q = this.object.rotationQuaternion;
  54324. //reset rotation
  54325. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  54326. //calculate the world matrix with no rotation
  54327. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  54328. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  54329. //bring back the rotation
  54330. this.object.rotationQuaternion = q;
  54331. //calculate the world matrix with the new rotation
  54332. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  54333. return size;
  54334. }
  54335. else {
  54336. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  54337. }
  54338. };
  54339. PhysicsImpostor.prototype.getObjectCenter = function () {
  54340. if (this.object.getBoundingInfo) {
  54341. return this.object.getBoundingInfo().boundingBox.centerWorld;
  54342. }
  54343. else {
  54344. return this.object.position;
  54345. }
  54346. };
  54347. /**
  54348. * Get a specific parametes from the options parameter.
  54349. */
  54350. PhysicsImpostor.prototype.getParam = function (paramName) {
  54351. return this._options[paramName];
  54352. };
  54353. /**
  54354. * Sets a specific parameter in the options given to the physics plugin
  54355. */
  54356. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  54357. this._options[paramName] = value;
  54358. this._bodyUpdateRequired = true;
  54359. };
  54360. /**
  54361. * Specifically change the body's mass option. Won't recreate the physics body object
  54362. */
  54363. PhysicsImpostor.prototype.setMass = function (mass) {
  54364. if (this.getParam("mass") !== mass) {
  54365. this.setParam("mass", mass);
  54366. }
  54367. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  54368. };
  54369. PhysicsImpostor.prototype.getLinearVelocity = function () {
  54370. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  54371. };
  54372. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  54373. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  54374. };
  54375. PhysicsImpostor.prototype.getAngularVelocity = function () {
  54376. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  54377. };
  54378. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  54379. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  54380. };
  54381. /**
  54382. * Execute a function with the physics plugin native code.
  54383. * Provide a function the will have two variables - the world object and the physics body object.
  54384. */
  54385. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  54386. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  54387. };
  54388. /**
  54389. * Register a function that will be executed before the physics world is stepping forward.
  54390. */
  54391. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  54392. this._onBeforePhysicsStepCallbacks.push(func);
  54393. };
  54394. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  54395. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  54396. if (index > -1) {
  54397. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  54398. }
  54399. else {
  54400. BABYLON.Tools.Warn("Function to remove was not found");
  54401. }
  54402. };
  54403. /**
  54404. * Register a function that will be executed after the physics step
  54405. */
  54406. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  54407. this._onAfterPhysicsStepCallbacks.push(func);
  54408. };
  54409. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  54410. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  54411. if (index > -1) {
  54412. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  54413. }
  54414. else {
  54415. BABYLON.Tools.Warn("Function to remove was not found");
  54416. }
  54417. };
  54418. /**
  54419. * register a function that will be executed when this impostor collides against a different body.
  54420. */
  54421. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  54422. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  54423. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  54424. };
  54425. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  54426. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  54427. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  54428. if (index > -1) {
  54429. this._onPhysicsCollideCallbacks.splice(index, 1);
  54430. }
  54431. else {
  54432. BABYLON.Tools.Warn("Function to remove was not found");
  54433. }
  54434. };
  54435. /**
  54436. * Apply a force
  54437. */
  54438. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  54439. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  54440. };
  54441. /**
  54442. * Apply an impulse
  54443. */
  54444. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  54445. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  54446. };
  54447. /**
  54448. * A help function to create a joint.
  54449. */
  54450. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  54451. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  54452. this.addJoint(otherImpostor, joint);
  54453. };
  54454. /**
  54455. * Add a joint to this impostor with a different impostor.
  54456. */
  54457. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  54458. this._joints.push({
  54459. otherImpostor: otherImpostor,
  54460. joint: joint
  54461. });
  54462. this._physicsEngine.addJoint(this, otherImpostor, joint);
  54463. };
  54464. /**
  54465. * Will keep this body still, in a sleep mode.
  54466. */
  54467. PhysicsImpostor.prototype.sleep = function () {
  54468. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  54469. };
  54470. /**
  54471. * Wake the body up.
  54472. */
  54473. PhysicsImpostor.prototype.wakeUp = function () {
  54474. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  54475. };
  54476. PhysicsImpostor.prototype.clone = function (newObject) {
  54477. if (!newObject)
  54478. return null;
  54479. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  54480. };
  54481. PhysicsImpostor.prototype.dispose = function () {
  54482. var _this = this;
  54483. //no dispose if no physics engine is available.
  54484. if (!this._physicsEngine) {
  54485. return;
  54486. }
  54487. this._joints.forEach(function (j) {
  54488. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  54489. });
  54490. //dispose the physics body
  54491. this._physicsEngine.removeImpostor(this);
  54492. if (this.parent) {
  54493. this.parent.forceUpdate();
  54494. }
  54495. else {
  54496. /*this._object.getChildMeshes().forEach(function(mesh) {
  54497. if (mesh.physicsImpostor) {
  54498. if (disposeChildren) {
  54499. mesh.physicsImpostor.dispose();
  54500. mesh.physicsImpostor = null;
  54501. }
  54502. }
  54503. })*/
  54504. }
  54505. };
  54506. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  54507. this._deltaPosition.copyFrom(position);
  54508. };
  54509. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  54510. if (!this._deltaRotation) {
  54511. this._deltaRotation = new BABYLON.Quaternion();
  54512. }
  54513. this._deltaRotation.copyFrom(rotation);
  54514. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  54515. };
  54516. return PhysicsImpostor;
  54517. }());
  54518. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  54519. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  54520. //Impostor types
  54521. PhysicsImpostor.NoImpostor = 0;
  54522. PhysicsImpostor.SphereImpostor = 1;
  54523. PhysicsImpostor.BoxImpostor = 2;
  54524. PhysicsImpostor.PlaneImpostor = 3;
  54525. PhysicsImpostor.MeshImpostor = 4;
  54526. PhysicsImpostor.CylinderImpostor = 7;
  54527. PhysicsImpostor.ParticleImpostor = 8;
  54528. PhysicsImpostor.HeightmapImpostor = 9;
  54529. BABYLON.PhysicsImpostor = PhysicsImpostor;
  54530. })(BABYLON || (BABYLON = {}));
  54531. //# sourceMappingURL=babylon.physicsImpostor.js.map
  54532. var BABYLON;
  54533. (function (BABYLON) {
  54534. var PhysicsEngine = (function () {
  54535. function PhysicsEngine(gravity, _physicsPlugin) {
  54536. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  54537. this._physicsPlugin = _physicsPlugin;
  54538. //new methods and parameters
  54539. this._impostors = [];
  54540. this._joints = [];
  54541. if (!this._physicsPlugin.isSupported()) {
  54542. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  54543. + "Please make sure it is included.");
  54544. }
  54545. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  54546. this.setGravity(gravity);
  54547. this.setTimeStep();
  54548. }
  54549. PhysicsEngine.prototype.setGravity = function (gravity) {
  54550. this.gravity = gravity;
  54551. this._physicsPlugin.setGravity(this.gravity);
  54552. };
  54553. /**
  54554. * Set the time step of the physics engine.
  54555. * default is 1/60.
  54556. * To slow it down, enter 1/600 for example.
  54557. * To speed it up, 1/30
  54558. * @param {number} newTimeStep the new timestep to apply to this world.
  54559. */
  54560. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  54561. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  54562. this._physicsPlugin.setTimeStep(newTimeStep);
  54563. };
  54564. PhysicsEngine.prototype.dispose = function () {
  54565. this._impostors.forEach(function (impostor) {
  54566. impostor.dispose();
  54567. });
  54568. this._physicsPlugin.dispose();
  54569. };
  54570. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  54571. return this._physicsPlugin.name;
  54572. };
  54573. /**
  54574. * Adding a new impostor for the impostor tracking.
  54575. * This will be done by the impostor itself.
  54576. * @param {PhysicsImpostor} impostor the impostor to add
  54577. */
  54578. PhysicsEngine.prototype.addImpostor = function (impostor) {
  54579. impostor.uniqueId = this._impostors.push(impostor);
  54580. //if no parent, generate the body
  54581. if (!impostor.parent) {
  54582. this._physicsPlugin.generatePhysicsBody(impostor);
  54583. }
  54584. };
  54585. /**
  54586. * Remove an impostor from the engine.
  54587. * This impostor and its mesh will not longer be updated by the physics engine.
  54588. * @param {PhysicsImpostor} impostor the impostor to remove
  54589. */
  54590. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  54591. var index = this._impostors.indexOf(impostor);
  54592. if (index > -1) {
  54593. var removed = this._impostors.splice(index, 1);
  54594. //Is it needed?
  54595. if (removed.length) {
  54596. //this will also remove it from the world.
  54597. removed[0].physicsBody = null;
  54598. }
  54599. }
  54600. };
  54601. /**
  54602. * Add a joint to the physics engine
  54603. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  54604. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  54605. * @param {PhysicsJoint} the joint that will connect both impostors.
  54606. */
  54607. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  54608. var impostorJoint = {
  54609. mainImpostor: mainImpostor,
  54610. connectedImpostor: connectedImpostor,
  54611. joint: joint
  54612. };
  54613. joint.physicsPlugin = this._physicsPlugin;
  54614. this._joints.push(impostorJoint);
  54615. this._physicsPlugin.generateJoint(impostorJoint);
  54616. };
  54617. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  54618. var matchingJoints = this._joints.filter(function (impostorJoint) {
  54619. return (impostorJoint.connectedImpostor === connectedImpostor
  54620. && impostorJoint.joint === joint
  54621. && impostorJoint.mainImpostor === mainImpostor);
  54622. });
  54623. if (matchingJoints.length) {
  54624. this._physicsPlugin.removeJoint(matchingJoints[0]);
  54625. //TODO remove it from the list as well
  54626. }
  54627. };
  54628. /**
  54629. * Called by the scene. no need to call it.
  54630. */
  54631. PhysicsEngine.prototype._step = function (delta) {
  54632. var _this = this;
  54633. //check if any mesh has no body / requires an update
  54634. this._impostors.forEach(function (impostor) {
  54635. if (impostor.isBodyInitRequired()) {
  54636. _this._physicsPlugin.generatePhysicsBody(impostor);
  54637. }
  54638. });
  54639. if (delta > 0.1) {
  54640. delta = 0.1;
  54641. }
  54642. else if (delta <= 0) {
  54643. delta = 1.0 / 60.0;
  54644. }
  54645. this._physicsPlugin.executeStep(delta, this._impostors);
  54646. };
  54647. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  54648. return this._physicsPlugin;
  54649. };
  54650. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  54651. for (var i = 0; i < this._impostors.length; ++i) {
  54652. if (this._impostors[i].object === object) {
  54653. return this._impostors[i];
  54654. }
  54655. }
  54656. };
  54657. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  54658. for (var i = 0; i < this._impostors.length; ++i) {
  54659. if (this._impostors[i].physicsBody === body) {
  54660. return this._impostors[i];
  54661. }
  54662. }
  54663. };
  54664. return PhysicsEngine;
  54665. }());
  54666. // Statics
  54667. PhysicsEngine.Epsilon = 0.001;
  54668. BABYLON.PhysicsEngine = PhysicsEngine;
  54669. })(BABYLON || (BABYLON = {}));
  54670. //# sourceMappingURL=babylon.physicsEngine.js.map
  54671. var BABYLON;
  54672. (function (BABYLON) {
  54673. var CannonJSPlugin = (function () {
  54674. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  54675. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  54676. if (iterations === void 0) { iterations = 10; }
  54677. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  54678. this.name = "CannonJSPlugin";
  54679. this._physicsMaterials = [];
  54680. this._fixedTimeStep = 1 / 60;
  54681. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  54682. this._currentCollisionGroup = 2;
  54683. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  54684. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  54685. this._tmpPosition = BABYLON.Vector3.Zero();
  54686. this._tmpQuaternion = new BABYLON.Quaternion();
  54687. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  54688. this._tmpDeltaRotation = new BABYLON.Quaternion();
  54689. this._tmpUnityRotation = new BABYLON.Quaternion();
  54690. if (!this.isSupported()) {
  54691. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  54692. return;
  54693. }
  54694. this.world = new CANNON.World();
  54695. this.world.broadphase = new CANNON.NaiveBroadphase();
  54696. this.world.solver.iterations = iterations;
  54697. }
  54698. CannonJSPlugin.prototype.setGravity = function (gravity) {
  54699. this.world.gravity.copy(gravity);
  54700. };
  54701. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  54702. this._fixedTimeStep = timeStep;
  54703. };
  54704. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  54705. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  54706. };
  54707. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  54708. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  54709. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  54710. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  54711. };
  54712. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  54713. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  54714. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  54715. impostor.physicsBody.applyForce(impulse, worldPoint);
  54716. };
  54717. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  54718. //parent-child relationship. Does this impostor has a parent impostor?
  54719. if (impostor.parent) {
  54720. if (impostor.physicsBody) {
  54721. this.removePhysicsBody(impostor);
  54722. //TODO is that needed?
  54723. impostor.forceUpdate();
  54724. }
  54725. return;
  54726. }
  54727. //should a new body be created for this impostor?
  54728. if (impostor.isBodyInitRequired()) {
  54729. var shape = this._createShape(impostor);
  54730. //unregister events, if body is being changed
  54731. var oldBody = impostor.physicsBody;
  54732. if (oldBody) {
  54733. this.removePhysicsBody(impostor);
  54734. }
  54735. //create the body and material
  54736. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  54737. var bodyCreationObject = {
  54738. mass: impostor.getParam("mass"),
  54739. material: material
  54740. };
  54741. // A simple extend, in case native options were used.
  54742. var nativeOptions = impostor.getParam("nativeOptions");
  54743. for (var key in nativeOptions) {
  54744. if (nativeOptions.hasOwnProperty(key)) {
  54745. bodyCreationObject[key] = nativeOptions[key];
  54746. }
  54747. }
  54748. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  54749. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  54750. this.world.addEventListener("preStep", impostor.beforeStep);
  54751. this.world.addEventListener("postStep", impostor.afterStep);
  54752. impostor.physicsBody.addShape(shape);
  54753. this.world.add(impostor.physicsBody);
  54754. //try to keep the body moving in the right direction by taking old properties.
  54755. //Should be tested!
  54756. if (oldBody) {
  54757. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  54758. impostor.physicsBody[param].copy(oldBody[param]);
  54759. });
  54760. }
  54761. this._processChildMeshes(impostor);
  54762. }
  54763. //now update the body's transformation
  54764. this._updatePhysicsBodyTransformation(impostor);
  54765. };
  54766. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  54767. var _this = this;
  54768. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  54769. if (meshChildren.length) {
  54770. var processMesh = function (localPosition, mesh) {
  54771. var childImpostor = mesh.getPhysicsImpostor();
  54772. if (childImpostor) {
  54773. var parent = childImpostor.parent;
  54774. if (parent !== mainImpostor) {
  54775. var localPosition = mesh.position;
  54776. if (childImpostor.physicsBody) {
  54777. _this.removePhysicsBody(childImpostor);
  54778. childImpostor.physicsBody = null;
  54779. }
  54780. childImpostor.parent = mainImpostor;
  54781. childImpostor.resetUpdateFlags();
  54782. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  54783. //Add the mass of the children.
  54784. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  54785. }
  54786. }
  54787. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  54788. };
  54789. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  54790. }
  54791. };
  54792. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  54793. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  54794. this.world.removeEventListener("preStep", impostor.beforeStep);
  54795. this.world.removeEventListener("postStep", impostor.afterStep);
  54796. this.world.remove(impostor.physicsBody);
  54797. };
  54798. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  54799. var mainBody = impostorJoint.mainImpostor.physicsBody;
  54800. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  54801. if (!mainBody || !connectedBody) {
  54802. return;
  54803. }
  54804. var constraint;
  54805. var jointData = impostorJoint.joint.jointData;
  54806. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  54807. var constraintData = {
  54808. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  54809. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  54810. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  54811. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  54812. maxForce: jointData.nativeParams.maxForce,
  54813. collideConnected: !!jointData.collision
  54814. };
  54815. switch (impostorJoint.joint.type) {
  54816. case BABYLON.PhysicsJoint.HingeJoint:
  54817. case BABYLON.PhysicsJoint.Hinge2Joint:
  54818. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  54819. break;
  54820. case BABYLON.PhysicsJoint.DistanceJoint:
  54821. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  54822. break;
  54823. case BABYLON.PhysicsJoint.SpringJoint:
  54824. var springData = jointData;
  54825. constraint = new CANNON.Spring(mainBody, connectedBody, {
  54826. restLength: springData.length,
  54827. stiffness: springData.stiffness,
  54828. damping: springData.damping,
  54829. localAnchorA: constraintData.pivotA,
  54830. localAnchorB: constraintData.pivotB
  54831. });
  54832. break;
  54833. case BABYLON.PhysicsJoint.LockJoint:
  54834. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  54835. break;
  54836. case BABYLON.PhysicsJoint.PointToPointJoint:
  54837. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  54838. default:
  54839. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  54840. break;
  54841. }
  54842. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  54843. constraint.collideConnected = !!jointData.collision;
  54844. impostorJoint.joint.physicsJoint = constraint;
  54845. //don't add spring as constraint, as it is not one.
  54846. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  54847. this.world.addConstraint(constraint);
  54848. }
  54849. else {
  54850. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  54851. constraint.applyForce();
  54852. });
  54853. }
  54854. };
  54855. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  54856. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  54857. };
  54858. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  54859. var index;
  54860. var mat;
  54861. for (index = 0; index < this._physicsMaterials.length; index++) {
  54862. mat = this._physicsMaterials[index];
  54863. if (mat.friction === friction && mat.restitution === restitution) {
  54864. return mat;
  54865. }
  54866. }
  54867. var currentMat = new CANNON.Material(name);
  54868. currentMat.friction = friction;
  54869. currentMat.restitution = restitution;
  54870. this._physicsMaterials.push(currentMat);
  54871. return currentMat;
  54872. };
  54873. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  54874. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  54875. };
  54876. CannonJSPlugin.prototype._createShape = function (impostor) {
  54877. var object = impostor.object;
  54878. var returnValue;
  54879. var extendSize = impostor.getObjectExtendSize();
  54880. switch (impostor.type) {
  54881. case BABYLON.PhysicsImpostor.SphereImpostor:
  54882. var radiusX = extendSize.x;
  54883. var radiusY = extendSize.y;
  54884. var radiusZ = extendSize.z;
  54885. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  54886. break;
  54887. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  54888. case BABYLON.PhysicsImpostor.CylinderImpostor:
  54889. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  54890. break;
  54891. case BABYLON.PhysicsImpostor.BoxImpostor:
  54892. var box = extendSize.scale(0.5);
  54893. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  54894. break;
  54895. case BABYLON.PhysicsImpostor.PlaneImpostor:
  54896. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  54897. returnValue = new CANNON.Plane();
  54898. break;
  54899. case BABYLON.PhysicsImpostor.MeshImpostor:
  54900. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  54901. var rawFaces = object.getIndices ? object.getIndices() : [];
  54902. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  54903. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  54904. break;
  54905. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  54906. returnValue = this._createHeightmap(object);
  54907. break;
  54908. case BABYLON.PhysicsImpostor.ParticleImpostor:
  54909. returnValue = new CANNON.Particle();
  54910. break;
  54911. }
  54912. return returnValue;
  54913. };
  54914. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  54915. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54916. var matrix = [];
  54917. //For now pointDepth will not be used and will be automatically calculated.
  54918. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  54919. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  54920. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  54921. var elementSize = dim * 2 / arraySize;
  54922. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  54923. for (var i = 0; i < pos.length; i = i + 3) {
  54924. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  54925. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  54926. var y = pos[i + 1] + minY;
  54927. if (!matrix[x]) {
  54928. matrix[x] = [];
  54929. }
  54930. if (!matrix[x][z]) {
  54931. matrix[x][z] = y;
  54932. }
  54933. matrix[x][z] = Math.max(y, matrix[x][z]);
  54934. }
  54935. for (var x = 0; x <= arraySize; ++x) {
  54936. if (!matrix[x]) {
  54937. var loc = 1;
  54938. while (!matrix[(x + loc) % arraySize]) {
  54939. loc++;
  54940. }
  54941. matrix[x] = matrix[(x + loc) % arraySize].slice();
  54942. //console.log("missing x", x);
  54943. }
  54944. for (var z = 0; z <= arraySize; ++z) {
  54945. if (!matrix[x][z]) {
  54946. var loc = 1;
  54947. var newValue;
  54948. while (newValue === undefined) {
  54949. newValue = matrix[x][(z + loc++) % arraySize];
  54950. }
  54951. matrix[x][z] = newValue;
  54952. }
  54953. }
  54954. }
  54955. var shape = new CANNON.Heightfield(matrix, {
  54956. elementSize: elementSize
  54957. });
  54958. //For future reference, needed for body transformation
  54959. shape.minY = minY;
  54960. return shape;
  54961. };
  54962. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  54963. var object = impostor.object;
  54964. //make sure it is updated...
  54965. object.computeWorldMatrix && object.computeWorldMatrix(true);
  54966. // The delta between the mesh position and the mesh bounding box center
  54967. var center = impostor.getObjectCenter();
  54968. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  54969. this._tmpPosition.copyFrom(center);
  54970. var quaternion = object.rotationQuaternion;
  54971. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  54972. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  54973. //-90 DEG in X, precalculated
  54974. quaternion = quaternion.multiply(this._minus90X);
  54975. //Invert! (Precalculated, 90 deg in X)
  54976. //No need to clone. this will never change.
  54977. impostor.setDeltaRotation(this._plus90X);
  54978. }
  54979. //If it is a heightfield, if should be centered.
  54980. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  54981. var mesh = object;
  54982. //calculate the correct body position:
  54983. var rotationQuaternion = mesh.rotationQuaternion;
  54984. mesh.rotationQuaternion = this._tmpUnityRotation;
  54985. mesh.computeWorldMatrix(true);
  54986. //get original center with no rotation
  54987. var c = center.clone();
  54988. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  54989. //rotation is back
  54990. mesh.rotationQuaternion = rotationQuaternion;
  54991. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  54992. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  54993. mesh.setPivotMatrix(p);
  54994. mesh.computeWorldMatrix(true);
  54995. //calculate the translation
  54996. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  54997. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  54998. //add it inverted to the delta
  54999. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  55000. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  55001. mesh.setPivotMatrix(oldPivot);
  55002. mesh.computeWorldMatrix(true);
  55003. }
  55004. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  55005. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  55006. this._tmpPosition.copyFrom(object.position);
  55007. }
  55008. impostor.setDeltaPosition(this._tmpDeltaPosition);
  55009. //Now update the impostor object
  55010. impostor.physicsBody.position.copy(this._tmpPosition);
  55011. impostor.physicsBody.quaternion.copy(quaternion);
  55012. };
  55013. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  55014. impostor.object.position.copyFrom(impostor.physicsBody.position);
  55015. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  55016. };
  55017. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  55018. impostor.physicsBody.position.copy(newPosition);
  55019. impostor.physicsBody.quaternion.copy(newRotation);
  55020. };
  55021. CannonJSPlugin.prototype.isSupported = function () {
  55022. return window.CANNON !== undefined;
  55023. };
  55024. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  55025. impostor.physicsBody.velocity.copy(velocity);
  55026. };
  55027. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  55028. impostor.physicsBody.angularVelocity.copy(velocity);
  55029. };
  55030. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  55031. var v = impostor.physicsBody.velocity;
  55032. if (!v)
  55033. return null;
  55034. return new BABYLON.Vector3(v.x, v.y, v.z);
  55035. };
  55036. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  55037. var v = impostor.physicsBody.angularVelocity;
  55038. if (!v)
  55039. return null;
  55040. return new BABYLON.Vector3(v.x, v.y, v.z);
  55041. };
  55042. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  55043. impostor.physicsBody.mass = mass;
  55044. impostor.physicsBody.updateMassProperties();
  55045. };
  55046. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  55047. impostor.physicsBody.sleep();
  55048. };
  55049. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  55050. impostor.physicsBody.wakeUp();
  55051. };
  55052. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  55053. joint.physicsJoint.distance = maxDistance;
  55054. };
  55055. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  55056. if (!motorIndex) {
  55057. joint.physicsJoint.enableMotor();
  55058. }
  55059. };
  55060. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  55061. if (!motorIndex) {
  55062. joint.physicsJoint.disableMotor();
  55063. }
  55064. };
  55065. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  55066. if (!motorIndex) {
  55067. joint.physicsJoint.enableMotor();
  55068. joint.physicsJoint.setMotorSpeed(speed);
  55069. if (maxForce) {
  55070. this.setLimit(joint, maxForce);
  55071. }
  55072. }
  55073. };
  55074. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  55075. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  55076. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  55077. };
  55078. CannonJSPlugin.prototype.dispose = function () {
  55079. //nothing to do, actually.
  55080. };
  55081. return CannonJSPlugin;
  55082. }());
  55083. BABYLON.CannonJSPlugin = CannonJSPlugin;
  55084. })(BABYLON || (BABYLON = {}));
  55085. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  55086. var BABYLON;
  55087. (function (BABYLON) {
  55088. var OimoJSPlugin = (function () {
  55089. function OimoJSPlugin(iterations) {
  55090. this.name = "OimoJSPlugin";
  55091. this._tmpImpostorsArray = [];
  55092. this._tmpPositionVector = BABYLON.Vector3.Zero();
  55093. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  55094. this.world.worldscale(1);
  55095. this.world.clear();
  55096. //making sure no stats are calculated
  55097. this.world.isNoStat = true;
  55098. }
  55099. OimoJSPlugin.prototype.setGravity = function (gravity) {
  55100. this.world.gravity.copy(gravity);
  55101. };
  55102. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  55103. this.world.timeStep = timeStep;
  55104. };
  55105. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  55106. var _this = this;
  55107. impostors.forEach(function (impostor) {
  55108. impostor.beforeStep();
  55109. });
  55110. this.world.step();
  55111. impostors.forEach(function (impostor) {
  55112. impostor.afterStep();
  55113. //update the ordered impostors array
  55114. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  55115. });
  55116. //check for collisions
  55117. var contact = this.world.contacts;
  55118. while (contact !== null) {
  55119. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  55120. contact = contact.next;
  55121. continue;
  55122. }
  55123. //is this body colliding with any other? get the impostor
  55124. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  55125. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  55126. if (!mainImpostor || !collidingImpostor) {
  55127. contact = contact.next;
  55128. continue;
  55129. }
  55130. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  55131. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  55132. contact = contact.next;
  55133. }
  55134. };
  55135. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  55136. var mass = impostor.physicsBody.massInfo.mass;
  55137. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  55138. };
  55139. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  55140. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  55141. this.applyImpulse(impostor, force, contactPoint);
  55142. };
  55143. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  55144. var _this = this;
  55145. //parent-child relationship. Does this impostor has a parent impostor?
  55146. if (impostor.parent) {
  55147. if (impostor.physicsBody) {
  55148. this.removePhysicsBody(impostor);
  55149. //TODO is that needed?
  55150. impostor.forceUpdate();
  55151. }
  55152. return;
  55153. }
  55154. if (impostor.isBodyInitRequired()) {
  55155. var bodyConfig = {
  55156. name: impostor.uniqueId,
  55157. //Oimo must have mass, also for static objects.
  55158. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  55159. size: [],
  55160. type: [],
  55161. pos: [],
  55162. rot: [],
  55163. move: impostor.getParam("mass") !== 0,
  55164. //Supporting older versions of Oimo
  55165. world: this.world
  55166. };
  55167. var impostors = [impostor];
  55168. var addToArray = function (parent) {
  55169. if (!parent.getChildMeshes)
  55170. return;
  55171. parent.getChildMeshes().forEach(function (m) {
  55172. if (m.physicsImpostor) {
  55173. impostors.push(m.physicsImpostor);
  55174. m.physicsImpostor._init();
  55175. }
  55176. });
  55177. };
  55178. addToArray(impostor.object);
  55179. var checkWithEpsilon_1 = function (value) {
  55180. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  55181. };
  55182. impostors.forEach(function (i) {
  55183. //get the correct bounding box
  55184. var oldQuaternion = i.object.rotationQuaternion;
  55185. var rot = new OIMO.Euler().setFromQuaternion({
  55186. x: impostor.object.rotationQuaternion.x,
  55187. y: impostor.object.rotationQuaternion.y,
  55188. z: impostor.object.rotationQuaternion.z,
  55189. s: impostor.object.rotationQuaternion.w
  55190. });
  55191. var extendSize = i.getObjectExtendSize();
  55192. if (i === impostor) {
  55193. var center = impostor.getObjectCenter();
  55194. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  55195. //Can also use Array.prototype.push.apply
  55196. bodyConfig.pos.push(center.x);
  55197. bodyConfig.pos.push(center.y);
  55198. bodyConfig.pos.push(center.z);
  55199. //tmp solution
  55200. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  55201. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  55202. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  55203. }
  55204. else {
  55205. bodyConfig.pos.push(i.object.position.x);
  55206. bodyConfig.pos.push(i.object.position.y);
  55207. bodyConfig.pos.push(i.object.position.z);
  55208. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  55209. bodyConfig.rot.push(0);
  55210. bodyConfig.rot.push(0);
  55211. bodyConfig.rot.push(0);
  55212. }
  55213. // register mesh
  55214. switch (i.type) {
  55215. case BABYLON.PhysicsImpostor.ParticleImpostor:
  55216. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  55217. case BABYLON.PhysicsImpostor.SphereImpostor:
  55218. var radiusX = extendSize.x;
  55219. var radiusY = extendSize.y;
  55220. var radiusZ = extendSize.z;
  55221. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  55222. bodyConfig.type.push('sphere');
  55223. //due to the way oimo works with compounds, add 3 times
  55224. bodyConfig.size.push(size);
  55225. bodyConfig.size.push(size);
  55226. bodyConfig.size.push(size);
  55227. break;
  55228. case BABYLON.PhysicsImpostor.CylinderImpostor:
  55229. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  55230. var sizeY = checkWithEpsilon_1(extendSize.y);
  55231. bodyConfig.type.push('cylinder');
  55232. bodyConfig.size.push(sizeX);
  55233. bodyConfig.size.push(sizeY);
  55234. //due to the way oimo works with compounds, add one more value.
  55235. bodyConfig.size.push(sizeY);
  55236. break;
  55237. case BABYLON.PhysicsImpostor.PlaneImpostor:
  55238. case BABYLON.PhysicsImpostor.BoxImpostor:
  55239. default:
  55240. var sizeX = checkWithEpsilon_1(extendSize.x);
  55241. var sizeY = checkWithEpsilon_1(extendSize.y);
  55242. var sizeZ = checkWithEpsilon_1(extendSize.z);
  55243. bodyConfig.type.push('box');
  55244. bodyConfig.size.push(sizeX);
  55245. bodyConfig.size.push(sizeY);
  55246. bodyConfig.size.push(sizeZ);
  55247. break;
  55248. }
  55249. //actually not needed, but hey...
  55250. i.object.rotationQuaternion = oldQuaternion;
  55251. });
  55252. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  55253. }
  55254. else {
  55255. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  55256. }
  55257. impostor.setDeltaPosition(this._tmpPositionVector);
  55258. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  55259. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  55260. };
  55261. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  55262. //impostor.physicsBody.dispose();
  55263. //Same as : (older oimo versions)
  55264. this.world.removeRigidBody(impostor.physicsBody);
  55265. };
  55266. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  55267. var mainBody = impostorJoint.mainImpostor.physicsBody;
  55268. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  55269. if (!mainBody || !connectedBody) {
  55270. return;
  55271. }
  55272. var jointData = impostorJoint.joint.jointData;
  55273. var options = jointData.nativeParams || {};
  55274. var type;
  55275. var nativeJointData = {
  55276. body1: mainBody,
  55277. body2: connectedBody,
  55278. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  55279. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  55280. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  55281. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  55282. min: options.min,
  55283. max: options.max,
  55284. collision: options.collision || jointData.collision,
  55285. spring: options.spring,
  55286. //supporting older version of Oimo
  55287. world: this.world
  55288. };
  55289. switch (impostorJoint.joint.type) {
  55290. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  55291. type = "jointBall";
  55292. break;
  55293. case BABYLON.PhysicsJoint.SpringJoint:
  55294. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  55295. var springData = jointData;
  55296. nativeJointData.min = springData.length || nativeJointData.min;
  55297. //Max should also be set, just make sure it is at least min
  55298. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  55299. case BABYLON.PhysicsJoint.DistanceJoint:
  55300. type = "jointDistance";
  55301. nativeJointData.max = jointData.maxDistance;
  55302. break;
  55303. case BABYLON.PhysicsJoint.PrismaticJoint:
  55304. type = "jointPrisme";
  55305. break;
  55306. case BABYLON.PhysicsJoint.SliderJoint:
  55307. type = "jointSlide";
  55308. break;
  55309. case BABYLON.PhysicsJoint.WheelJoint:
  55310. type = "jointWheel";
  55311. break;
  55312. case BABYLON.PhysicsJoint.HingeJoint:
  55313. default:
  55314. type = "jointHinge";
  55315. break;
  55316. }
  55317. nativeJointData.type = type;
  55318. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  55319. };
  55320. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  55321. //Bug in Oimo prevents us from disposing a joint in the playground
  55322. //joint.joint.physicsJoint.dispose();
  55323. //So we will bruteforce it!
  55324. try {
  55325. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  55326. }
  55327. catch (e) {
  55328. BABYLON.Tools.Warn(e);
  55329. }
  55330. };
  55331. OimoJSPlugin.prototype.isSupported = function () {
  55332. return OIMO !== undefined;
  55333. };
  55334. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  55335. if (!impostor.physicsBody.sleeping) {
  55336. //TODO check that
  55337. if (impostor.physicsBody.shapes.next) {
  55338. var parentShape = this._getLastShape(impostor.physicsBody);
  55339. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  55340. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  55341. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  55342. }
  55343. else {
  55344. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  55345. }
  55346. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  55347. impostor.object.rotationQuaternion.normalize();
  55348. }
  55349. };
  55350. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  55351. var body = impostor.physicsBody;
  55352. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  55353. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  55354. body.syncShapes();
  55355. body.awake();
  55356. };
  55357. OimoJSPlugin.prototype._getLastShape = function (body) {
  55358. var lastShape = body.shapes;
  55359. while (lastShape.next) {
  55360. lastShape = lastShape.next;
  55361. }
  55362. return lastShape;
  55363. };
  55364. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  55365. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  55366. };
  55367. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  55368. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  55369. };
  55370. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  55371. var v = impostor.physicsBody.linearVelocity;
  55372. if (!v)
  55373. return null;
  55374. return new BABYLON.Vector3(v.x, v.y, v.z);
  55375. };
  55376. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  55377. var v = impostor.physicsBody.angularVelocity;
  55378. if (!v)
  55379. return null;
  55380. return new BABYLON.Vector3(v.x, v.y, v.z);
  55381. };
  55382. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  55383. var staticBody = mass === 0;
  55384. //this will actually set the body's density and not its mass.
  55385. //But this is how oimo treats the mass variable.
  55386. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  55387. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  55388. };
  55389. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  55390. impostor.physicsBody.sleep();
  55391. };
  55392. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  55393. impostor.physicsBody.awake();
  55394. };
  55395. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  55396. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  55397. if (minDistance !== void 0) {
  55398. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  55399. }
  55400. };
  55401. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  55402. //TODO separate rotational and transational motors.
  55403. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  55404. if (motor) {
  55405. motor.setMotor(speed, maxForce);
  55406. }
  55407. };
  55408. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  55409. //TODO separate rotational and transational motors.
  55410. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  55411. if (motor) {
  55412. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  55413. }
  55414. };
  55415. OimoJSPlugin.prototype.dispose = function () {
  55416. this.world.clear();
  55417. };
  55418. return OimoJSPlugin;
  55419. }());
  55420. BABYLON.OimoJSPlugin = OimoJSPlugin;
  55421. })(BABYLON || (BABYLON = {}));
  55422. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  55423. var BABYLON;
  55424. (function (BABYLON) {
  55425. var Internals;
  55426. (function (Internals) {
  55427. /*
  55428. * Based on jsTGALoader - Javascript loader for TGA file
  55429. * By Vincent Thibault
  55430. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  55431. */
  55432. var TGATools = (function () {
  55433. function TGATools() {
  55434. }
  55435. TGATools.GetTGAHeader = function (data) {
  55436. var offset = 0;
  55437. var header = {
  55438. id_length: data[offset++],
  55439. colormap_type: data[offset++],
  55440. image_type: data[offset++],
  55441. colormap_index: data[offset++] | data[offset++] << 8,
  55442. colormap_length: data[offset++] | data[offset++] << 8,
  55443. colormap_size: data[offset++],
  55444. origin: [
  55445. data[offset++] | data[offset++] << 8,
  55446. data[offset++] | data[offset++] << 8
  55447. ],
  55448. width: data[offset++] | data[offset++] << 8,
  55449. height: data[offset++] | data[offset++] << 8,
  55450. pixel_size: data[offset++],
  55451. flags: data[offset++]
  55452. };
  55453. return header;
  55454. };
  55455. TGATools.UploadContent = function (gl, data) {
  55456. // Not enough data to contain header ?
  55457. if (data.length < 19) {
  55458. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  55459. return;
  55460. }
  55461. // Read Header
  55462. var offset = 18;
  55463. var header = TGATools.GetTGAHeader(data);
  55464. // Assume it's a valid Targa file.
  55465. if (header.id_length + offset > data.length) {
  55466. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  55467. return;
  55468. }
  55469. // Skip not needed data
  55470. offset += header.id_length;
  55471. var use_rle = false;
  55472. var use_pal = false;
  55473. var use_rgb = false;
  55474. var use_grey = false;
  55475. // Get some informations.
  55476. switch (header.image_type) {
  55477. case TGATools._TYPE_RLE_INDEXED:
  55478. use_rle = true;
  55479. case TGATools._TYPE_INDEXED:
  55480. use_pal = true;
  55481. break;
  55482. case TGATools._TYPE_RLE_RGB:
  55483. use_rle = true;
  55484. case TGATools._TYPE_RGB:
  55485. use_rgb = true;
  55486. break;
  55487. case TGATools._TYPE_RLE_GREY:
  55488. use_rle = true;
  55489. case TGATools._TYPE_GREY:
  55490. use_grey = true;
  55491. break;
  55492. }
  55493. var pixel_data;
  55494. var numAlphaBits = header.flags & 0xf;
  55495. var pixel_size = header.pixel_size >> 3;
  55496. var pixel_total = header.width * header.height * pixel_size;
  55497. // Read palettes
  55498. var palettes;
  55499. if (use_pal) {
  55500. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  55501. }
  55502. // Read LRE
  55503. if (use_rle) {
  55504. pixel_data = new Uint8Array(pixel_total);
  55505. var c, count, i;
  55506. var localOffset = 0;
  55507. var pixels = new Uint8Array(pixel_size);
  55508. while (offset < pixel_total && localOffset < pixel_total) {
  55509. c = data[offset++];
  55510. count = (c & 0x7f) + 1;
  55511. // RLE pixels
  55512. if (c & 0x80) {
  55513. // Bind pixel tmp array
  55514. for (i = 0; i < pixel_size; ++i) {
  55515. pixels[i] = data[offset++];
  55516. }
  55517. // Copy pixel array
  55518. for (i = 0; i < count; ++i) {
  55519. pixel_data.set(pixels, localOffset + i * pixel_size);
  55520. }
  55521. localOffset += pixel_size * count;
  55522. }
  55523. else {
  55524. count *= pixel_size;
  55525. for (i = 0; i < count; ++i) {
  55526. pixel_data[localOffset + i] = data[offset++];
  55527. }
  55528. localOffset += count;
  55529. }
  55530. }
  55531. }
  55532. else {
  55533. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  55534. }
  55535. // Load to texture
  55536. var x_start, y_start, x_step, y_step, y_end, x_end;
  55537. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  55538. default:
  55539. case TGATools._ORIGIN_UL:
  55540. x_start = 0;
  55541. x_step = 1;
  55542. x_end = header.width;
  55543. y_start = 0;
  55544. y_step = 1;
  55545. y_end = header.height;
  55546. break;
  55547. case TGATools._ORIGIN_BL:
  55548. x_start = 0;
  55549. x_step = 1;
  55550. x_end = header.width;
  55551. y_start = header.height - 1;
  55552. y_step = -1;
  55553. y_end = -1;
  55554. break;
  55555. case TGATools._ORIGIN_UR:
  55556. x_start = header.width - 1;
  55557. x_step = -1;
  55558. x_end = -1;
  55559. y_start = 0;
  55560. y_step = 1;
  55561. y_end = header.height;
  55562. break;
  55563. case TGATools._ORIGIN_BR:
  55564. x_start = header.width - 1;
  55565. x_step = -1;
  55566. x_end = -1;
  55567. y_start = header.height - 1;
  55568. y_step = -1;
  55569. y_end = -1;
  55570. break;
  55571. }
  55572. // Load the specify method
  55573. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  55574. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  55575. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  55576. };
  55577. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55578. var image = pixel_data, colormap = palettes;
  55579. var width = header.width, height = header.height;
  55580. var color, i = 0, x, y;
  55581. var imageData = new Uint8Array(width * height * 4);
  55582. for (y = y_start; y !== y_end; y += y_step) {
  55583. for (x = x_start; x !== x_end; x += x_step, i++) {
  55584. color = image[i];
  55585. imageData[(x + width * y) * 4 + 3] = 255;
  55586. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  55587. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  55588. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  55589. }
  55590. }
  55591. return imageData;
  55592. };
  55593. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55594. var image = pixel_data;
  55595. var width = header.width, height = header.height;
  55596. var color, i = 0, x, y;
  55597. var imageData = new Uint8Array(width * height * 4);
  55598. for (y = y_start; y !== y_end; y += y_step) {
  55599. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  55600. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  55601. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  55602. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  55603. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  55604. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  55605. }
  55606. }
  55607. return imageData;
  55608. };
  55609. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55610. var image = pixel_data;
  55611. var width = header.width, height = header.height;
  55612. var i = 0, x, y;
  55613. var imageData = new Uint8Array(width * height * 4);
  55614. for (y = y_start; y !== y_end; y += y_step) {
  55615. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  55616. imageData[(x + width * y) * 4 + 3] = 255;
  55617. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  55618. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  55619. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  55620. }
  55621. }
  55622. return imageData;
  55623. };
  55624. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55625. var image = pixel_data;
  55626. var width = header.width, height = header.height;
  55627. var i = 0, x, y;
  55628. var imageData = new Uint8Array(width * height * 4);
  55629. for (y = y_start; y !== y_end; y += y_step) {
  55630. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  55631. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  55632. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  55633. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  55634. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  55635. }
  55636. }
  55637. return imageData;
  55638. };
  55639. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55640. var image = pixel_data;
  55641. var width = header.width, height = header.height;
  55642. var color, i = 0, x, y;
  55643. var imageData = new Uint8Array(width * height * 4);
  55644. for (y = y_start; y !== y_end; y += y_step) {
  55645. for (x = x_start; x !== x_end; x += x_step, i++) {
  55646. color = image[i];
  55647. imageData[(x + width * y) * 4 + 0] = color;
  55648. imageData[(x + width * y) * 4 + 1] = color;
  55649. imageData[(x + width * y) * 4 + 2] = color;
  55650. imageData[(x + width * y) * 4 + 3] = 255;
  55651. }
  55652. }
  55653. return imageData;
  55654. };
  55655. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  55656. var image = pixel_data;
  55657. var width = header.width, height = header.height;
  55658. var i = 0, x, y;
  55659. var imageData = new Uint8Array(width * height * 4);
  55660. for (y = y_start; y !== y_end; y += y_step) {
  55661. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  55662. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  55663. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  55664. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  55665. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  55666. }
  55667. }
  55668. return imageData;
  55669. };
  55670. return TGATools;
  55671. }());
  55672. TGATools._TYPE_NO_DATA = 0;
  55673. TGATools._TYPE_INDEXED = 1;
  55674. TGATools._TYPE_RGB = 2;
  55675. TGATools._TYPE_GREY = 3;
  55676. TGATools._TYPE_RLE_INDEXED = 9;
  55677. TGATools._TYPE_RLE_RGB = 10;
  55678. TGATools._TYPE_RLE_GREY = 11;
  55679. TGATools._ORIGIN_MASK = 0x30;
  55680. TGATools._ORIGIN_SHIFT = 0x04;
  55681. TGATools._ORIGIN_BL = 0x00;
  55682. TGATools._ORIGIN_BR = 0x01;
  55683. TGATools._ORIGIN_UL = 0x02;
  55684. TGATools._ORIGIN_UR = 0x03;
  55685. Internals.TGATools = TGATools;
  55686. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55687. })(BABYLON || (BABYLON = {}));
  55688. //# sourceMappingURL=babylon.tga.js.map
  55689. var BABYLON;
  55690. (function (BABYLON) {
  55691. var Internals;
  55692. (function (Internals) {
  55693. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  55694. // All values and structures referenced from:
  55695. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  55696. var DDS_MAGIC = 0x20534444;
  55697. 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;
  55698. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  55699. 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;
  55700. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  55701. function FourCCToInt32(value) {
  55702. return value.charCodeAt(0) +
  55703. (value.charCodeAt(1) << 8) +
  55704. (value.charCodeAt(2) << 16) +
  55705. (value.charCodeAt(3) << 24);
  55706. }
  55707. function Int32ToFourCC(value) {
  55708. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  55709. }
  55710. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  55711. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  55712. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  55713. var headerLengthInt = 31; // The header length in 32 bit ints
  55714. // Offsets into the header array
  55715. var off_magic = 0;
  55716. var off_size = 1;
  55717. var off_flags = 2;
  55718. var off_height = 3;
  55719. var off_width = 4;
  55720. var off_mipmapCount = 7;
  55721. var off_pfFlags = 20;
  55722. var off_pfFourCC = 21;
  55723. var off_RGBbpp = 22;
  55724. var off_RMask = 23;
  55725. var off_GMask = 24;
  55726. var off_BMask = 25;
  55727. var off_AMask = 26;
  55728. var off_caps1 = 27;
  55729. var off_caps2 = 28;
  55730. ;
  55731. var DDSTools = (function () {
  55732. function DDSTools() {
  55733. }
  55734. DDSTools.GetDDSInfo = function (arrayBuffer) {
  55735. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  55736. var mipmapCount = 1;
  55737. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  55738. mipmapCount = Math.max(1, header[off_mipmapCount]);
  55739. }
  55740. return {
  55741. width: header[off_width],
  55742. height: header[off_height],
  55743. mipmapCount: mipmapCount,
  55744. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  55745. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  55746. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  55747. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  55748. };
  55749. };
  55750. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  55751. var byteArray = new Uint8Array(dataLength);
  55752. var srcData = new Uint8Array(arrayBuffer);
  55753. var index = 0;
  55754. for (var y = height - 1; y >= 0; y--) {
  55755. for (var x = 0; x < width; x++) {
  55756. var srcPos = dataOffset + (x + y * width) * 4;
  55757. byteArray[index + 2] = srcData[srcPos];
  55758. byteArray[index + 1] = srcData[srcPos + 1];
  55759. byteArray[index] = srcData[srcPos + 2];
  55760. byteArray[index + 3] = srcData[srcPos + 3];
  55761. index += 4;
  55762. }
  55763. }
  55764. return byteArray;
  55765. };
  55766. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  55767. var byteArray = new Uint8Array(dataLength);
  55768. var srcData = new Uint8Array(arrayBuffer);
  55769. var index = 0;
  55770. for (var y = height - 1; y >= 0; y--) {
  55771. for (var x = 0; x < width; x++) {
  55772. var srcPos = dataOffset + (x + y * width) * 3;
  55773. byteArray[index + 2] = srcData[srcPos];
  55774. byteArray[index + 1] = srcData[srcPos + 1];
  55775. byteArray[index] = srcData[srcPos + 2];
  55776. index += 3;
  55777. }
  55778. }
  55779. return byteArray;
  55780. };
  55781. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  55782. var byteArray = new Uint8Array(dataLength);
  55783. var srcData = new Uint8Array(arrayBuffer);
  55784. var index = 0;
  55785. for (var y = height - 1; y >= 0; y--) {
  55786. for (var x = 0; x < width; x++) {
  55787. var srcPos = dataOffset + (x + y * width);
  55788. byteArray[index] = srcData[srcPos];
  55789. index++;
  55790. }
  55791. }
  55792. return byteArray;
  55793. };
  55794. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  55795. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  55796. if (header[off_magic] != DDS_MAGIC) {
  55797. BABYLON.Tools.Error("Invalid magic number in DDS header");
  55798. return;
  55799. }
  55800. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  55801. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  55802. return;
  55803. }
  55804. if (info.isFourCC) {
  55805. fourCC = header[off_pfFourCC];
  55806. switch (fourCC) {
  55807. case FOURCC_DXT1:
  55808. blockBytes = 8;
  55809. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  55810. break;
  55811. case FOURCC_DXT3:
  55812. blockBytes = 16;
  55813. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  55814. break;
  55815. case FOURCC_DXT5:
  55816. blockBytes = 16;
  55817. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  55818. break;
  55819. default:
  55820. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  55821. return;
  55822. }
  55823. }
  55824. mipmapCount = 1;
  55825. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  55826. mipmapCount = Math.max(1, header[off_mipmapCount]);
  55827. }
  55828. var bpp = header[off_RGBbpp];
  55829. for (var face = 0; face < faces; face++) {
  55830. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  55831. width = header[off_width];
  55832. height = header[off_height];
  55833. dataOffset = header[off_size] + 4;
  55834. for (i = 0; i < mipmapCount; ++i) {
  55835. if (info.isRGB) {
  55836. if (bpp === 24) {
  55837. dataLength = width * height * 3;
  55838. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  55839. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  55840. }
  55841. else {
  55842. dataLength = width * height * 4;
  55843. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  55844. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  55845. }
  55846. }
  55847. else if (info.isLuminance) {
  55848. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  55849. var unpaddedRowSize = width;
  55850. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  55851. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  55852. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  55853. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  55854. }
  55855. else {
  55856. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  55857. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  55858. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  55859. }
  55860. dataOffset += dataLength;
  55861. width *= 0.5;
  55862. height *= 0.5;
  55863. width = Math.max(1.0, width);
  55864. height = Math.max(1.0, height);
  55865. }
  55866. }
  55867. };
  55868. return DDSTools;
  55869. }());
  55870. Internals.DDSTools = DDSTools;
  55871. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55872. })(BABYLON || (BABYLON = {}));
  55873. //# sourceMappingURL=babylon.dds.js.map
  55874. var BABYLON;
  55875. (function (BABYLON) {
  55876. var Internals;
  55877. (function (Internals) {
  55878. /**
  55879. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  55880. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  55881. */
  55882. var KhronosTextureContainer = (function () {
  55883. /**
  55884. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  55885. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  55886. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  55887. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  55888. */
  55889. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  55890. this.arrayBuffer = arrayBuffer;
  55891. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  55892. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  55893. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  55894. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  55895. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  55896. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  55897. BABYLON.Tools.Error("texture missing KTX identifier");
  55898. return;
  55899. }
  55900. // load the reset of the header in native 32 bit int
  55901. var header = new Int32Array(this.arrayBuffer, 12, 13);
  55902. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  55903. var oppositeEndianess = header[0] === 0x01020304;
  55904. // read all the header elements in order they exist in the file, without modification (sans endainness)
  55905. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  55906. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  55907. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  55908. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  55909. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  55910. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  55911. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  55912. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  55913. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  55914. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  55915. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  55916. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  55917. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  55918. if (this.glType !== 0) {
  55919. BABYLON.Tools.Error("only compressed formats currently supported");
  55920. return;
  55921. }
  55922. else {
  55923. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  55924. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  55925. }
  55926. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  55927. BABYLON.Tools.Error("only 2D textures currently supported");
  55928. return;
  55929. }
  55930. if (this.numberOfArrayElements !== 0) {
  55931. BABYLON.Tools.Error("texture arrays not currently supported");
  55932. return;
  55933. }
  55934. if (this.numberOfFaces !== facesExpected) {
  55935. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  55936. return;
  55937. }
  55938. // we now have a completely validated file, so could use existence of loadType as success
  55939. // would need to make this more elaborate & adjust checks above to support more than one load type
  55940. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  55941. }
  55942. // not as fast hardware based, but will probably never need to use
  55943. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  55944. return ((val & 0xFF) << 24)
  55945. | ((val & 0xFF00) << 8)
  55946. | ((val >> 8) & 0xFF00)
  55947. | ((val >> 24) & 0xFF);
  55948. };
  55949. /**
  55950. * It is assumed that the texture has already been created & is currently bound
  55951. */
  55952. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  55953. switch (this.loadType) {
  55954. case KhronosTextureContainer.COMPRESSED_2D:
  55955. this._upload2DCompressedLevels(gl, loadMipmaps);
  55956. break;
  55957. case KhronosTextureContainer.TEX_2D:
  55958. case KhronosTextureContainer.COMPRESSED_3D:
  55959. case KhronosTextureContainer.TEX_3D:
  55960. }
  55961. };
  55962. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  55963. // initialize width & height for level 1
  55964. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  55965. var width = this.pixelWidth;
  55966. var height = this.pixelHeight;
  55967. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  55968. for (var level = 0; level < mipmapCount; level++) {
  55969. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  55970. for (var face = 0; face < this.numberOfFaces; face++) {
  55971. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  55972. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  55973. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  55974. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  55975. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  55976. }
  55977. width = Math.max(1.0, width * 0.5);
  55978. height = Math.max(1.0, height * 0.5);
  55979. }
  55980. };
  55981. return KhronosTextureContainer;
  55982. }());
  55983. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  55984. // load types
  55985. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  55986. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  55987. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  55988. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  55989. Internals.KhronosTextureContainer = KhronosTextureContainer;
  55990. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55991. })(BABYLON || (BABYLON = {}));
  55992. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  55993. var BABYLON;
  55994. (function (BABYLON) {
  55995. var Debug;
  55996. (function (Debug) {
  55997. /**
  55998. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  55999. */
  56000. var SkeletonViewer = (function () {
  56001. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  56002. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  56003. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  56004. this.skeleton = skeleton;
  56005. this.mesh = mesh;
  56006. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  56007. this.renderingGroupId = renderingGroupId;
  56008. this.color = BABYLON.Color3.White();
  56009. this._debugLines = [];
  56010. this._isEnabled = false;
  56011. this._scene = scene;
  56012. this.update();
  56013. this._renderFunction = this.update.bind(this);
  56014. }
  56015. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  56016. get: function () {
  56017. return this._isEnabled;
  56018. },
  56019. set: function (value) {
  56020. if (this._isEnabled === value) {
  56021. return;
  56022. }
  56023. this._isEnabled = value;
  56024. if (value) {
  56025. this._scene.registerBeforeRender(this._renderFunction);
  56026. }
  56027. else {
  56028. this._scene.unregisterBeforeRender(this._renderFunction);
  56029. }
  56030. },
  56031. enumerable: true,
  56032. configurable: true
  56033. });
  56034. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  56035. if (x === void 0) { x = 0; }
  56036. if (y === void 0) { y = 0; }
  56037. if (z === void 0) { z = 0; }
  56038. var tmat = BABYLON.Tmp.Matrix[0];
  56039. var parentBone = bone.getParent();
  56040. tmat.copyFrom(bone.getLocalMatrix());
  56041. if (x !== 0 || y !== 0 || z !== 0) {
  56042. var tmat2 = BABYLON.Tmp.Matrix[1];
  56043. BABYLON.Matrix.IdentityToRef(tmat2);
  56044. tmat2.m[12] = x;
  56045. tmat2.m[13] = y;
  56046. tmat2.m[14] = z;
  56047. tmat2.multiplyToRef(tmat, tmat);
  56048. }
  56049. if (parentBone) {
  56050. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  56051. }
  56052. tmat.multiplyToRef(meshMat, tmat);
  56053. position.x = tmat.m[12];
  56054. position.y = tmat.m[13];
  56055. position.z = tmat.m[14];
  56056. };
  56057. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  56058. var len = bones.length;
  56059. for (var i = 0; i < len; i++) {
  56060. var bone = bones[i];
  56061. var points = this._debugLines[i];
  56062. if (!points) {
  56063. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56064. this._debugLines[i] = points;
  56065. }
  56066. this._getBonePosition(points[0], bone, meshMat);
  56067. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  56068. }
  56069. };
  56070. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  56071. var len = bones.length;
  56072. var boneNum = 0;
  56073. for (var i = len - 1; i >= 0; i--) {
  56074. var childBone = bones[i];
  56075. var parentBone = childBone.getParent();
  56076. if (!parentBone) {
  56077. continue;
  56078. }
  56079. var points = this._debugLines[boneNum];
  56080. if (!points) {
  56081. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56082. this._debugLines[boneNum] = points;
  56083. }
  56084. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  56085. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  56086. boneNum++;
  56087. }
  56088. };
  56089. SkeletonViewer.prototype.update = function () {
  56090. if (this.autoUpdateBonesMatrices) {
  56091. this.skeleton.computeAbsoluteTransforms();
  56092. }
  56093. if (this.skeleton.bones[0].length === undefined) {
  56094. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56095. }
  56096. else {
  56097. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  56098. }
  56099. if (!this._debugMesh) {
  56100. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  56101. this._debugMesh.renderingGroupId = this.renderingGroupId;
  56102. }
  56103. else {
  56104. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  56105. }
  56106. this._debugMesh.color = this.color;
  56107. };
  56108. SkeletonViewer.prototype.dispose = function () {
  56109. if (this._debugMesh) {
  56110. this.isEnabled = false;
  56111. this._debugMesh.dispose();
  56112. this._debugMesh = null;
  56113. }
  56114. };
  56115. return SkeletonViewer;
  56116. }());
  56117. Debug.SkeletonViewer = SkeletonViewer;
  56118. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56119. })(BABYLON || (BABYLON = {}));
  56120. //# sourceMappingURL=babylon.skeletonViewer.js.map
  56121. var BABYLON;
  56122. (function (BABYLON) {
  56123. var Debug;
  56124. (function (Debug) {
  56125. var AxesViewer = (function () {
  56126. function AxesViewer(scene, scaleLines) {
  56127. if (scaleLines === void 0) { scaleLines = 1; }
  56128. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56129. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56130. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56131. this.scaleLines = 1;
  56132. this.scaleLines = scaleLines;
  56133. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  56134. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  56135. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  56136. this._xmesh.renderingGroupId = 2;
  56137. this._ymesh.renderingGroupId = 2;
  56138. this._zmesh.renderingGroupId = 2;
  56139. this._xmesh.material.checkReadyOnlyOnce = true;
  56140. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  56141. this._ymesh.material.checkReadyOnlyOnce = true;
  56142. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  56143. this._zmesh.material.checkReadyOnlyOnce = true;
  56144. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  56145. this.scene = scene;
  56146. }
  56147. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  56148. var scaleLines = this.scaleLines;
  56149. var point1 = this._xline[0];
  56150. var point2 = this._xline[1];
  56151. point1.x = position.x;
  56152. point1.y = position.y;
  56153. point1.z = position.z;
  56154. point2.x = point1.x + xaxis.x * scaleLines;
  56155. point2.y = point1.y + xaxis.y * scaleLines;
  56156. point2.z = point1.z + xaxis.z * scaleLines;
  56157. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  56158. point1 = this._yline[0];
  56159. point2 = this._yline[1];
  56160. point1.x = position.x;
  56161. point1.y = position.y;
  56162. point1.z = position.z;
  56163. point2.x = point1.x + yaxis.x * scaleLines;
  56164. point2.y = point1.y + yaxis.y * scaleLines;
  56165. point2.z = point1.z + yaxis.z * scaleLines;
  56166. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  56167. point1 = this._zline[0];
  56168. point2 = this._zline[1];
  56169. point1.x = position.x;
  56170. point1.y = position.y;
  56171. point1.z = position.z;
  56172. point2.x = point1.x + zaxis.x * scaleLines;
  56173. point2.y = point1.y + zaxis.y * scaleLines;
  56174. point2.z = point1.z + zaxis.z * scaleLines;
  56175. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  56176. };
  56177. AxesViewer.prototype.dispose = function () {
  56178. if (this._xmesh) {
  56179. this._xmesh.dispose();
  56180. this._ymesh.dispose();
  56181. this._zmesh.dispose();
  56182. this._xmesh = null;
  56183. this._ymesh = null;
  56184. this._zmesh = null;
  56185. this._xline = null;
  56186. this._yline = null;
  56187. this._zline = null;
  56188. this.scene = null;
  56189. }
  56190. };
  56191. return AxesViewer;
  56192. }());
  56193. Debug.AxesViewer = AxesViewer;
  56194. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56195. })(BABYLON || (BABYLON = {}));
  56196. //# sourceMappingURL=babylon.axesViewer.js.map
  56197. var BABYLON;
  56198. (function (BABYLON) {
  56199. var Debug;
  56200. (function (Debug) {
  56201. var BoneAxesViewer = (function (_super) {
  56202. __extends(BoneAxesViewer, _super);
  56203. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  56204. if (scaleLines === void 0) { scaleLines = 1; }
  56205. var _this = _super.call(this, scene, scaleLines) || this;
  56206. _this.pos = BABYLON.Vector3.Zero();
  56207. _this.xaxis = BABYLON.Vector3.Zero();
  56208. _this.yaxis = BABYLON.Vector3.Zero();
  56209. _this.zaxis = BABYLON.Vector3.Zero();
  56210. _this.mesh = mesh;
  56211. _this.bone = bone;
  56212. return _this;
  56213. }
  56214. BoneAxesViewer.prototype.update = function () {
  56215. var bone = this.bone;
  56216. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  56217. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  56218. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  56219. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  56220. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  56221. };
  56222. BoneAxesViewer.prototype.dispose = function () {
  56223. if (this.pos) {
  56224. this.pos = null;
  56225. this.xaxis = null;
  56226. this.yaxis = null;
  56227. this.zaxis = null;
  56228. this.mesh = null;
  56229. this.bone = null;
  56230. _super.prototype.dispose.call(this);
  56231. }
  56232. };
  56233. return BoneAxesViewer;
  56234. }(Debug.AxesViewer));
  56235. Debug.BoneAxesViewer = BoneAxesViewer;
  56236. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  56237. })(BABYLON || (BABYLON = {}));
  56238. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  56239. var BABYLON;
  56240. (function (BABYLON) {
  56241. var RayHelper = (function () {
  56242. function RayHelper(ray) {
  56243. this.ray = ray;
  56244. }
  56245. RayHelper.CreateAndShow = function (ray, scene, color) {
  56246. var helper = new RayHelper(ray);
  56247. helper.show(scene, color);
  56248. return helper;
  56249. };
  56250. RayHelper.prototype.show = function (scene, color) {
  56251. if (!this._renderFunction) {
  56252. var ray = this.ray;
  56253. this._renderFunction = this._render.bind(this);
  56254. this._scene = scene;
  56255. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  56256. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  56257. this._scene.registerBeforeRender(this._renderFunction);
  56258. }
  56259. if (color) {
  56260. this._renderLine.color.copyFrom(color);
  56261. }
  56262. };
  56263. RayHelper.prototype.hide = function () {
  56264. if (this._renderFunction) {
  56265. this._scene.unregisterBeforeRender(this._renderFunction);
  56266. this._scene = null;
  56267. this._renderFunction = null;
  56268. this._renderLine.dispose();
  56269. this._renderLine = null;
  56270. this._renderPoints = null;
  56271. }
  56272. };
  56273. RayHelper.prototype._render = function () {
  56274. var ray = this.ray;
  56275. var point = this._renderPoints[1];
  56276. var len = Math.min(ray.length, 1000000);
  56277. point.copyFrom(ray.direction);
  56278. point.scaleInPlace(len);
  56279. point.addInPlace(ray.origin);
  56280. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  56281. };
  56282. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  56283. this._attachedToMesh = mesh;
  56284. var ray = this.ray;
  56285. if (!ray.direction) {
  56286. ray.direction = BABYLON.Vector3.Zero();
  56287. }
  56288. if (!ray.origin) {
  56289. ray.origin = BABYLON.Vector3.Zero();
  56290. }
  56291. if (length) {
  56292. ray.length = length;
  56293. }
  56294. if (!meshSpaceOrigin) {
  56295. meshSpaceOrigin = BABYLON.Vector3.Zero();
  56296. }
  56297. if (!meshSpaceDirection) {
  56298. // -1 so that this will work with Mesh.lookAt
  56299. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  56300. }
  56301. if (!this._meshSpaceDirection) {
  56302. this._meshSpaceDirection = meshSpaceDirection.clone();
  56303. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  56304. }
  56305. else {
  56306. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  56307. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  56308. }
  56309. if (!this._updateToMeshFunction) {
  56310. this._updateToMeshFunction = this._updateToMesh.bind(this);
  56311. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  56312. }
  56313. this._updateToMesh();
  56314. };
  56315. RayHelper.prototype.detachFromMesh = function () {
  56316. if (this._attachedToMesh) {
  56317. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  56318. this._attachedToMesh = null;
  56319. this._updateToMeshFunction = null;
  56320. }
  56321. };
  56322. RayHelper.prototype._updateToMesh = function () {
  56323. var ray = this.ray;
  56324. if (this._attachedToMesh._isDisposed) {
  56325. this.detachFromMesh();
  56326. return;
  56327. }
  56328. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  56329. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  56330. };
  56331. RayHelper.prototype.dispose = function () {
  56332. this.hide();
  56333. this.detachFromMesh();
  56334. this.ray = null;
  56335. };
  56336. return RayHelper;
  56337. }());
  56338. BABYLON.RayHelper = RayHelper;
  56339. })(BABYLON || (BABYLON = {}));
  56340. //# sourceMappingURL=babylon.rayHelper.js.map
  56341. var BABYLON;
  56342. (function (BABYLON) {
  56343. var DebugLayer = (function () {
  56344. function DebugLayer(scene) {
  56345. this._scene = scene;
  56346. }
  56347. /** Creates the inspector window. */
  56348. DebugLayer.prototype._createInspector = function (config) {
  56349. if (config === void 0) { config = {}; }
  56350. var popup = config.popup || false;
  56351. var initialTab = config.initialTab || 0;
  56352. var parentElement = config.parentElement || null;
  56353. if (!this._inspector) {
  56354. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  56355. } // else nothing to do,; instance is already existing
  56356. };
  56357. DebugLayer.prototype.isVisible = function () {
  56358. if (!this._inspector) {
  56359. return false;
  56360. }
  56361. return true;
  56362. };
  56363. DebugLayer.prototype.hide = function () {
  56364. if (this._inspector) {
  56365. try {
  56366. this._inspector.dispose();
  56367. }
  56368. catch (e) {
  56369. // If the inspector has been removed directly from the inspector tool
  56370. }
  56371. this._inspector = null;
  56372. }
  56373. };
  56374. DebugLayer.prototype.show = function (config) {
  56375. if (config === void 0) { config = {}; }
  56376. if (typeof INSPECTOR == 'undefined') {
  56377. // Load inspector and add it to the DOM
  56378. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  56379. }
  56380. else {
  56381. // Otherwise creates the inspector
  56382. this._createInspector(config);
  56383. }
  56384. };
  56385. return DebugLayer;
  56386. }());
  56387. // Get protocol used - http or https
  56388. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//www.babylonjs.com/babylon.inspector.bundle.js';
  56389. BABYLON.DebugLayer = DebugLayer;
  56390. })(BABYLON || (BABYLON = {}));
  56391. //# sourceMappingURL=babylon.debugLayer.js.map
  56392. var BABYLON;
  56393. (function (BABYLON) {
  56394. var BoundingBoxRenderer = (function () {
  56395. function BoundingBoxRenderer(scene) {
  56396. this.frontColor = new BABYLON.Color3(1, 1, 1);
  56397. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  56398. this.showBackLines = true;
  56399. this.renderList = new BABYLON.SmartArray(32);
  56400. this._vertexBuffers = {};
  56401. this._scene = scene;
  56402. }
  56403. BoundingBoxRenderer.prototype._prepareRessources = function () {
  56404. if (this._colorShader) {
  56405. return;
  56406. }
  56407. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  56408. attributes: [BABYLON.VertexBuffer.PositionKind],
  56409. uniforms: ["worldViewProjection", "color"]
  56410. });
  56411. var engine = this._scene.getEngine();
  56412. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  56413. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  56414. 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]);
  56415. };
  56416. BoundingBoxRenderer.prototype.reset = function () {
  56417. this.renderList.reset();
  56418. };
  56419. BoundingBoxRenderer.prototype.render = function () {
  56420. if (this.renderList.length === 0) {
  56421. return;
  56422. }
  56423. this._prepareRessources();
  56424. if (!this._colorShader.isReady()) {
  56425. return;
  56426. }
  56427. var engine = this._scene.getEngine();
  56428. engine.setDepthWrite(false);
  56429. this._colorShader._preBind();
  56430. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  56431. var boundingBox = this.renderList.data[boundingBoxIndex];
  56432. var min = boundingBox.minimum;
  56433. var max = boundingBox.maximum;
  56434. var diff = max.subtract(min);
  56435. var median = min.add(diff.scale(0.5));
  56436. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  56437. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  56438. .multiply(boundingBox.getWorldMatrix());
  56439. // VBOs
  56440. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  56441. if (this.showBackLines) {
  56442. // Back
  56443. engine.setDepthFunctionToGreaterOrEqual();
  56444. this._scene.resetCachedMaterial();
  56445. this._colorShader.setColor4("color", this.backColor.toColor4());
  56446. this._colorShader.bind(worldMatrix);
  56447. // Draw order
  56448. engine.draw(false, 0, 24);
  56449. }
  56450. // Front
  56451. engine.setDepthFunctionToLess();
  56452. this._scene.resetCachedMaterial();
  56453. this._colorShader.setColor4("color", this.frontColor.toColor4());
  56454. this._colorShader.bind(worldMatrix);
  56455. // Draw order
  56456. engine.draw(false, 0, 24);
  56457. }
  56458. this._colorShader.unbind();
  56459. engine.setDepthFunctionToLessOrEqual();
  56460. engine.setDepthWrite(true);
  56461. };
  56462. BoundingBoxRenderer.prototype.dispose = function () {
  56463. if (!this._colorShader) {
  56464. return;
  56465. }
  56466. this.renderList.dispose();
  56467. this._colorShader.dispose();
  56468. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  56469. if (buffer) {
  56470. buffer.dispose();
  56471. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  56472. }
  56473. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56474. };
  56475. return BoundingBoxRenderer;
  56476. }());
  56477. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  56478. })(BABYLON || (BABYLON = {}));
  56479. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  56480. var BABYLON;
  56481. (function (BABYLON) {
  56482. var MorphTarget = (function () {
  56483. function MorphTarget(name, influence) {
  56484. if (influence === void 0) { influence = 0; }
  56485. this.name = name;
  56486. this.onInfluenceChanged = new BABYLON.Observable();
  56487. this.influence = influence;
  56488. }
  56489. Object.defineProperty(MorphTarget.prototype, "influence", {
  56490. get: function () {
  56491. return this._influence;
  56492. },
  56493. set: function (influence) {
  56494. if (this._influence === influence) {
  56495. return;
  56496. }
  56497. var previous = this._influence;
  56498. this._influence = influence;
  56499. if (this.onInfluenceChanged.hasObservers) {
  56500. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  56501. }
  56502. },
  56503. enumerable: true,
  56504. configurable: true
  56505. });
  56506. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  56507. get: function () {
  56508. return this._normals !== undefined;
  56509. },
  56510. enumerable: true,
  56511. configurable: true
  56512. });
  56513. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  56514. get: function () {
  56515. return this._tangents !== undefined;
  56516. },
  56517. enumerable: true,
  56518. configurable: true
  56519. });
  56520. MorphTarget.prototype.setPositions = function (data) {
  56521. this._positions = new Float32Array(data);
  56522. };
  56523. MorphTarget.prototype.getPositions = function () {
  56524. return this._positions;
  56525. };
  56526. MorphTarget.prototype.setNormals = function (data) {
  56527. this._normals = new Float32Array(data);
  56528. };
  56529. MorphTarget.prototype.getNormals = function () {
  56530. return this._normals;
  56531. };
  56532. MorphTarget.prototype.setTangents = function (data) {
  56533. this._tangents = new Float32Array(data);
  56534. };
  56535. MorphTarget.prototype.getTangents = function () {
  56536. return this._tangents;
  56537. };
  56538. /**
  56539. * Serializes the current target into a Serialization object.
  56540. * Returns the serialized object.
  56541. */
  56542. MorphTarget.prototype.serialize = function () {
  56543. var serializationObject = {};
  56544. serializationObject.name = this.name;
  56545. serializationObject.influence = this.influence;
  56546. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  56547. if (this.hasNormals) {
  56548. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  56549. }
  56550. if (this.hasTangents) {
  56551. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  56552. }
  56553. return serializationObject;
  56554. };
  56555. // Statics
  56556. MorphTarget.Parse = function (serializationObject) {
  56557. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  56558. result.setPositions(serializationObject.positions);
  56559. if (serializationObject.normals) {
  56560. result.setNormals(serializationObject.normals);
  56561. }
  56562. if (serializationObject.tangents) {
  56563. result.setTangents(serializationObject.tangents);
  56564. }
  56565. return result;
  56566. };
  56567. MorphTarget.FromMesh = function (mesh, name, influence) {
  56568. if (!name) {
  56569. name = mesh.name;
  56570. }
  56571. var result = new MorphTarget(name, influence);
  56572. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  56573. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  56574. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  56575. }
  56576. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  56577. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  56578. }
  56579. return result;
  56580. };
  56581. return MorphTarget;
  56582. }());
  56583. BABYLON.MorphTarget = MorphTarget;
  56584. })(BABYLON || (BABYLON = {}));
  56585. //# sourceMappingURL=babylon.morphTarget.js.map
  56586. var BABYLON;
  56587. (function (BABYLON) {
  56588. var MorphTargetManager = (function () {
  56589. function MorphTargetManager(scene) {
  56590. this._targets = new Array();
  56591. this._targetObservable = new Array();
  56592. this._activeTargets = new BABYLON.SmartArray(16);
  56593. this._supportsNormals = false;
  56594. this._supportsTangents = false;
  56595. this._vertexCount = 0;
  56596. this._uniqueId = 0;
  56597. if (!scene) {
  56598. scene = BABYLON.Engine.LastCreatedScene;
  56599. }
  56600. this._scene = scene;
  56601. this._scene.morphTargetManagers.push(this);
  56602. this._uniqueId = scene.getUniqueId();
  56603. }
  56604. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  56605. get: function () {
  56606. return this._uniqueId;
  56607. },
  56608. enumerable: true,
  56609. configurable: true
  56610. });
  56611. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  56612. get: function () {
  56613. return this._vertexCount;
  56614. },
  56615. enumerable: true,
  56616. configurable: true
  56617. });
  56618. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  56619. get: function () {
  56620. return this._supportsNormals;
  56621. },
  56622. enumerable: true,
  56623. configurable: true
  56624. });
  56625. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  56626. get: function () {
  56627. return this._supportsTangents;
  56628. },
  56629. enumerable: true,
  56630. configurable: true
  56631. });
  56632. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  56633. get: function () {
  56634. return this._activeTargets.length;
  56635. },
  56636. enumerable: true,
  56637. configurable: true
  56638. });
  56639. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  56640. get: function () {
  56641. return this._influences;
  56642. },
  56643. enumerable: true,
  56644. configurable: true
  56645. });
  56646. MorphTargetManager.prototype.getActiveTarget = function (index) {
  56647. return this._activeTargets.data[index];
  56648. };
  56649. MorphTargetManager.prototype.addTarget = function (target) {
  56650. var _this = this;
  56651. if (this._vertexCount) {
  56652. if (this._vertexCount !== target.getPositions().length / 3) {
  56653. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  56654. return;
  56655. }
  56656. }
  56657. this._targets.push(target);
  56658. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  56659. _this._syncActiveTargets(needUpdate);
  56660. }));
  56661. this._syncActiveTargets(true);
  56662. };
  56663. MorphTargetManager.prototype.removeTarget = function (target) {
  56664. var index = this._targets.indexOf(target);
  56665. if (index >= 0) {
  56666. this._targets.splice(index, 1);
  56667. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  56668. this._vertexCount = 0;
  56669. this._syncActiveTargets(true);
  56670. }
  56671. };
  56672. /**
  56673. * Serializes the current manager into a Serialization object.
  56674. * Returns the serialized object.
  56675. */
  56676. MorphTargetManager.prototype.serialize = function () {
  56677. var serializationObject = {};
  56678. serializationObject.id = this.uniqueId;
  56679. serializationObject.targets = [];
  56680. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  56681. var target = _a[_i];
  56682. serializationObject.targets.push(target.serialize());
  56683. }
  56684. return serializationObject;
  56685. };
  56686. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  56687. this._syncActiveTargets(needUpdate);
  56688. };
  56689. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  56690. this._activeTargets.reset();
  56691. var tempInfluences = [];
  56692. this._supportsNormals = true;
  56693. this._supportsTangents = true;
  56694. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  56695. var target = _a[_i];
  56696. if (target.influence > 0) {
  56697. this._activeTargets.push(target);
  56698. tempInfluences.push(target.influence);
  56699. this._supportsNormals = this._supportsNormals && target.hasNormals;
  56700. this._supportsTangents = this._supportsTangents && target.hasTangents;
  56701. if (this._vertexCount === 0) {
  56702. this._vertexCount = target.getPositions().length / 3;
  56703. }
  56704. }
  56705. }
  56706. this._influences = new Float32Array(tempInfluences);
  56707. if (needUpdate) {
  56708. // Flag meshes as dirty to resync with the active targets
  56709. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  56710. var mesh = _c[_b];
  56711. if (mesh.morphTargetManager === this) {
  56712. mesh._syncGeometryWithMorphTargetManager();
  56713. }
  56714. }
  56715. }
  56716. };
  56717. // Statics
  56718. MorphTargetManager.Parse = function (serializationObject, scene) {
  56719. var result = new MorphTargetManager(scene);
  56720. result._uniqueId = serializationObject.id;
  56721. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  56722. var targetData = _a[_i];
  56723. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  56724. }
  56725. return result;
  56726. };
  56727. return MorphTargetManager;
  56728. }());
  56729. BABYLON.MorphTargetManager = MorphTargetManager;
  56730. })(BABYLON || (BABYLON = {}));
  56731. //# sourceMappingURL=babylon.morphTargetManager.js.map
  56732. var BABYLON;
  56733. (function (BABYLON) {
  56734. /**
  56735. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  56736. * It can help converting any input color in a desired output one. This can then be used to create effects
  56737. * from sepia, black and white to sixties or futuristic rendering...
  56738. *
  56739. * The only supported format is currently 3dl.
  56740. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  56741. */
  56742. var ColorGradingTexture = (function (_super) {
  56743. __extends(ColorGradingTexture, _super);
  56744. /**
  56745. * Instantiates a ColorGradingTexture from the following parameters.
  56746. *
  56747. * @param url The location of the color gradind data (currently only supporting 3dl)
  56748. * @param scene The scene the texture will be used in
  56749. */
  56750. function ColorGradingTexture(url, scene) {
  56751. var _this = _super.call(this, scene) || this;
  56752. if (!url) {
  56753. return _this;
  56754. }
  56755. _this._textureMatrix = BABYLON.Matrix.Identity();
  56756. _this.name = url;
  56757. _this.url = url;
  56758. _this.hasAlpha = false;
  56759. _this.isCube = false;
  56760. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56761. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56762. _this.anisotropicFilteringLevel = 1;
  56763. _this._texture = _this._getFromCache(url, true);
  56764. if (!_this._texture) {
  56765. if (!scene.useDelayedTextureLoading) {
  56766. _this.loadTexture();
  56767. }
  56768. else {
  56769. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56770. }
  56771. }
  56772. return _this;
  56773. }
  56774. /**
  56775. * Returns the texture matrix used in most of the material.
  56776. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  56777. */
  56778. ColorGradingTexture.prototype.getTextureMatrix = function () {
  56779. return this._textureMatrix;
  56780. };
  56781. /**
  56782. * Occurs when the file being loaded is a .3dl LUT file.
  56783. */
  56784. ColorGradingTexture.prototype.load3dlTexture = function () {
  56785. var _this = this;
  56786. var mipLevels = 0;
  56787. var floatArrayView = null;
  56788. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56789. this._texture = texture;
  56790. var callback = function (text) {
  56791. var data;
  56792. var tempData;
  56793. var line;
  56794. var lines = text.split('\n');
  56795. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  56796. var maxColor = 0;
  56797. for (var i = 0; i < lines.length; i++) {
  56798. line = lines[i];
  56799. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  56800. continue;
  56801. if (line.indexOf('#') === 0)
  56802. continue;
  56803. var words = line.split(" ");
  56804. if (size === 0) {
  56805. // Number of space + one
  56806. size = words.length;
  56807. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  56808. tempData = new Float32Array(size * size * size * 4);
  56809. continue;
  56810. }
  56811. if (size != 0) {
  56812. var r = Math.max(parseInt(words[0]), 0);
  56813. var g = Math.max(parseInt(words[1]), 0);
  56814. var b = Math.max(parseInt(words[2]), 0);
  56815. maxColor = Math.max(r, maxColor);
  56816. maxColor = Math.max(g, maxColor);
  56817. maxColor = Math.max(b, maxColor);
  56818. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  56819. tempData[pixelStorageIndex + 0] = r;
  56820. tempData[pixelStorageIndex + 1] = g;
  56821. tempData[pixelStorageIndex + 2] = b;
  56822. tempData[pixelStorageIndex + 3] = 0;
  56823. pixelIndexSlice++;
  56824. if (pixelIndexSlice % size == 0) {
  56825. pixelIndexH++;
  56826. pixelIndexSlice = 0;
  56827. if (pixelIndexH % size == 0) {
  56828. pixelIndexW++;
  56829. pixelIndexH = 0;
  56830. }
  56831. }
  56832. }
  56833. }
  56834. for (var i = 0; i < tempData.length; i++) {
  56835. var value = tempData[i];
  56836. data[i] = (value / maxColor * 255);
  56837. }
  56838. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  56839. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  56840. };
  56841. BABYLON.Tools.LoadFile(this.url, callback);
  56842. return this._texture;
  56843. };
  56844. /**
  56845. * Starts the loading process of the texture.
  56846. */
  56847. ColorGradingTexture.prototype.loadTexture = function () {
  56848. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  56849. this.load3dlTexture();
  56850. }
  56851. };
  56852. /**
  56853. * Clones the color gradind texture.
  56854. */
  56855. ColorGradingTexture.prototype.clone = function () {
  56856. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  56857. // Base texture
  56858. newTexture.level = this.level;
  56859. return newTexture;
  56860. };
  56861. /**
  56862. * Called during delayed load for textures.
  56863. */
  56864. ColorGradingTexture.prototype.delayLoad = function () {
  56865. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56866. return;
  56867. }
  56868. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56869. this._texture = this._getFromCache(this.url, true);
  56870. if (!this._texture) {
  56871. this.loadTexture();
  56872. }
  56873. };
  56874. /**
  56875. * Binds the color grading to the shader.
  56876. * @param colorGrading The texture to bind
  56877. * @param effect The effect to bind to
  56878. */
  56879. ColorGradingTexture.Bind = function (colorGrading, effect) {
  56880. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  56881. var x = colorGrading.level; // Texture Level
  56882. var y = colorGrading.getSize().height; // Texture Size example with 8
  56883. var z = y - 1.0; // SizeMinusOne 8 - 1
  56884. var w = 1 / y; // Space of 1 slice 1 / 8
  56885. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  56886. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  56887. 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
  56888. 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
  56889. 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
  56890. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  56891. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  56892. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  56893. };
  56894. /**
  56895. * Prepare the list of uniforms associated with the ColorGrading effects.
  56896. * @param uniformsList The list of uniforms used in the effect
  56897. * @param samplersList The list of samplers used in the effect
  56898. */
  56899. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  56900. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  56901. samplersList.push("cameraColorGrading2DSampler");
  56902. };
  56903. /**
  56904. * Parses a color grading texture serialized by Babylon.
  56905. * @param parsedTexture The texture information being parsedTexture
  56906. * @param scene The scene to load the texture in
  56907. * @param rootUrl The root url of the data assets to load
  56908. * @return A color gradind texture
  56909. */
  56910. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56911. var texture = null;
  56912. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  56913. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  56914. texture.name = parsedTexture.name;
  56915. texture.level = parsedTexture.level;
  56916. }
  56917. return texture;
  56918. };
  56919. /**
  56920. * Serializes the LUT texture to json format.
  56921. */
  56922. ColorGradingTexture.prototype.serialize = function () {
  56923. if (!this.name) {
  56924. return null;
  56925. }
  56926. var serializationObject = {};
  56927. serializationObject.name = this.name;
  56928. serializationObject.level = this.level;
  56929. serializationObject.customType = "BABYLON.ColorGradingTexture";
  56930. return serializationObject;
  56931. };
  56932. return ColorGradingTexture;
  56933. }(BABYLON.BaseTexture));
  56934. /**
  56935. * Empty line regex stored for GC.
  56936. */
  56937. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  56938. BABYLON.ColorGradingTexture = ColorGradingTexture;
  56939. })(BABYLON || (BABYLON = {}));
  56940. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  56941. var BABYLON;
  56942. (function (BABYLON) {
  56943. /**
  56944. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  56945. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  56946. * 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;
  56947. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  56948. */
  56949. var ColorCurves = (function () {
  56950. function ColorCurves() {
  56951. this._dirty = true;
  56952. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  56953. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  56954. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  56955. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  56956. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  56957. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  56958. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  56959. this._globalHue = 30;
  56960. this._globalDensity = 0;
  56961. this._globalSaturation = 0;
  56962. this._globalExposure = 0;
  56963. this._highlightsHue = 30;
  56964. this._highlightsDensity = 0;
  56965. this._highlightsSaturation = 0;
  56966. this._highlightsExposure = 0;
  56967. this._midtonesHue = 30;
  56968. this._midtonesDensity = 0;
  56969. this._midtonesSaturation = 0;
  56970. this._midtonesExposure = 0;
  56971. this._shadowsHue = 30;
  56972. this._shadowsDensity = 0;
  56973. this._shadowsSaturation = 0;
  56974. this._shadowsExposure = 0;
  56975. }
  56976. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  56977. /**
  56978. * Gets the global Hue value.
  56979. * 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).
  56980. */
  56981. get: function () {
  56982. return this._globalHue;
  56983. },
  56984. /**
  56985. * Sets the global Hue value.
  56986. * 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).
  56987. */
  56988. set: function (value) {
  56989. this._globalHue = value;
  56990. this._dirty = true;
  56991. },
  56992. enumerable: true,
  56993. configurable: true
  56994. });
  56995. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  56996. /**
  56997. * Gets the global Density value.
  56998. * 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.
  56999. * Values less than zero provide a filter of opposite hue.
  57000. */
  57001. get: function () {
  57002. return this._globalDensity;
  57003. },
  57004. /**
  57005. * Sets the global Density value.
  57006. * 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.
  57007. * Values less than zero provide a filter of opposite hue.
  57008. */
  57009. set: function (value) {
  57010. this._globalDensity = value;
  57011. this._dirty = true;
  57012. },
  57013. enumerable: true,
  57014. configurable: true
  57015. });
  57016. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  57017. /**
  57018. * Gets the global Saturation value.
  57019. * 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.
  57020. */
  57021. get: function () {
  57022. return this._globalSaturation;
  57023. },
  57024. /**
  57025. * Sets the global Saturation value.
  57026. * 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.
  57027. */
  57028. set: function (value) {
  57029. this._globalSaturation = value;
  57030. this._dirty = true;
  57031. },
  57032. enumerable: true,
  57033. configurable: true
  57034. });
  57035. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  57036. /**
  57037. * Gets the highlights Hue value.
  57038. * 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).
  57039. */
  57040. get: function () {
  57041. return this._highlightsHue;
  57042. },
  57043. /**
  57044. * Sets the highlights Hue value.
  57045. * 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).
  57046. */
  57047. set: function (value) {
  57048. this._highlightsHue = value;
  57049. this._dirty = true;
  57050. },
  57051. enumerable: true,
  57052. configurable: true
  57053. });
  57054. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  57055. /**
  57056. * Gets the highlights Density value.
  57057. * 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.
  57058. * Values less than zero provide a filter of opposite hue.
  57059. */
  57060. get: function () {
  57061. return this._highlightsDensity;
  57062. },
  57063. /**
  57064. * Sets the highlights Density value.
  57065. * 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.
  57066. * Values less than zero provide a filter of opposite hue.
  57067. */
  57068. set: function (value) {
  57069. this._highlightsDensity = value;
  57070. this._dirty = true;
  57071. },
  57072. enumerable: true,
  57073. configurable: true
  57074. });
  57075. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  57076. /**
  57077. * Gets the highlights Saturation value.
  57078. * 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.
  57079. */
  57080. get: function () {
  57081. return this._highlightsSaturation;
  57082. },
  57083. /**
  57084. * Sets the highlights Saturation value.
  57085. * 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.
  57086. */
  57087. set: function (value) {
  57088. this._highlightsSaturation = value;
  57089. this._dirty = true;
  57090. },
  57091. enumerable: true,
  57092. configurable: true
  57093. });
  57094. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  57095. /**
  57096. * Gets the highlights Exposure value.
  57097. * 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.
  57098. */
  57099. get: function () {
  57100. return this._highlightsExposure;
  57101. },
  57102. /**
  57103. * Sets the highlights Exposure value.
  57104. * 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.
  57105. */
  57106. set: function (value) {
  57107. this._highlightsExposure = value;
  57108. this._dirty = true;
  57109. },
  57110. enumerable: true,
  57111. configurable: true
  57112. });
  57113. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  57114. /**
  57115. * Gets the midtones Hue value.
  57116. * 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).
  57117. */
  57118. get: function () {
  57119. return this._midtonesHue;
  57120. },
  57121. /**
  57122. * Sets the midtones Hue value.
  57123. * 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).
  57124. */
  57125. set: function (value) {
  57126. this._midtonesHue = value;
  57127. this._dirty = true;
  57128. },
  57129. enumerable: true,
  57130. configurable: true
  57131. });
  57132. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  57133. /**
  57134. * Gets the midtones Density value.
  57135. * 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.
  57136. * Values less than zero provide a filter of opposite hue.
  57137. */
  57138. get: function () {
  57139. return this._midtonesDensity;
  57140. },
  57141. /**
  57142. * Sets the midtones Density value.
  57143. * 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.
  57144. * Values less than zero provide a filter of opposite hue.
  57145. */
  57146. set: function (value) {
  57147. this._midtonesDensity = value;
  57148. this._dirty = true;
  57149. },
  57150. enumerable: true,
  57151. configurable: true
  57152. });
  57153. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  57154. /**
  57155. * Gets the midtones Saturation value.
  57156. * 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.
  57157. */
  57158. get: function () {
  57159. return this._midtonesSaturation;
  57160. },
  57161. /**
  57162. * Sets the midtones Saturation value.
  57163. * 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.
  57164. */
  57165. set: function (value) {
  57166. this._midtonesSaturation = value;
  57167. this._dirty = true;
  57168. },
  57169. enumerable: true,
  57170. configurable: true
  57171. });
  57172. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  57173. /**
  57174. * Gets the midtones Exposure value.
  57175. * 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.
  57176. */
  57177. get: function () {
  57178. return this._midtonesExposure;
  57179. },
  57180. /**
  57181. * Sets the midtones Exposure value.
  57182. * 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.
  57183. */
  57184. set: function (value) {
  57185. this._midtonesExposure = value;
  57186. this._dirty = true;
  57187. },
  57188. enumerable: true,
  57189. configurable: true
  57190. });
  57191. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  57192. /**
  57193. * Gets the shadows Hue value.
  57194. * 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).
  57195. */
  57196. get: function () {
  57197. return this._shadowsHue;
  57198. },
  57199. /**
  57200. * Sets the shadows Hue value.
  57201. * 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).
  57202. */
  57203. set: function (value) {
  57204. this._shadowsHue = value;
  57205. this._dirty = true;
  57206. },
  57207. enumerable: true,
  57208. configurable: true
  57209. });
  57210. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  57211. /**
  57212. * Gets the shadows Density value.
  57213. * 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.
  57214. * Values less than zero provide a filter of opposite hue.
  57215. */
  57216. get: function () {
  57217. return this._shadowsDensity;
  57218. },
  57219. /**
  57220. * Sets the shadows Density value.
  57221. * 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.
  57222. * Values less than zero provide a filter of opposite hue.
  57223. */
  57224. set: function (value) {
  57225. this._shadowsDensity = value;
  57226. this._dirty = true;
  57227. },
  57228. enumerable: true,
  57229. configurable: true
  57230. });
  57231. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  57232. /**
  57233. * Gets the shadows Saturation value.
  57234. * 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.
  57235. */
  57236. get: function () {
  57237. return this._shadowsSaturation;
  57238. },
  57239. /**
  57240. * Sets the shadows Saturation value.
  57241. * 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.
  57242. */
  57243. set: function (value) {
  57244. this._shadowsSaturation = value;
  57245. this._dirty = true;
  57246. },
  57247. enumerable: true,
  57248. configurable: true
  57249. });
  57250. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  57251. /**
  57252. * Gets the shadows Exposure value.
  57253. * 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.
  57254. */
  57255. get: function () {
  57256. return this._shadowsExposure;
  57257. },
  57258. /**
  57259. * Sets the shadows Exposure value.
  57260. * 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.
  57261. */
  57262. set: function (value) {
  57263. this._shadowsExposure = value;
  57264. this._dirty = true;
  57265. },
  57266. enumerable: true,
  57267. configurable: true
  57268. });
  57269. /**
  57270. * Binds the color curves to the shader.
  57271. * @param colorCurves The color curve to bind
  57272. * @param effect The effect to bind to
  57273. */
  57274. ColorCurves.Bind = function (colorCurves, effect) {
  57275. if (colorCurves._dirty) {
  57276. colorCurves._dirty = false;
  57277. // Fill in global info.
  57278. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  57279. // Compute highlights info.
  57280. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  57281. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  57282. // Compute midtones info.
  57283. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  57284. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  57285. // Compute shadows info.
  57286. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  57287. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  57288. // Compute deltas (neutral is midtones).
  57289. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  57290. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  57291. }
  57292. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  57293. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  57294. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  57295. };
  57296. /**
  57297. * Prepare the list of uniforms associated with the ColorCurves effects.
  57298. * @param uniformsList The list of uniforms used in the effect
  57299. */
  57300. ColorCurves.PrepareUniforms = function (uniformsList) {
  57301. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  57302. };
  57303. /**
  57304. * Returns color grading data based on a hue, density, saturation and exposure value.
  57305. * @param filterHue The hue of the color filter.
  57306. * @param filterDensity The density of the color filter.
  57307. * @param saturation The saturation.
  57308. * @param exposure The exposure.
  57309. * @param result The result data container.
  57310. */
  57311. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  57312. if (hue == null) {
  57313. return;
  57314. }
  57315. hue = ColorCurves.clamp(hue, 0, 360);
  57316. density = ColorCurves.clamp(density, -100, 100);
  57317. saturation = ColorCurves.clamp(saturation, -100, 100);
  57318. exposure = ColorCurves.clamp(exposure, -100, 100);
  57319. // Remap the slider/config filter density with non-linear mapping and also scale by half
  57320. // so that the maximum filter density is only 50% control. This provides fine control
  57321. // for small values and reasonable range.
  57322. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  57323. density *= 0.5;
  57324. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  57325. if (density < 0) {
  57326. density *= -1;
  57327. hue = (hue + 180) % 360;
  57328. }
  57329. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  57330. result.scaleToRef(2, result);
  57331. result.a = 1 + 0.01 * saturation;
  57332. };
  57333. /**
  57334. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  57335. * @param value The input slider value in range [-100,100].
  57336. * @returns Adjusted value.
  57337. */
  57338. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  57339. value /= 100;
  57340. var x = Math.abs(value);
  57341. x = Math.pow(x, 2);
  57342. if (value < 0) {
  57343. x *= -1;
  57344. }
  57345. x *= 100;
  57346. return x;
  57347. };
  57348. /**
  57349. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  57350. * @param hue The hue (H) input.
  57351. * @param saturation The saturation (S) input.
  57352. * @param brightness The brightness (B) input.
  57353. * @result An RGBA color represented as Vector4.
  57354. */
  57355. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  57356. var h = ColorCurves.clamp(hue, 0, 360);
  57357. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  57358. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  57359. if (s === 0) {
  57360. result.r = v;
  57361. result.g = v;
  57362. result.b = v;
  57363. }
  57364. else {
  57365. // sector 0 to 5
  57366. h /= 60;
  57367. var i = Math.floor(h);
  57368. // fractional part of h
  57369. var f = h - i;
  57370. var p = v * (1 - s);
  57371. var q = v * (1 - s * f);
  57372. var t = v * (1 - s * (1 - f));
  57373. switch (i) {
  57374. case 0:
  57375. result.r = v;
  57376. result.g = t;
  57377. result.b = p;
  57378. break;
  57379. case 1:
  57380. result.r = q;
  57381. result.g = v;
  57382. result.b = p;
  57383. break;
  57384. case 2:
  57385. result.r = p;
  57386. result.g = v;
  57387. result.b = t;
  57388. break;
  57389. case 3:
  57390. result.r = p;
  57391. result.g = q;
  57392. result.b = v;
  57393. break;
  57394. case 4:
  57395. result.r = t;
  57396. result.g = p;
  57397. result.b = v;
  57398. break;
  57399. default:
  57400. result.r = v;
  57401. result.g = p;
  57402. result.b = q;
  57403. break;
  57404. }
  57405. }
  57406. result.a = 1;
  57407. };
  57408. /**
  57409. * Returns a value clamped between min and max
  57410. * @param value The value to clamp
  57411. * @param min The minimum of value
  57412. * @param max The maximum of value
  57413. * @returns The clamped value.
  57414. */
  57415. ColorCurves.clamp = function (value, min, max) {
  57416. return Math.min(Math.max(value, min), max);
  57417. };
  57418. /**
  57419. * Clones the current color curve instance.
  57420. * @return The cloned curves
  57421. */
  57422. ColorCurves.prototype.clone = function () {
  57423. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  57424. };
  57425. /**
  57426. * Serializes the current color curve instance to a json representation.
  57427. * @return a JSON representation
  57428. */
  57429. ColorCurves.prototype.serialize = function () {
  57430. return BABYLON.SerializationHelper.Serialize(this);
  57431. };
  57432. /**
  57433. * Parses the color curve from a json representation.
  57434. * @param source the JSON source to parse
  57435. * @return The parsed curves
  57436. */
  57437. ColorCurves.Parse = function (source) {
  57438. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  57439. };
  57440. return ColorCurves;
  57441. }());
  57442. __decorate([
  57443. BABYLON.serialize()
  57444. ], ColorCurves.prototype, "_globalHue", void 0);
  57445. __decorate([
  57446. BABYLON.serialize()
  57447. ], ColorCurves.prototype, "_globalDensity", void 0);
  57448. __decorate([
  57449. BABYLON.serialize()
  57450. ], ColorCurves.prototype, "_globalSaturation", void 0);
  57451. __decorate([
  57452. BABYLON.serialize()
  57453. ], ColorCurves.prototype, "_globalExposure", void 0);
  57454. __decorate([
  57455. BABYLON.serialize()
  57456. ], ColorCurves.prototype, "_highlightsHue", void 0);
  57457. __decorate([
  57458. BABYLON.serialize()
  57459. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  57460. __decorate([
  57461. BABYLON.serialize()
  57462. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  57463. __decorate([
  57464. BABYLON.serialize()
  57465. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  57466. __decorate([
  57467. BABYLON.serialize()
  57468. ], ColorCurves.prototype, "_midtonesHue", void 0);
  57469. __decorate([
  57470. BABYLON.serialize()
  57471. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  57472. __decorate([
  57473. BABYLON.serialize()
  57474. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  57475. __decorate([
  57476. BABYLON.serialize()
  57477. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  57478. BABYLON.ColorCurves = ColorCurves;
  57479. })(BABYLON || (BABYLON = {}));
  57480. //# sourceMappingURL=babylon.colorCurves.js.map
  57481. var BABYLON;
  57482. (function (BABYLON) {
  57483. var Octree = (function () {
  57484. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  57485. if (maxDepth === void 0) { maxDepth = 2; }
  57486. this.maxDepth = maxDepth;
  57487. this.dynamicContent = new Array();
  57488. this._maxBlockCapacity = maxBlockCapacity || 64;
  57489. this._selectionContent = new BABYLON.SmartArray(1024);
  57490. this._creationFunc = creationFunc;
  57491. }
  57492. // Methods
  57493. Octree.prototype.update = function (worldMin, worldMax, entries) {
  57494. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  57495. };
  57496. Octree.prototype.addMesh = function (entry) {
  57497. for (var index = 0; index < this.blocks.length; index++) {
  57498. var block = this.blocks[index];
  57499. block.addEntry(entry);
  57500. }
  57501. };
  57502. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  57503. this._selectionContent.reset();
  57504. for (var index = 0; index < this.blocks.length; index++) {
  57505. var block = this.blocks[index];
  57506. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  57507. }
  57508. if (allowDuplicate) {
  57509. this._selectionContent.concat(this.dynamicContent);
  57510. }
  57511. else {
  57512. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  57513. }
  57514. return this._selectionContent;
  57515. };
  57516. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  57517. this._selectionContent.reset();
  57518. for (var index = 0; index < this.blocks.length; index++) {
  57519. var block = this.blocks[index];
  57520. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  57521. }
  57522. if (allowDuplicate) {
  57523. this._selectionContent.concat(this.dynamicContent);
  57524. }
  57525. else {
  57526. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  57527. }
  57528. return this._selectionContent;
  57529. };
  57530. Octree.prototype.intersectsRay = function (ray) {
  57531. this._selectionContent.reset();
  57532. for (var index = 0; index < this.blocks.length; index++) {
  57533. var block = this.blocks[index];
  57534. block.intersectsRay(ray, this._selectionContent);
  57535. }
  57536. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  57537. return this._selectionContent;
  57538. };
  57539. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  57540. target.blocks = new Array();
  57541. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  57542. // Segmenting space
  57543. for (var x = 0; x < 2; x++) {
  57544. for (var y = 0; y < 2; y++) {
  57545. for (var z = 0; z < 2; z++) {
  57546. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  57547. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  57548. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  57549. block.addEntries(entries);
  57550. target.blocks.push(block);
  57551. }
  57552. }
  57553. }
  57554. };
  57555. return Octree;
  57556. }());
  57557. Octree.CreationFuncForMeshes = function (entry, block) {
  57558. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  57559. block.entries.push(entry);
  57560. }
  57561. };
  57562. Octree.CreationFuncForSubMeshes = function (entry, block) {
  57563. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  57564. block.entries.push(entry);
  57565. }
  57566. };
  57567. BABYLON.Octree = Octree;
  57568. })(BABYLON || (BABYLON = {}));
  57569. //# sourceMappingURL=babylon.octree.js.map
  57570. var BABYLON;
  57571. (function (BABYLON) {
  57572. var OctreeBlock = (function () {
  57573. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  57574. this.entries = new Array();
  57575. this._boundingVectors = new Array();
  57576. this._capacity = capacity;
  57577. this._depth = depth;
  57578. this._maxDepth = maxDepth;
  57579. this._creationFunc = creationFunc;
  57580. this._minPoint = minPoint;
  57581. this._maxPoint = maxPoint;
  57582. this._boundingVectors.push(minPoint.clone());
  57583. this._boundingVectors.push(maxPoint.clone());
  57584. this._boundingVectors.push(minPoint.clone());
  57585. this._boundingVectors[2].x = maxPoint.x;
  57586. this._boundingVectors.push(minPoint.clone());
  57587. this._boundingVectors[3].y = maxPoint.y;
  57588. this._boundingVectors.push(minPoint.clone());
  57589. this._boundingVectors[4].z = maxPoint.z;
  57590. this._boundingVectors.push(maxPoint.clone());
  57591. this._boundingVectors[5].z = minPoint.z;
  57592. this._boundingVectors.push(maxPoint.clone());
  57593. this._boundingVectors[6].x = minPoint.x;
  57594. this._boundingVectors.push(maxPoint.clone());
  57595. this._boundingVectors[7].y = minPoint.y;
  57596. }
  57597. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  57598. // Property
  57599. get: function () {
  57600. return this._capacity;
  57601. },
  57602. enumerable: true,
  57603. configurable: true
  57604. });
  57605. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  57606. get: function () {
  57607. return this._minPoint;
  57608. },
  57609. enumerable: true,
  57610. configurable: true
  57611. });
  57612. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  57613. get: function () {
  57614. return this._maxPoint;
  57615. },
  57616. enumerable: true,
  57617. configurable: true
  57618. });
  57619. // Methods
  57620. OctreeBlock.prototype.addEntry = function (entry) {
  57621. if (this.blocks) {
  57622. for (var index = 0; index < this.blocks.length; index++) {
  57623. var block = this.blocks[index];
  57624. block.addEntry(entry);
  57625. }
  57626. return;
  57627. }
  57628. this._creationFunc(entry, this);
  57629. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  57630. this.createInnerBlocks();
  57631. }
  57632. };
  57633. OctreeBlock.prototype.addEntries = function (entries) {
  57634. for (var index = 0; index < entries.length; index++) {
  57635. var mesh = entries[index];
  57636. this.addEntry(mesh);
  57637. }
  57638. };
  57639. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  57640. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  57641. if (this.blocks) {
  57642. for (var index = 0; index < this.blocks.length; index++) {
  57643. var block = this.blocks[index];
  57644. block.select(frustumPlanes, selection, allowDuplicate);
  57645. }
  57646. return;
  57647. }
  57648. if (allowDuplicate) {
  57649. selection.concat(this.entries);
  57650. }
  57651. else {
  57652. selection.concatWithNoDuplicate(this.entries);
  57653. }
  57654. }
  57655. };
  57656. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  57657. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  57658. if (this.blocks) {
  57659. for (var index = 0; index < this.blocks.length; index++) {
  57660. var block = this.blocks[index];
  57661. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  57662. }
  57663. return;
  57664. }
  57665. if (allowDuplicate) {
  57666. selection.concat(this.entries);
  57667. }
  57668. else {
  57669. selection.concatWithNoDuplicate(this.entries);
  57670. }
  57671. }
  57672. };
  57673. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  57674. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  57675. if (this.blocks) {
  57676. for (var index = 0; index < this.blocks.length; index++) {
  57677. var block = this.blocks[index];
  57678. block.intersectsRay(ray, selection);
  57679. }
  57680. return;
  57681. }
  57682. selection.concatWithNoDuplicate(this.entries);
  57683. }
  57684. };
  57685. OctreeBlock.prototype.createInnerBlocks = function () {
  57686. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  57687. };
  57688. return OctreeBlock;
  57689. }());
  57690. BABYLON.OctreeBlock = OctreeBlock;
  57691. })(BABYLON || (BABYLON = {}));
  57692. //# sourceMappingURL=babylon.octreeBlock.js.map
  57693. var BABYLON;
  57694. (function (BABYLON) {
  57695. var SIMDVector3 = (function () {
  57696. function SIMDVector3() {
  57697. }
  57698. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  57699. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  57700. };
  57701. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  57702. var m = transformation.m;
  57703. var m0 = SIMD.Float32x4.load(m, 0);
  57704. var m1 = SIMD.Float32x4.load(m, 4);
  57705. var m2 = SIMD.Float32x4.load(m, 8);
  57706. var m3 = SIMD.Float32x4.load(m, 12);
  57707. 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));
  57708. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  57709. result.x = SIMD.Float32x4.extractLane(r, 0);
  57710. result.y = SIMD.Float32x4.extractLane(r, 1);
  57711. result.z = SIMD.Float32x4.extractLane(r, 2);
  57712. };
  57713. return SIMDVector3;
  57714. }());
  57715. var SIMDMatrix = (function () {
  57716. function SIMDMatrix() {
  57717. }
  57718. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  57719. var tm = this.m;
  57720. var om = other.m;
  57721. var m0 = SIMD.Float32x4.load(om, 0);
  57722. var m1 = SIMD.Float32x4.load(om, 4);
  57723. var m2 = SIMD.Float32x4.load(om, 8);
  57724. var m3 = SIMD.Float32x4.load(om, 12);
  57725. for (var i = 0; i < 16; i += 4) {
  57726. 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)))));
  57727. }
  57728. return this;
  57729. };
  57730. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  57731. var src = this.m;
  57732. var dest = other.m;
  57733. // Load the 4 rows
  57734. var src0 = SIMD.Float32x4.load(src, 0);
  57735. var src1 = SIMD.Float32x4.load(src, 4);
  57736. var src2 = SIMD.Float32x4.load(src, 8);
  57737. var src3 = SIMD.Float32x4.load(src, 12);
  57738. // Transpose the source matrix. Sort of. Not a true transpose operation
  57739. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  57740. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  57741. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  57742. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  57743. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  57744. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  57745. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  57746. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  57747. // This is a true transposition, but it will lead to an incorrect result
  57748. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  57749. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  57750. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  57751. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  57752. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  57753. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  57754. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  57755. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  57756. // ----
  57757. tmp1 = SIMD.Float32x4.mul(row2, row3);
  57758. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  57759. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  57760. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  57761. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  57762. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  57763. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  57764. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  57765. // ----
  57766. tmp1 = SIMD.Float32x4.mul(row1, row2);
  57767. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  57768. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  57769. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  57770. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  57771. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  57772. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  57773. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  57774. // ----
  57775. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  57776. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  57777. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  57778. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  57779. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  57780. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  57781. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  57782. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  57783. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  57784. // ----
  57785. tmp1 = SIMD.Float32x4.mul(row0, row1);
  57786. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  57787. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  57788. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  57789. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  57790. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  57791. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  57792. // ----
  57793. tmp1 = SIMD.Float32x4.mul(row0, row3);
  57794. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  57795. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  57796. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  57797. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  57798. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  57799. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  57800. // ----
  57801. tmp1 = SIMD.Float32x4.mul(row0, row2);
  57802. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  57803. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  57804. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  57805. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  57806. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  57807. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  57808. // Compute determinant
  57809. var det = SIMD.Float32x4.mul(row0, minor0);
  57810. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  57811. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  57812. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  57813. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  57814. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  57815. // These shuffles aren't necessary if the faulty transposition is done
  57816. // up at the top of this function.
  57817. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  57818. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  57819. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  57820. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  57821. // Compute final values by multiplying with 1/det
  57822. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  57823. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  57824. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  57825. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  57826. return this;
  57827. };
  57828. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  57829. var out = result.m;
  57830. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  57831. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  57832. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  57833. // cc.kmVec3Subtract(f, pCenter, pEye);
  57834. var f = SIMD.Float32x4.sub(center, eye);
  57835. // cc.kmVec3Normalize(f, f);
  57836. var tmp = SIMD.Float32x4.mul(f, f);
  57837. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  57838. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  57839. // cc.kmVec3Assign(up, pUp);
  57840. // cc.kmVec3Normalize(up, up);
  57841. tmp = SIMD.Float32x4.mul(up, up);
  57842. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  57843. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  57844. // cc.kmVec3Cross(s, f, up);
  57845. 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)));
  57846. // cc.kmVec3Normalize(s, s);
  57847. tmp = SIMD.Float32x4.mul(s, s);
  57848. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  57849. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  57850. // cc.kmVec3Cross(u, s, f);
  57851. 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)));
  57852. // cc.kmVec3Normalize(s, s);
  57853. tmp = SIMD.Float32x4.mul(s, s);
  57854. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  57855. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  57856. var zero = SIMD.Float32x4.splat(0.0);
  57857. s = SIMD.Float32x4.neg(s);
  57858. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  57859. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  57860. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  57861. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  57862. 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);
  57863. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  57864. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  57865. 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)))));
  57866. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  57867. 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)))));
  57868. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  57869. 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)))));
  57870. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  57871. 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)))));
  57872. };
  57873. return SIMDMatrix;
  57874. }());
  57875. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  57876. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  57877. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  57878. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  57879. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  57880. var SIMDHelper = (function () {
  57881. function SIMDHelper() {
  57882. }
  57883. Object.defineProperty(SIMDHelper, "IsEnabled", {
  57884. get: function () {
  57885. return SIMDHelper._isEnabled;
  57886. },
  57887. enumerable: true,
  57888. configurable: true
  57889. });
  57890. SIMDHelper.DisableSIMD = function () {
  57891. // Replace functions
  57892. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  57893. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  57894. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  57895. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  57896. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  57897. SIMDHelper._isEnabled = false;
  57898. };
  57899. SIMDHelper.EnableSIMD = function () {
  57900. if (self.SIMD === undefined) {
  57901. return;
  57902. }
  57903. // check if polyfills needed
  57904. if (!self.Math.fround) {
  57905. self.Math.fround = (function (array) { return function (x) {
  57906. return array[0] = x, array[0];
  57907. }; })(new Float32Array(1));
  57908. }
  57909. if (!self.Math.imul) {
  57910. self.Math.imul = function (a, b) {
  57911. var ah = (a >>> 16) & 0xffff;
  57912. var al = a & 0xffff;
  57913. var bh = (b >>> 16) & 0xffff;
  57914. var bl = b & 0xffff;
  57915. // the shift by 0 fixes the sign on the high part
  57916. // the final |0 converts the unsigned value into a signed value
  57917. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  57918. };
  57919. }
  57920. // Replace functions
  57921. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  57922. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  57923. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  57924. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  57925. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  57926. SIMDHelper._isEnabled = true;
  57927. };
  57928. return SIMDHelper;
  57929. }());
  57930. SIMDHelper._isEnabled = false;
  57931. BABYLON.SIMDHelper = SIMDHelper;
  57932. })(BABYLON || (BABYLON = {}));
  57933. //# sourceMappingURL=babylon.math.SIMD.js.map
  57934. var BABYLON;
  57935. (function (BABYLON) {
  57936. var VRDistortionCorrectionPostProcess = (function (_super) {
  57937. __extends(VRDistortionCorrectionPostProcess, _super);
  57938. //ANY
  57939. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  57940. var _this = _super.call(this, name, "vrDistortionCorrection", [
  57941. 'LensCenter',
  57942. 'Scale',
  57943. 'ScaleIn',
  57944. 'HmdWarpParam'
  57945. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  57946. _this._isRightEye = isRightEye;
  57947. _this._distortionFactors = vrMetrics.distortionK;
  57948. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  57949. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  57950. _this.onSizeChangedObservable.add(function () {
  57951. _this.aspectRatio = _this.width * .5 / _this.height;
  57952. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  57953. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  57954. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  57955. });
  57956. _this.onApplyObservable.add(function (effect) {
  57957. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  57958. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  57959. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  57960. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  57961. });
  57962. return _this;
  57963. }
  57964. return VRDistortionCorrectionPostProcess;
  57965. }(BABYLON.PostProcess));
  57966. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  57967. })(BABYLON || (BABYLON = {}));
  57968. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  57969. var BABYLON;
  57970. (function (BABYLON) {
  57971. var AnaglyphPostProcess = (function (_super) {
  57972. __extends(AnaglyphPostProcess, _super);
  57973. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  57974. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  57975. _this._passedProcess = rigCameras[0]._rigPostProcess;
  57976. _this.onApplyObservable.add(function (effect) {
  57977. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  57978. });
  57979. return _this;
  57980. }
  57981. return AnaglyphPostProcess;
  57982. }(BABYLON.PostProcess));
  57983. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  57984. })(BABYLON || (BABYLON = {}));
  57985. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  57986. var BABYLON;
  57987. (function (BABYLON) {
  57988. var StereoscopicInterlacePostProcess = (function (_super) {
  57989. __extends(StereoscopicInterlacePostProcess, _super);
  57990. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  57991. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  57992. _this._passedProcess = rigCameras[0]._rigPostProcess;
  57993. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  57994. _this.onSizeChangedObservable.add(function () {
  57995. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  57996. });
  57997. _this.onApplyObservable.add(function (effect) {
  57998. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  57999. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  58000. });
  58001. return _this;
  58002. }
  58003. return StereoscopicInterlacePostProcess;
  58004. }(BABYLON.PostProcess));
  58005. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  58006. })(BABYLON || (BABYLON = {}));
  58007. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  58008. var BABYLON;
  58009. (function (BABYLON) {
  58010. var FreeCameraDeviceOrientationInput = (function () {
  58011. function FreeCameraDeviceOrientationInput() {
  58012. var _this = this;
  58013. this._screenOrientationAngle = 0;
  58014. this._screenQuaternion = new BABYLON.Quaternion();
  58015. this._alpha = 0;
  58016. this._beta = 0;
  58017. this._gamma = 0;
  58018. this._orientationChanged = function () {
  58019. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  58020. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  58021. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  58022. };
  58023. this._deviceOrientation = function (evt) {
  58024. _this._alpha = evt.alpha;
  58025. _this._beta = evt.beta;
  58026. _this._gamma = evt.gamma;
  58027. };
  58028. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  58029. this._orientationChanged();
  58030. }
  58031. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  58032. get: function () {
  58033. return this._camera;
  58034. },
  58035. set: function (camera) {
  58036. this._camera = camera;
  58037. if (!this._camera.rotationQuaternion)
  58038. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  58039. },
  58040. enumerable: true,
  58041. configurable: true
  58042. });
  58043. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  58044. window.addEventListener("orientationchange", this._orientationChanged);
  58045. window.addEventListener("deviceorientation", this._deviceOrientation);
  58046. //In certain cases, the attach control is called AFTER orientation was changed,
  58047. //So this is needed.
  58048. this._orientationChanged();
  58049. };
  58050. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  58051. window.removeEventListener("orientationchange", this._orientationChanged);
  58052. window.removeEventListener("deviceorientation", this._deviceOrientation);
  58053. };
  58054. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  58055. //if no device orientation provided, don't update the rotation.
  58056. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  58057. if (!this._alpha)
  58058. return;
  58059. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  58060. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  58061. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  58062. //Mirror on XY Plane
  58063. this._camera.rotationQuaternion.z *= -1;
  58064. this._camera.rotationQuaternion.w *= -1;
  58065. };
  58066. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  58067. return "FreeCameraDeviceOrientationInput";
  58068. };
  58069. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  58070. return "deviceOrientation";
  58071. };
  58072. return FreeCameraDeviceOrientationInput;
  58073. }());
  58074. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  58075. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  58076. })(BABYLON || (BABYLON = {}));
  58077. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  58078. var BABYLON;
  58079. (function (BABYLON) {
  58080. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  58081. function ArcRotateCameraVRDeviceOrientationInput() {
  58082. this.alphaCorrection = 1;
  58083. this.betaCorrection = 1;
  58084. this.gammaCorrection = 1;
  58085. this._alpha = 0;
  58086. this._beta = 0;
  58087. this._gamma = 0;
  58088. this._dirty = false;
  58089. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  58090. }
  58091. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  58092. this.camera.attachControl(element, noPreventDefault);
  58093. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  58094. };
  58095. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  58096. var camera = this.camera;
  58097. this._alpha = +evt.alpha | 0;
  58098. this._beta = +evt.beta | 0;
  58099. this._gamma = +evt.gamma | 0;
  58100. this._dirty = true;
  58101. };
  58102. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  58103. if (this._dirty) {
  58104. this._dirty = false;
  58105. if (this._gamma < 0) {
  58106. this._gamma = 180 + this._gamma;
  58107. }
  58108. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  58109. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  58110. }
  58111. };
  58112. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  58113. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  58114. };
  58115. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  58116. return "ArcRotateCameraVRDeviceOrientationInput";
  58117. };
  58118. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  58119. return "VRDeviceOrientation";
  58120. };
  58121. return ArcRotateCameraVRDeviceOrientationInput;
  58122. }());
  58123. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  58124. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  58125. })(BABYLON || (BABYLON = {}));
  58126. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  58127. var BABYLON;
  58128. (function (BABYLON) {
  58129. var VRCameraMetrics = (function () {
  58130. function VRCameraMetrics() {
  58131. this.compensateDistortion = true;
  58132. }
  58133. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  58134. get: function () {
  58135. return this.hResolution / (2 * this.vResolution);
  58136. },
  58137. enumerable: true,
  58138. configurable: true
  58139. });
  58140. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  58141. get: function () {
  58142. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  58143. },
  58144. enumerable: true,
  58145. configurable: true
  58146. });
  58147. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  58148. get: function () {
  58149. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  58150. var h = (4 * meters) / this.hScreenSize;
  58151. return BABYLON.Matrix.Translation(h, 0, 0);
  58152. },
  58153. enumerable: true,
  58154. configurable: true
  58155. });
  58156. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  58157. get: function () {
  58158. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  58159. var h = (4 * meters) / this.hScreenSize;
  58160. return BABYLON.Matrix.Translation(-h, 0, 0);
  58161. },
  58162. enumerable: true,
  58163. configurable: true
  58164. });
  58165. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  58166. get: function () {
  58167. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  58168. },
  58169. enumerable: true,
  58170. configurable: true
  58171. });
  58172. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  58173. get: function () {
  58174. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  58175. },
  58176. enumerable: true,
  58177. configurable: true
  58178. });
  58179. VRCameraMetrics.GetDefault = function () {
  58180. var result = new VRCameraMetrics();
  58181. result.hResolution = 1280;
  58182. result.vResolution = 800;
  58183. result.hScreenSize = 0.149759993;
  58184. result.vScreenSize = 0.0935999975;
  58185. result.vScreenCenter = 0.0467999987;
  58186. result.eyeToScreenDistance = 0.0410000011;
  58187. result.lensSeparationDistance = 0.0635000020;
  58188. result.interpupillaryDistance = 0.0640000030;
  58189. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  58190. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  58191. result.postProcessScaleFactor = 1.714605507808412;
  58192. result.lensCenterOffset = 0.151976421;
  58193. return result;
  58194. };
  58195. return VRCameraMetrics;
  58196. }());
  58197. BABYLON.VRCameraMetrics = VRCameraMetrics;
  58198. })(BABYLON || (BABYLON = {}));
  58199. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  58200. var BABYLON;
  58201. (function (BABYLON) {
  58202. var WebVRFreeCamera = (function (_super) {
  58203. __extends(WebVRFreeCamera, _super);
  58204. function WebVRFreeCamera(name, position, scene, webVROptions) {
  58205. if (webVROptions === void 0) { webVROptions = {}; }
  58206. var _this = _super.call(this, name, position, scene) || this;
  58207. _this.webVROptions = webVROptions;
  58208. _this._vrDevice = null;
  58209. _this.rawPose = null;
  58210. _this._vrEnabled = false;
  58211. _this._specsVersion = 1.1;
  58212. _this._attached = false;
  58213. _this._positionOffset = BABYLON.Vector3.Zero();
  58214. _this._descendants = [];
  58215. _this.devicePosition = BABYLON.Vector3.Zero();
  58216. _this.deviceScaleFactor = 1;
  58217. _this.controllers = [];
  58218. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  58219. //legacy support - the compensation boolean was removed.
  58220. if (arguments.length === 5) {
  58221. _this.webVROptions = arguments[4];
  58222. }
  58223. // default webVR options
  58224. if (_this.webVROptions.trackPosition == undefined) {
  58225. _this.webVROptions.trackPosition = true;
  58226. }
  58227. if (_this.webVROptions.controllerMeshes == undefined) {
  58228. _this.webVROptions.controllerMeshes = true;
  58229. }
  58230. if (_this.webVROptions.defaultLightningOnControllers == undefined) {
  58231. _this.webVROptions.defaultLightningOnControllers = true;
  58232. }
  58233. _this.rotationQuaternion = new BABYLON.Quaternion();
  58234. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  58235. if (_this.webVROptions && _this.webVROptions.positionScale) {
  58236. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  58237. }
  58238. //enable VR
  58239. _this.getEngine().initWebVR();
  58240. if (!_this.getEngine().vrDisplaysPromise) {
  58241. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  58242. }
  58243. else {
  58244. //check specs version
  58245. if (!window.VRFrameData) {
  58246. _this._specsVersion = 1.0;
  58247. _this._frameData = {};
  58248. }
  58249. else {
  58250. _this._frameData = new VRFrameData();
  58251. }
  58252. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  58253. if (devices.length > 0) {
  58254. _this._vrEnabled = true;
  58255. if (_this.webVROptions.displayName) {
  58256. var found = devices.some(function (device) {
  58257. if (device.displayName === _this.webVROptions.displayName) {
  58258. _this._vrDevice = device;
  58259. return true;
  58260. }
  58261. else {
  58262. return false;
  58263. }
  58264. });
  58265. if (!found) {
  58266. _this._vrDevice = devices[0];
  58267. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  58268. }
  58269. }
  58270. else {
  58271. //choose the first one
  58272. _this._vrDevice = devices[0];
  58273. }
  58274. //reset the rig parameters.
  58275. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  58276. if (_this._attached) {
  58277. _this.getEngine().enableVR(_this._vrDevice);
  58278. }
  58279. }
  58280. else {
  58281. BABYLON.Tools.Error("No WebVR devices found!");
  58282. }
  58283. });
  58284. }
  58285. // try to attach the controllers, if found.
  58286. _this.initControllers();
  58287. /**
  58288. * The idea behind the following lines:
  58289. * objects that have the camera as parent should actually have the rig cameras as a parent.
  58290. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  58291. * the second will not show it correctly.
  58292. *
  58293. * To solve this - each object that has the camera as parent will be added to a protected array.
  58294. * When the rig camera renders, it will take this array and set all of those to be its children.
  58295. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  58296. * Amazing!
  58297. */
  58298. scene.onBeforeCameraRenderObservable.add(function (camera) {
  58299. if (camera.parent === _this && _this.rigParenting) {
  58300. _this._descendants = _this.getDescendants(true, function (n) {
  58301. // don't take the cameras or the controllers!
  58302. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  58303. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  58304. return !isController && !isRigCamera;
  58305. });
  58306. _this._descendants.forEach(function (node) {
  58307. node.parent = camera;
  58308. });
  58309. }
  58310. });
  58311. scene.onAfterCameraRenderObservable.add(function (camera) {
  58312. if (camera.parent === _this && _this.rigParenting) {
  58313. _this._descendants.forEach(function (node) {
  58314. node.parent = _this;
  58315. });
  58316. }
  58317. });
  58318. return _this;
  58319. }
  58320. Object.defineProperty(WebVRFreeCamera.prototype, "onControllersAttached", {
  58321. set: function (callback) {
  58322. this._onControllersAttached = callback;
  58323. // after setting - if the controllers are already set, execute the callback.
  58324. if (this.controllers.length >= 2) {
  58325. callback(this.controllers);
  58326. }
  58327. },
  58328. enumerable: true,
  58329. configurable: true
  58330. });
  58331. WebVRFreeCamera.prototype.getLeftCamera = function () {
  58332. return this._rigCameras[0];
  58333. };
  58334. WebVRFreeCamera.prototype.getRightCamera = function () {
  58335. return this._rigCameras[1];
  58336. };
  58337. WebVRFreeCamera.prototype.getLeftTarget = function () {
  58338. return this._rigCameras[0].getTarget();
  58339. };
  58340. WebVRFreeCamera.prototype.getRightTarget = function () {
  58341. return this._rigCameras[1].getTarget();
  58342. };
  58343. WebVRFreeCamera.prototype._checkInputs = function () {
  58344. if (this._vrEnabled) {
  58345. if (this._specsVersion === 1.1) {
  58346. this._vrDevice.getFrameData(this._frameData);
  58347. }
  58348. else {
  58349. //backwards comp
  58350. var pose = this._vrDevice.getPose();
  58351. this._frameData.pose = pose;
  58352. // calculate view and projection matrix
  58353. }
  58354. this.updateFromDevice(this._frameData.pose);
  58355. }
  58356. _super.prototype._checkInputs.call(this);
  58357. };
  58358. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  58359. if (poseData && poseData.orientation) {
  58360. this.rawPose = poseData;
  58361. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  58362. if (this.getScene().useRightHandedSystem) {
  58363. this.deviceRotationQuaternion.z *= -1;
  58364. this.deviceRotationQuaternion.w *= -1;
  58365. }
  58366. if (this.webVROptions.trackPosition && this.rawPose.position) {
  58367. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  58368. if (this.getScene().useRightHandedSystem) {
  58369. this.devicePosition.z *= -1;
  58370. }
  58371. }
  58372. }
  58373. };
  58374. /**
  58375. * WebVR's attach control will start broadcasting frames to the device.
  58376. * Note that in certain browsers (chrome for example) this function must be called
  58377. * within a user-interaction callback. Example:
  58378. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  58379. *
  58380. * @param {HTMLElement} element
  58381. * @param {boolean} [noPreventDefault]
  58382. *
  58383. * @memberOf WebVRFreeCamera
  58384. */
  58385. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  58386. _super.prototype.attachControl.call(this, element, noPreventDefault);
  58387. this._attached = true;
  58388. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  58389. if (this._vrEnabled) {
  58390. this.getEngine().enableVR(this._vrDevice);
  58391. }
  58392. };
  58393. WebVRFreeCamera.prototype.detachControl = function (element) {
  58394. _super.prototype.detachControl.call(this, element);
  58395. this._vrEnabled = false;
  58396. this._attached = false;
  58397. this.getEngine().disableVR();
  58398. };
  58399. WebVRFreeCamera.prototype.getClassName = function () {
  58400. return "WebVRFreeCamera";
  58401. };
  58402. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  58403. //uses the vrDisplay's "resetPose()".
  58404. //pitch and roll won't be affected.
  58405. this._vrDevice.resetPose();
  58406. };
  58407. WebVRFreeCamera.prototype._updateRigCameras = function () {
  58408. var camLeft = this._rigCameras[0];
  58409. var camRight = this._rigCameras[1];
  58410. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  58411. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  58412. camLeft.position.copyFrom(this.devicePosition);
  58413. camRight.position.copyFrom(this.devicePosition);
  58414. };
  58415. /**
  58416. * This function is called by the two RIG cameras.
  58417. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  58418. */
  58419. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  58420. var _this = this;
  58421. //WebVR 1.0
  58422. if (this._cameraRigParams["specs"] === 1.0) {
  58423. this._updateCameraRotationMatrix();
  58424. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  58425. // Computing target and final matrix
  58426. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  58427. if (this.getScene().useRightHandedSystem) {
  58428. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  58429. }
  58430. else {
  58431. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  58432. }
  58433. //now move the eye in the right direction
  58434. var eyeParams = this._cameraRigParams["eyeParameters"];
  58435. var offset = eyeParams.offset;
  58436. // it will actually always be 0, but just in case
  58437. if (this.getScene().useRightHandedSystem) {
  58438. offset[2] *= -1;
  58439. }
  58440. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  58441. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  58442. }
  58443. else {
  58444. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  58445. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  58446. if (!this.getScene().useRightHandedSystem) {
  58447. [2, 6, 8, 9, 14].forEach(function (num) {
  58448. _this._webvrViewMatrix.m[num] *= -1;
  58449. });
  58450. }
  58451. // update the camera rotation matrix
  58452. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  58453. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  58454. // Computing target and final matrix
  58455. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  58456. }
  58457. var parentCamera = this._cameraRigParams["parentCamera"];
  58458. // should the view matrix be updated with scale and position offset?
  58459. if (parentCamera.deviceScaleFactor !== 1) {
  58460. this._webvrViewMatrix.invert();
  58461. // scale the position, if set
  58462. if (parentCamera.deviceScaleFactor) {
  58463. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  58464. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  58465. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  58466. }
  58467. this._webvrViewMatrix.invert();
  58468. }
  58469. return this._webvrViewMatrix;
  58470. };
  58471. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  58472. var _this = this;
  58473. if (this._cameraRigParams["specs"] === 1.0) {
  58474. var eyeParams = this._cameraRigParams["eyeParameters"];
  58475. // deprecated!!
  58476. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, 0.1, 1000, this._projectionMatrix, this.getScene().useRightHandedSystem);
  58477. }
  58478. else {
  58479. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  58480. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  58481. //babylon compatible matrix
  58482. if (!this.getScene().useRightHandedSystem) {
  58483. [8, 9, 10, 11].forEach(function (num) {
  58484. _this._projectionMatrix.m[num] *= -1;
  58485. });
  58486. }
  58487. }
  58488. return this._projectionMatrix;
  58489. };
  58490. WebVRFreeCamera.prototype.initControllers = function () {
  58491. var _this = this;
  58492. this.controllers = [];
  58493. new BABYLON.Gamepads(function (gp) {
  58494. if (gp.type === BABYLON.Gamepad.POSE_ENABLED) {
  58495. var webVrController = gp;
  58496. if (_this.webVROptions.controllerMeshes) {
  58497. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  58498. if (_this.webVROptions.defaultLightningOnControllers) {
  58499. if (!_this._lightOnControllers) {
  58500. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  58501. }
  58502. loadedMesh.getChildren().forEach(function (mesh) {
  58503. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  58504. });
  58505. }
  58506. });
  58507. }
  58508. webVrController.attachToPoseControlledCamera(_this);
  58509. // since this is async - sanity check. Is the controller already stored?
  58510. if (_this.controllers.indexOf(webVrController) === -1) {
  58511. //add to the controllers array
  58512. _this.controllers.push(webVrController);
  58513. //did we find enough controllers? Great! let the developer know.
  58514. if (_this._onControllersAttached && _this.controllers.length >= 2) {
  58515. _this._onControllersAttached(_this.controllers);
  58516. }
  58517. }
  58518. }
  58519. });
  58520. };
  58521. return WebVRFreeCamera;
  58522. }(BABYLON.FreeCamera));
  58523. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  58524. })(BABYLON || (BABYLON = {}));
  58525. //# sourceMappingURL=babylon.webVRCamera.js.map
  58526. /// <reference path="babylon.freeCamera.ts" />
  58527. var BABYLON;
  58528. (function (BABYLON) {
  58529. // We're mainly based on the logic defined into the FreeCamera code
  58530. var DeviceOrientationCamera = (function (_super) {
  58531. __extends(DeviceOrientationCamera, _super);
  58532. function DeviceOrientationCamera(name, position, scene) {
  58533. var _this = _super.call(this, name, position, scene) || this;
  58534. _this._quaternionCache = new BABYLON.Quaternion();
  58535. _this.inputs.addDeviceOrientation();
  58536. return _this;
  58537. }
  58538. DeviceOrientationCamera.prototype.getClassName = function () {
  58539. return "DeviceOrientationCamera";
  58540. };
  58541. DeviceOrientationCamera.prototype._checkInputs = function () {
  58542. _super.prototype._checkInputs.call(this);
  58543. this._quaternionCache.copyFrom(this.rotationQuaternion);
  58544. if (this._initialQuaternion) {
  58545. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  58546. }
  58547. };
  58548. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  58549. var _this = this;
  58550. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  58551. //can only work if this camera has a rotation quaternion already.
  58552. if (!this.rotationQuaternion)
  58553. return;
  58554. if (!this._initialQuaternion) {
  58555. this._initialQuaternion = new BABYLON.Quaternion();
  58556. }
  58557. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  58558. ['x', 'y', 'z'].forEach(function (axisName) {
  58559. if (!axis[axisName]) {
  58560. _this._initialQuaternion[axisName] = 0;
  58561. }
  58562. else {
  58563. _this._initialQuaternion[axisName] *= -1;
  58564. }
  58565. });
  58566. this._initialQuaternion.normalize();
  58567. //force rotation update
  58568. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  58569. };
  58570. return DeviceOrientationCamera;
  58571. }(BABYLON.FreeCamera));
  58572. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  58573. })(BABYLON || (BABYLON = {}));
  58574. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  58575. var BABYLON;
  58576. (function (BABYLON) {
  58577. var VRDeviceOrientationFreeCamera = (function (_super) {
  58578. __extends(VRDeviceOrientationFreeCamera, _super);
  58579. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  58580. if (compensateDistortion === void 0) { compensateDistortion = true; }
  58581. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  58582. var _this = _super.call(this, name, position, scene) || this;
  58583. vrCameraMetrics.compensateDistortion = compensateDistortion;
  58584. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  58585. return _this;
  58586. }
  58587. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  58588. return "VRDeviceOrientationFreeCamera";
  58589. };
  58590. return VRDeviceOrientationFreeCamera;
  58591. }(BABYLON.DeviceOrientationCamera));
  58592. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  58593. var VRDeviceOrientationGamepadCamera = (function (_super) {
  58594. __extends(VRDeviceOrientationGamepadCamera, _super);
  58595. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  58596. if (compensateDistortion === void 0) { compensateDistortion = true; }
  58597. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  58598. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  58599. _this.inputs.addGamepad();
  58600. return _this;
  58601. }
  58602. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  58603. return "VRDeviceOrientationGamepadCamera";
  58604. };
  58605. return VRDeviceOrientationGamepadCamera;
  58606. }(VRDeviceOrientationFreeCamera));
  58607. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  58608. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  58609. __extends(VRDeviceOrientationArcRotateCamera, _super);
  58610. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  58611. if (compensateDistortion === void 0) { compensateDistortion = true; }
  58612. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  58613. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  58614. vrCameraMetrics.compensateDistortion = compensateDistortion;
  58615. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  58616. _this.inputs.addVRDeviceOrientation();
  58617. return _this;
  58618. }
  58619. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  58620. return "VRDeviceOrientationArcRotateCamera";
  58621. };
  58622. return VRDeviceOrientationArcRotateCamera;
  58623. }(BABYLON.ArcRotateCamera));
  58624. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  58625. })(BABYLON || (BABYLON = {}));
  58626. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  58627. /// <reference path="babylon.freeCamera.ts" />
  58628. /// <reference path="babylon.arcRotateCamera.ts" />
  58629. /// <reference path="babylon.gamepadCamera.ts" />
  58630. /// <reference path="babylon.universalCamera.ts" />
  58631. var BABYLON;
  58632. (function (BABYLON) {
  58633. var AnaglyphFreeCamera = (function (_super) {
  58634. __extends(AnaglyphFreeCamera, _super);
  58635. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  58636. var _this = _super.call(this, name, position, scene) || this;
  58637. _this.interaxialDistance = interaxialDistance;
  58638. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  58639. return _this;
  58640. }
  58641. AnaglyphFreeCamera.prototype.getClassName = function () {
  58642. return "AnaglyphFreeCamera";
  58643. };
  58644. return AnaglyphFreeCamera;
  58645. }(BABYLON.FreeCamera));
  58646. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  58647. var AnaglyphArcRotateCamera = (function (_super) {
  58648. __extends(AnaglyphArcRotateCamera, _super);
  58649. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  58650. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  58651. _this.interaxialDistance = interaxialDistance;
  58652. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  58653. return _this;
  58654. }
  58655. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  58656. return "AnaglyphArcRotateCamera";
  58657. };
  58658. return AnaglyphArcRotateCamera;
  58659. }(BABYLON.ArcRotateCamera));
  58660. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  58661. var AnaglyphGamepadCamera = (function (_super) {
  58662. __extends(AnaglyphGamepadCamera, _super);
  58663. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  58664. var _this = _super.call(this, name, position, scene) || this;
  58665. _this.interaxialDistance = interaxialDistance;
  58666. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  58667. return _this;
  58668. }
  58669. AnaglyphGamepadCamera.prototype.getClassName = function () {
  58670. return "AnaglyphGamepadCamera";
  58671. };
  58672. return AnaglyphGamepadCamera;
  58673. }(BABYLON.GamepadCamera));
  58674. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  58675. var AnaglyphUniversalCamera = (function (_super) {
  58676. __extends(AnaglyphUniversalCamera, _super);
  58677. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  58678. var _this = _super.call(this, name, position, scene) || this;
  58679. _this.interaxialDistance = interaxialDistance;
  58680. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  58681. return _this;
  58682. }
  58683. AnaglyphUniversalCamera.prototype.getClassName = function () {
  58684. return "AnaglyphUniversalCamera";
  58685. };
  58686. return AnaglyphUniversalCamera;
  58687. }(BABYLON.UniversalCamera));
  58688. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  58689. var StereoscopicFreeCamera = (function (_super) {
  58690. __extends(StereoscopicFreeCamera, _super);
  58691. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  58692. var _this = _super.call(this, name, position, scene) || this;
  58693. _this.interaxialDistance = interaxialDistance;
  58694. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  58695. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  58696. return _this;
  58697. }
  58698. StereoscopicFreeCamera.prototype.getClassName = function () {
  58699. return "StereoscopicFreeCamera";
  58700. };
  58701. return StereoscopicFreeCamera;
  58702. }(BABYLON.FreeCamera));
  58703. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  58704. var StereoscopicArcRotateCamera = (function (_super) {
  58705. __extends(StereoscopicArcRotateCamera, _super);
  58706. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  58707. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  58708. _this.interaxialDistance = interaxialDistance;
  58709. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  58710. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  58711. return _this;
  58712. }
  58713. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  58714. return "StereoscopicArcRotateCamera";
  58715. };
  58716. return StereoscopicArcRotateCamera;
  58717. }(BABYLON.ArcRotateCamera));
  58718. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  58719. var StereoscopicGamepadCamera = (function (_super) {
  58720. __extends(StereoscopicGamepadCamera, _super);
  58721. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  58722. var _this = _super.call(this, name, position, scene) || this;
  58723. _this.interaxialDistance = interaxialDistance;
  58724. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  58725. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  58726. return _this;
  58727. }
  58728. StereoscopicGamepadCamera.prototype.getClassName = function () {
  58729. return "StereoscopicGamepadCamera";
  58730. };
  58731. return StereoscopicGamepadCamera;
  58732. }(BABYLON.GamepadCamera));
  58733. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  58734. var StereoscopicUniversalCamera = (function (_super) {
  58735. __extends(StereoscopicUniversalCamera, _super);
  58736. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  58737. var _this = _super.call(this, name, position, scene) || this;
  58738. _this.interaxialDistance = interaxialDistance;
  58739. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  58740. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  58741. return _this;
  58742. }
  58743. StereoscopicUniversalCamera.prototype.getClassName = function () {
  58744. return "StereoscopicUniversalCamera";
  58745. };
  58746. return StereoscopicUniversalCamera;
  58747. }(BABYLON.UniversalCamera));
  58748. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  58749. })(BABYLON || (BABYLON = {}));
  58750. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  58751. // Mainly based on these 2 articles :
  58752. // 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
  58753. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  58754. var BABYLON;
  58755. (function (BABYLON) {
  58756. var JoystickAxis;
  58757. (function (JoystickAxis) {
  58758. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  58759. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  58760. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  58761. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  58762. var VirtualJoystick = (function () {
  58763. function VirtualJoystick(leftJoystick) {
  58764. var _this = this;
  58765. if (leftJoystick) {
  58766. this._leftJoystick = true;
  58767. }
  58768. else {
  58769. this._leftJoystick = false;
  58770. }
  58771. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  58772. VirtualJoystick._globalJoystickIndex++;
  58773. // By default left & right arrow keys are moving the X
  58774. // and up & down keys are moving the Y
  58775. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  58776. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  58777. this.reverseLeftRight = false;
  58778. this.reverseUpDown = false;
  58779. // collections of pointers
  58780. this._touches = new BABYLON.StringDictionary();
  58781. this.deltaPosition = BABYLON.Vector3.Zero();
  58782. this._joystickSensibility = 25;
  58783. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  58784. this._rotationSpeed = 25;
  58785. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  58786. this._rotateOnAxisRelativeToMesh = false;
  58787. this._onResize = function (evt) {
  58788. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  58789. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  58790. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  58791. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  58792. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  58793. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  58794. };
  58795. // injecting a canvas element on top of the canvas 3D game
  58796. if (!VirtualJoystick.vjCanvas) {
  58797. window.addEventListener("resize", this._onResize, false);
  58798. VirtualJoystick.vjCanvas = document.createElement("canvas");
  58799. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  58800. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  58801. VirtualJoystick.vjCanvas.width = window.innerWidth;
  58802. VirtualJoystick.vjCanvas.height = window.innerHeight;
  58803. VirtualJoystick.vjCanvas.style.width = "100%";
  58804. VirtualJoystick.vjCanvas.style.height = "100%";
  58805. VirtualJoystick.vjCanvas.style.position = "absolute";
  58806. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  58807. VirtualJoystick.vjCanvas.style.top = "0px";
  58808. VirtualJoystick.vjCanvas.style.left = "0px";
  58809. VirtualJoystick.vjCanvas.style.zIndex = "5";
  58810. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  58811. // Support for jQuery PEP polyfill
  58812. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  58813. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  58814. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  58815. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  58816. document.body.appendChild(VirtualJoystick.vjCanvas);
  58817. }
  58818. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  58819. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  58820. this.pressed = false;
  58821. // default joystick color
  58822. this._joystickColor = "cyan";
  58823. this._joystickPointerID = -1;
  58824. // current joystick position
  58825. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  58826. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  58827. // origin joystick position
  58828. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  58829. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  58830. this._onPointerDownHandlerRef = function (evt) {
  58831. _this._onPointerDown(evt);
  58832. };
  58833. this._onPointerMoveHandlerRef = function (evt) {
  58834. _this._onPointerMove(evt);
  58835. };
  58836. this._onPointerOutHandlerRef = function (evt) {
  58837. _this._onPointerUp(evt);
  58838. };
  58839. this._onPointerUpHandlerRef = function (evt) {
  58840. _this._onPointerUp(evt);
  58841. };
  58842. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  58843. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  58844. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  58845. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  58846. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  58847. evt.preventDefault(); // Disables system menu
  58848. }, false);
  58849. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  58850. }
  58851. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  58852. this._joystickSensibility = newJoystickSensibility;
  58853. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  58854. };
  58855. VirtualJoystick.prototype._onPointerDown = function (e) {
  58856. var positionOnScreenCondition;
  58857. e.preventDefault();
  58858. if (this._leftJoystick === true) {
  58859. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  58860. }
  58861. else {
  58862. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  58863. }
  58864. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  58865. // First contact will be dedicated to the virtual joystick
  58866. this._joystickPointerID = e.pointerId;
  58867. this._joystickPointerStartPos.x = e.clientX;
  58868. this._joystickPointerStartPos.y = e.clientY;
  58869. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  58870. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  58871. this._deltaJoystickVector.x = 0;
  58872. this._deltaJoystickVector.y = 0;
  58873. this.pressed = true;
  58874. this._touches.add(e.pointerId.toString(), e);
  58875. }
  58876. else {
  58877. // You can only trigger the action buttons with a joystick declared
  58878. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  58879. this._action();
  58880. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  58881. }
  58882. }
  58883. };
  58884. VirtualJoystick.prototype._onPointerMove = function (e) {
  58885. // If the current pointer is the one associated to the joystick (first touch contact)
  58886. if (this._joystickPointerID == e.pointerId) {
  58887. this._joystickPointerPos.x = e.clientX;
  58888. this._joystickPointerPos.y = e.clientY;
  58889. this._deltaJoystickVector = this._joystickPointerPos.clone();
  58890. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  58891. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  58892. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  58893. switch (this._axisTargetedByLeftAndRight) {
  58894. case JoystickAxis.X:
  58895. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  58896. break;
  58897. case JoystickAxis.Y:
  58898. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  58899. break;
  58900. case JoystickAxis.Z:
  58901. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  58902. break;
  58903. }
  58904. var directionUpDown = this.reverseUpDown ? 1 : -1;
  58905. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  58906. switch (this._axisTargetedByUpAndDown) {
  58907. case JoystickAxis.X:
  58908. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  58909. break;
  58910. case JoystickAxis.Y:
  58911. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  58912. break;
  58913. case JoystickAxis.Z:
  58914. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  58915. break;
  58916. }
  58917. }
  58918. else {
  58919. var data = this._touches.get(e.pointerId.toString());
  58920. if (data) {
  58921. data.x = e.clientX;
  58922. data.y = e.clientY;
  58923. }
  58924. }
  58925. };
  58926. VirtualJoystick.prototype._onPointerUp = function (e) {
  58927. if (this._joystickPointerID == e.pointerId) {
  58928. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  58929. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  58930. this._joystickPointerID = -1;
  58931. this.pressed = false;
  58932. }
  58933. else {
  58934. var touch = this._touches.get(e.pointerId.toString());
  58935. if (touch) {
  58936. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  58937. }
  58938. }
  58939. this._deltaJoystickVector.x = 0;
  58940. this._deltaJoystickVector.y = 0;
  58941. this._touches.remove(e.pointerId.toString());
  58942. };
  58943. /**
  58944. * Change the color of the virtual joystick
  58945. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  58946. */
  58947. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  58948. this._joystickColor = newColor;
  58949. };
  58950. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  58951. this._action = action;
  58952. };
  58953. // Define which axis you'd like to control for left & right
  58954. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  58955. switch (axis) {
  58956. case JoystickAxis.X:
  58957. case JoystickAxis.Y:
  58958. case JoystickAxis.Z:
  58959. this._axisTargetedByLeftAndRight = axis;
  58960. break;
  58961. default:
  58962. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  58963. break;
  58964. }
  58965. };
  58966. // Define which axis you'd like to control for up & down
  58967. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  58968. switch (axis) {
  58969. case JoystickAxis.X:
  58970. case JoystickAxis.Y:
  58971. case JoystickAxis.Z:
  58972. this._axisTargetedByUpAndDown = axis;
  58973. break;
  58974. default:
  58975. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  58976. break;
  58977. }
  58978. };
  58979. VirtualJoystick.prototype._clearCanvas = function () {
  58980. if (this._leftJoystick) {
  58981. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  58982. }
  58983. else {
  58984. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  58985. }
  58986. };
  58987. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  58988. var _this = this;
  58989. if (this.pressed) {
  58990. this._touches.forEach(function (key, touch) {
  58991. if (touch.pointerId === _this._joystickPointerID) {
  58992. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  58993. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  58994. VirtualJoystick.vjCanvasContext.beginPath();
  58995. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  58996. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  58997. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  58998. VirtualJoystick.vjCanvasContext.stroke();
  58999. VirtualJoystick.vjCanvasContext.closePath();
  59000. VirtualJoystick.vjCanvasContext.beginPath();
  59001. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  59002. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  59003. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  59004. VirtualJoystick.vjCanvasContext.stroke();
  59005. VirtualJoystick.vjCanvasContext.closePath();
  59006. VirtualJoystick.vjCanvasContext.beginPath();
  59007. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  59008. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  59009. VirtualJoystick.vjCanvasContext.stroke();
  59010. VirtualJoystick.vjCanvasContext.closePath();
  59011. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  59012. }
  59013. else {
  59014. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  59015. VirtualJoystick.vjCanvasContext.beginPath();
  59016. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  59017. VirtualJoystick.vjCanvasContext.beginPath();
  59018. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  59019. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  59020. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  59021. VirtualJoystick.vjCanvasContext.stroke();
  59022. VirtualJoystick.vjCanvasContext.closePath();
  59023. touch.prevX = touch.x;
  59024. touch.prevY = touch.y;
  59025. }
  59026. ;
  59027. });
  59028. }
  59029. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  59030. };
  59031. VirtualJoystick.prototype.releaseCanvas = function () {
  59032. if (VirtualJoystick.vjCanvas) {
  59033. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  59034. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  59035. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  59036. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  59037. window.removeEventListener("resize", this._onResize);
  59038. document.body.removeChild(VirtualJoystick.vjCanvas);
  59039. VirtualJoystick.vjCanvas = null;
  59040. }
  59041. };
  59042. return VirtualJoystick;
  59043. }());
  59044. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  59045. VirtualJoystick._globalJoystickIndex = 0;
  59046. BABYLON.VirtualJoystick = VirtualJoystick;
  59047. })(BABYLON || (BABYLON = {}));
  59048. //# sourceMappingURL=babylon.virtualJoystick.js.map
  59049. var BABYLON;
  59050. (function (BABYLON) {
  59051. // We're mainly based on the logic defined into the FreeCamera code
  59052. var VirtualJoysticksCamera = (function (_super) {
  59053. __extends(VirtualJoysticksCamera, _super);
  59054. function VirtualJoysticksCamera(name, position, scene) {
  59055. var _this = _super.call(this, name, position, scene) || this;
  59056. _this.inputs.addVirtualJoystick();
  59057. return _this;
  59058. }
  59059. VirtualJoysticksCamera.prototype.getClassName = function () {
  59060. return "VirtualJoysticksCamera";
  59061. };
  59062. return VirtualJoysticksCamera;
  59063. }(BABYLON.FreeCamera));
  59064. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  59065. })(BABYLON || (BABYLON = {}));
  59066. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  59067. var BABYLON;
  59068. (function (BABYLON) {
  59069. var FreeCameraVirtualJoystickInput = (function () {
  59070. function FreeCameraVirtualJoystickInput() {
  59071. }
  59072. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  59073. return this._leftjoystick;
  59074. };
  59075. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  59076. return this._rightjoystick;
  59077. };
  59078. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  59079. if (this._leftjoystick) {
  59080. var camera = this.camera;
  59081. var speed = camera._computeLocalCameraSpeed() * 50;
  59082. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  59083. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  59084. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  59085. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  59086. if (!this._leftjoystick.pressed) {
  59087. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  59088. }
  59089. if (!this._rightjoystick.pressed) {
  59090. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  59091. }
  59092. }
  59093. };
  59094. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  59095. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  59096. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  59097. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  59098. this._leftjoystick.setJoystickSensibility(0.15);
  59099. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  59100. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  59101. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  59102. this._rightjoystick.reverseUpDown = true;
  59103. this._rightjoystick.setJoystickSensibility(0.05);
  59104. this._rightjoystick.setJoystickColor("yellow");
  59105. };
  59106. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  59107. this._leftjoystick.releaseCanvas();
  59108. this._rightjoystick.releaseCanvas();
  59109. };
  59110. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  59111. return "FreeCameraVirtualJoystickInput";
  59112. };
  59113. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  59114. return "virtualJoystick";
  59115. };
  59116. return FreeCameraVirtualJoystickInput;
  59117. }());
  59118. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  59119. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  59120. })(BABYLON || (BABYLON = {}));
  59121. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  59122. var BABYLON;
  59123. (function (BABYLON) {
  59124. var SimplificationSettings = (function () {
  59125. function SimplificationSettings(quality, distance, optimizeMesh) {
  59126. this.quality = quality;
  59127. this.distance = distance;
  59128. this.optimizeMesh = optimizeMesh;
  59129. }
  59130. return SimplificationSettings;
  59131. }());
  59132. BABYLON.SimplificationSettings = SimplificationSettings;
  59133. var SimplificationQueue = (function () {
  59134. function SimplificationQueue() {
  59135. this.running = false;
  59136. this._simplificationArray = [];
  59137. }
  59138. SimplificationQueue.prototype.addTask = function (task) {
  59139. this._simplificationArray.push(task);
  59140. };
  59141. SimplificationQueue.prototype.executeNext = function () {
  59142. var task = this._simplificationArray.pop();
  59143. if (task) {
  59144. this.running = true;
  59145. this.runSimplification(task);
  59146. }
  59147. else {
  59148. this.running = false;
  59149. }
  59150. };
  59151. SimplificationQueue.prototype.runSimplification = function (task) {
  59152. var _this = this;
  59153. if (task.parallelProcessing) {
  59154. //parallel simplifier
  59155. task.settings.forEach(function (setting) {
  59156. var simplifier = _this.getSimplifier(task);
  59157. simplifier.simplify(setting, function (newMesh) {
  59158. task.mesh.addLODLevel(setting.distance, newMesh);
  59159. newMesh.isVisible = true;
  59160. //check if it is the last
  59161. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  59162. //all done, run the success callback.
  59163. task.successCallback();
  59164. }
  59165. _this.executeNext();
  59166. });
  59167. });
  59168. }
  59169. else {
  59170. //single simplifier.
  59171. var simplifier = this.getSimplifier(task);
  59172. var runDecimation = function (setting, callback) {
  59173. simplifier.simplify(setting, function (newMesh) {
  59174. task.mesh.addLODLevel(setting.distance, newMesh);
  59175. newMesh.isVisible = true;
  59176. //run the next quality level
  59177. callback();
  59178. });
  59179. };
  59180. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  59181. runDecimation(task.settings[loop.index], function () {
  59182. loop.executeNext();
  59183. });
  59184. }, function () {
  59185. //execution ended, run the success callback.
  59186. if (task.successCallback) {
  59187. task.successCallback();
  59188. }
  59189. _this.executeNext();
  59190. });
  59191. }
  59192. };
  59193. SimplificationQueue.prototype.getSimplifier = function (task) {
  59194. switch (task.simplificationType) {
  59195. case SimplificationType.QUADRATIC:
  59196. default:
  59197. return new QuadraticErrorSimplification(task.mesh);
  59198. }
  59199. };
  59200. return SimplificationQueue;
  59201. }());
  59202. BABYLON.SimplificationQueue = SimplificationQueue;
  59203. /**
  59204. * The implemented types of simplification.
  59205. * At the moment only Quadratic Error Decimation is implemented.
  59206. */
  59207. var SimplificationType;
  59208. (function (SimplificationType) {
  59209. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  59210. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  59211. var DecimationTriangle = (function () {
  59212. function DecimationTriangle(vertices) {
  59213. this.vertices = vertices;
  59214. this.error = new Array(4);
  59215. this.deleted = false;
  59216. this.isDirty = false;
  59217. this.deletePending = false;
  59218. this.borderFactor = 0;
  59219. }
  59220. return DecimationTriangle;
  59221. }());
  59222. BABYLON.DecimationTriangle = DecimationTriangle;
  59223. var DecimationVertex = (function () {
  59224. function DecimationVertex(position, id) {
  59225. this.position = position;
  59226. this.id = id;
  59227. this.isBorder = true;
  59228. this.q = new QuadraticMatrix();
  59229. this.triangleCount = 0;
  59230. this.triangleStart = 0;
  59231. this.originalOffsets = [];
  59232. }
  59233. DecimationVertex.prototype.updatePosition = function (newPosition) {
  59234. this.position.copyFrom(newPosition);
  59235. };
  59236. return DecimationVertex;
  59237. }());
  59238. BABYLON.DecimationVertex = DecimationVertex;
  59239. var QuadraticMatrix = (function () {
  59240. function QuadraticMatrix(data) {
  59241. this.data = new Array(10);
  59242. for (var i = 0; i < 10; ++i) {
  59243. if (data && data[i]) {
  59244. this.data[i] = data[i];
  59245. }
  59246. else {
  59247. this.data[i] = 0;
  59248. }
  59249. }
  59250. }
  59251. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  59252. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  59253. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  59254. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  59255. return det;
  59256. };
  59257. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  59258. for (var i = 0; i < 10; ++i) {
  59259. this.data[i] += matrix.data[i];
  59260. }
  59261. };
  59262. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  59263. for (var i = 0; i < 10; ++i) {
  59264. this.data[i] += data[i];
  59265. }
  59266. };
  59267. QuadraticMatrix.prototype.add = function (matrix) {
  59268. var m = new QuadraticMatrix();
  59269. for (var i = 0; i < 10; ++i) {
  59270. m.data[i] = this.data[i] + matrix.data[i];
  59271. }
  59272. return m;
  59273. };
  59274. QuadraticMatrix.FromData = function (a, b, c, d) {
  59275. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  59276. };
  59277. //returning an array to avoid garbage collection
  59278. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  59279. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  59280. };
  59281. return QuadraticMatrix;
  59282. }());
  59283. BABYLON.QuadraticMatrix = QuadraticMatrix;
  59284. var Reference = (function () {
  59285. function Reference(vertexId, triangleId) {
  59286. this.vertexId = vertexId;
  59287. this.triangleId = triangleId;
  59288. }
  59289. return Reference;
  59290. }());
  59291. BABYLON.Reference = Reference;
  59292. /**
  59293. * An implementation of the Quadratic Error simplification algorithm.
  59294. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  59295. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  59296. * @author RaananW
  59297. */
  59298. var QuadraticErrorSimplification = (function () {
  59299. function QuadraticErrorSimplification(_mesh) {
  59300. this._mesh = _mesh;
  59301. this.initialized = false;
  59302. this.syncIterations = 5000;
  59303. this.aggressiveness = 7;
  59304. this.decimationIterations = 100;
  59305. this.boundingBoxEpsilon = BABYLON.Epsilon;
  59306. }
  59307. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  59308. var _this = this;
  59309. this.initDecimatedMesh();
  59310. //iterating through the submeshes array, one after the other.
  59311. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  59312. _this.initWithMesh(loop.index, function () {
  59313. _this.runDecimation(settings, loop.index, function () {
  59314. loop.executeNext();
  59315. });
  59316. }, settings.optimizeMesh);
  59317. }, function () {
  59318. setTimeout(function () {
  59319. successCallback(_this._reconstructedMesh);
  59320. }, 0);
  59321. });
  59322. };
  59323. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  59324. var _this = this;
  59325. var gCount = 0;
  59326. triangle.vertices.forEach(function (vertex) {
  59327. var count = 0;
  59328. var vPos = vertex.position;
  59329. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  59330. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  59331. ++count;
  59332. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  59333. ++count;
  59334. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  59335. ++count;
  59336. if (count > 1) {
  59337. ++gCount;
  59338. }
  59339. ;
  59340. });
  59341. if (gCount > 1) {
  59342. console.log(triangle, gCount);
  59343. }
  59344. return gCount > 1;
  59345. };
  59346. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  59347. var _this = this;
  59348. var targetCount = ~~(this.triangles.length * settings.quality);
  59349. var deletedTriangles = 0;
  59350. var triangleCount = this.triangles.length;
  59351. var iterationFunction = function (iteration, callback) {
  59352. setTimeout(function () {
  59353. if (iteration % 5 === 0) {
  59354. _this.updateMesh(iteration === 0);
  59355. }
  59356. for (var i = 0; i < _this.triangles.length; ++i) {
  59357. _this.triangles[i].isDirty = false;
  59358. }
  59359. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  59360. var trianglesIterator = function (i) {
  59361. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  59362. var t = _this.triangles[tIdx];
  59363. if (!t)
  59364. return;
  59365. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  59366. return;
  59367. }
  59368. for (var j = 0; j < 3; ++j) {
  59369. if (t.error[j] < threshold) {
  59370. var deleted0 = [];
  59371. var deleted1 = [];
  59372. var v0 = t.vertices[j];
  59373. var v1 = t.vertices[(j + 1) % 3];
  59374. if (v0.isBorder || v1.isBorder)
  59375. continue;
  59376. var p = BABYLON.Vector3.Zero();
  59377. var n = BABYLON.Vector3.Zero();
  59378. var uv = BABYLON.Vector2.Zero();
  59379. var color = new BABYLON.Color4(0, 0, 0, 1);
  59380. _this.calculateError(v0, v1, p, n, uv, color);
  59381. var delTr = [];
  59382. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  59383. continue;
  59384. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  59385. continue;
  59386. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  59387. continue;
  59388. var uniqueArray = [];
  59389. delTr.forEach(function (deletedT) {
  59390. if (uniqueArray.indexOf(deletedT) === -1) {
  59391. deletedT.deletePending = true;
  59392. uniqueArray.push(deletedT);
  59393. }
  59394. });
  59395. if (uniqueArray.length % 2 !== 0) {
  59396. continue;
  59397. }
  59398. v0.q = v1.q.add(v0.q);
  59399. v0.updatePosition(p);
  59400. var tStart = _this.references.length;
  59401. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  59402. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  59403. var tCount = _this.references.length - tStart;
  59404. if (tCount <= v0.triangleCount) {
  59405. if (tCount) {
  59406. for (var c = 0; c < tCount; c++) {
  59407. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  59408. }
  59409. }
  59410. }
  59411. else {
  59412. v0.triangleStart = tStart;
  59413. }
  59414. v0.triangleCount = tCount;
  59415. break;
  59416. }
  59417. }
  59418. };
  59419. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  59420. }, 0);
  59421. };
  59422. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  59423. if (triangleCount - deletedTriangles <= targetCount)
  59424. loop.breakLoop();
  59425. else {
  59426. iterationFunction(loop.index, function () {
  59427. loop.executeNext();
  59428. });
  59429. }
  59430. }, function () {
  59431. setTimeout(function () {
  59432. //reconstruct this part of the mesh
  59433. _this.reconstructMesh(submeshIndex);
  59434. successCallback();
  59435. }, 0);
  59436. });
  59437. };
  59438. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  59439. var _this = this;
  59440. this.vertices = [];
  59441. this.triangles = [];
  59442. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59443. var indices = this._mesh.getIndices();
  59444. var submesh = this._mesh.subMeshes[submeshIndex];
  59445. var findInVertices = function (positionToSearch) {
  59446. if (optimizeMesh) {
  59447. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  59448. if (_this.vertices[ii].position.equals(positionToSearch)) {
  59449. return _this.vertices[ii];
  59450. }
  59451. }
  59452. }
  59453. return null;
  59454. };
  59455. var vertexReferences = [];
  59456. var vertexInit = function (i) {
  59457. var offset = i + submesh.verticesStart;
  59458. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  59459. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  59460. vertex.originalOffsets.push(offset);
  59461. if (vertex.id === _this.vertices.length) {
  59462. _this.vertices.push(vertex);
  59463. }
  59464. vertexReferences.push(vertex.id);
  59465. };
  59466. //var totalVertices = mesh.getTotalVertices();
  59467. var totalVertices = submesh.verticesCount;
  59468. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  59469. var indicesInit = function (i) {
  59470. var offset = (submesh.indexStart / 3) + i;
  59471. var pos = (offset * 3);
  59472. var i0 = indices[pos + 0];
  59473. var i1 = indices[pos + 1];
  59474. var i2 = indices[pos + 2];
  59475. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  59476. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  59477. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  59478. var triangle = new DecimationTriangle([v0, v1, v2]);
  59479. triangle.originalOffset = pos;
  59480. _this.triangles.push(triangle);
  59481. };
  59482. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  59483. _this.init(callback);
  59484. });
  59485. });
  59486. };
  59487. QuadraticErrorSimplification.prototype.init = function (callback) {
  59488. var _this = this;
  59489. var triangleInit1 = function (i) {
  59490. var t = _this.triangles[i];
  59491. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  59492. for (var j = 0; j < 3; j++) {
  59493. 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))));
  59494. }
  59495. };
  59496. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  59497. var triangleInit2 = function (i) {
  59498. var t = _this.triangles[i];
  59499. for (var j = 0; j < 3; ++j) {
  59500. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  59501. }
  59502. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  59503. };
  59504. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  59505. _this.initialized = true;
  59506. callback();
  59507. });
  59508. });
  59509. };
  59510. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  59511. var newTriangles = [];
  59512. var i;
  59513. for (i = 0; i < this.vertices.length; ++i) {
  59514. this.vertices[i].triangleCount = 0;
  59515. }
  59516. var t;
  59517. var j;
  59518. for (i = 0; i < this.triangles.length; ++i) {
  59519. if (!this.triangles[i].deleted) {
  59520. t = this.triangles[i];
  59521. for (j = 0; j < 3; ++j) {
  59522. t.vertices[j].triangleCount = 1;
  59523. }
  59524. newTriangles.push(t);
  59525. }
  59526. }
  59527. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  59528. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  59529. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  59530. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  59531. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  59532. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59533. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  59534. var vertexCount = 0;
  59535. for (i = 0; i < this.vertices.length; ++i) {
  59536. var vertex = this.vertices[i];
  59537. vertex.id = vertexCount;
  59538. if (vertex.triangleCount) {
  59539. vertex.originalOffsets.forEach(function (originalOffset) {
  59540. newPositionData.push(vertex.position.x);
  59541. newPositionData.push(vertex.position.y);
  59542. newPositionData.push(vertex.position.z);
  59543. newNormalData.push(normalData[originalOffset * 3]);
  59544. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  59545. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  59546. if (uvs && uvs.length) {
  59547. newUVsData.push(uvs[(originalOffset * 2)]);
  59548. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  59549. }
  59550. else if (colorsData && colorsData.length) {
  59551. newColorsData.push(colorsData[(originalOffset * 4)]);
  59552. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  59553. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  59554. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  59555. }
  59556. ++vertexCount;
  59557. });
  59558. }
  59559. }
  59560. var startingIndex = this._reconstructedMesh.getTotalIndices();
  59561. var startingVertex = this._reconstructedMesh.getTotalVertices();
  59562. var submeshesArray = this._reconstructedMesh.subMeshes;
  59563. this._reconstructedMesh.subMeshes = [];
  59564. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  59565. var originalIndices = this._mesh.getIndices();
  59566. for (i = 0; i < newTriangles.length; ++i) {
  59567. t = newTriangles[i]; //now get the new referencing point for each vertex
  59568. [0, 1, 2].forEach(function (idx) {
  59569. var id = originalIndices[t.originalOffset + idx];
  59570. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  59571. if (offset < 0)
  59572. offset = 0;
  59573. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  59574. });
  59575. }
  59576. //overwriting the old vertex buffers and indices.
  59577. this._reconstructedMesh.setIndices(newIndicesArray);
  59578. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  59579. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  59580. if (newUVsData.length > 0)
  59581. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  59582. if (newColorsData.length > 0)
  59583. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  59584. //create submesh
  59585. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  59586. if (submeshIndex > 0) {
  59587. this._reconstructedMesh.subMeshes = [];
  59588. submeshesArray.forEach(function (submesh) {
  59589. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  59590. });
  59591. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  59592. }
  59593. };
  59594. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  59595. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  59596. this._reconstructedMesh.material = this._mesh.material;
  59597. this._reconstructedMesh.parent = this._mesh.parent;
  59598. this._reconstructedMesh.isVisible = false;
  59599. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  59600. };
  59601. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  59602. for (var i = 0; i < vertex1.triangleCount; ++i) {
  59603. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  59604. if (t.deleted)
  59605. continue;
  59606. var s = this.references[vertex1.triangleStart + i].vertexId;
  59607. var v1 = t.vertices[(s + 1) % 3];
  59608. var v2 = t.vertices[(s + 2) % 3];
  59609. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  59610. deletedArray[i] = true;
  59611. delTr.push(t);
  59612. continue;
  59613. }
  59614. var d1 = v1.position.subtract(point);
  59615. d1 = d1.normalize();
  59616. var d2 = v2.position.subtract(point);
  59617. d2 = d2.normalize();
  59618. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  59619. return true;
  59620. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  59621. deletedArray[i] = false;
  59622. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  59623. return true;
  59624. }
  59625. return false;
  59626. };
  59627. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  59628. var newDeleted = deletedTriangles;
  59629. for (var i = 0; i < vertex.triangleCount; ++i) {
  59630. var ref = this.references[vertex.triangleStart + i];
  59631. var t = this.triangles[ref.triangleId];
  59632. if (t.deleted)
  59633. continue;
  59634. if (deletedArray[i] && t.deletePending) {
  59635. t.deleted = true;
  59636. newDeleted++;
  59637. continue;
  59638. }
  59639. t.vertices[ref.vertexId] = origVertex;
  59640. t.isDirty = true;
  59641. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  59642. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  59643. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  59644. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  59645. this.references.push(ref);
  59646. }
  59647. return newDeleted;
  59648. };
  59649. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  59650. for (var i = 0; i < this.vertices.length; ++i) {
  59651. var vCount = [];
  59652. var vId = [];
  59653. var v = this.vertices[i];
  59654. var j;
  59655. for (j = 0; j < v.triangleCount; ++j) {
  59656. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  59657. for (var ii = 0; ii < 3; ii++) {
  59658. var ofs = 0;
  59659. var vv = triangle.vertices[ii];
  59660. while (ofs < vCount.length) {
  59661. if (vId[ofs] === vv.id)
  59662. break;
  59663. ++ofs;
  59664. }
  59665. if (ofs === vCount.length) {
  59666. vCount.push(1);
  59667. vId.push(vv.id);
  59668. }
  59669. else {
  59670. vCount[ofs]++;
  59671. }
  59672. }
  59673. }
  59674. for (j = 0; j < vCount.length; ++j) {
  59675. if (vCount[j] === 1) {
  59676. this.vertices[vId[j]].isBorder = true;
  59677. }
  59678. else {
  59679. this.vertices[vId[j]].isBorder = false;
  59680. }
  59681. }
  59682. }
  59683. };
  59684. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  59685. if (identifyBorders === void 0) { identifyBorders = false; }
  59686. var i;
  59687. if (!identifyBorders) {
  59688. var newTrianglesVector = [];
  59689. for (i = 0; i < this.triangles.length; ++i) {
  59690. if (!this.triangles[i].deleted) {
  59691. newTrianglesVector.push(this.triangles[i]);
  59692. }
  59693. }
  59694. this.triangles = newTrianglesVector;
  59695. }
  59696. for (i = 0; i < this.vertices.length; ++i) {
  59697. this.vertices[i].triangleCount = 0;
  59698. this.vertices[i].triangleStart = 0;
  59699. }
  59700. var t;
  59701. var j;
  59702. var v;
  59703. for (i = 0; i < this.triangles.length; ++i) {
  59704. t = this.triangles[i];
  59705. for (j = 0; j < 3; ++j) {
  59706. v = t.vertices[j];
  59707. v.triangleCount++;
  59708. }
  59709. }
  59710. var tStart = 0;
  59711. for (i = 0; i < this.vertices.length; ++i) {
  59712. this.vertices[i].triangleStart = tStart;
  59713. tStart += this.vertices[i].triangleCount;
  59714. this.vertices[i].triangleCount = 0;
  59715. }
  59716. var newReferences = new Array(this.triangles.length * 3);
  59717. for (i = 0; i < this.triangles.length; ++i) {
  59718. t = this.triangles[i];
  59719. for (j = 0; j < 3; ++j) {
  59720. v = t.vertices[j];
  59721. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  59722. v.triangleCount++;
  59723. }
  59724. }
  59725. this.references = newReferences;
  59726. if (identifyBorders) {
  59727. this.identifyBorder();
  59728. }
  59729. };
  59730. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  59731. var x = point.x;
  59732. var y = point.y;
  59733. var z = point.z;
  59734. 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
  59735. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  59736. };
  59737. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  59738. var q = vertex1.q.add(vertex2.q);
  59739. var border = vertex1.isBorder && vertex2.isBorder;
  59740. var error = 0;
  59741. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  59742. if (qDet !== 0 && !border) {
  59743. if (!pointResult) {
  59744. pointResult = BABYLON.Vector3.Zero();
  59745. }
  59746. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  59747. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  59748. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  59749. error = this.vertexError(q, pointResult);
  59750. }
  59751. else {
  59752. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  59753. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  59754. var error1 = this.vertexError(q, vertex1.position);
  59755. var error2 = this.vertexError(q, vertex2.position);
  59756. var error3 = this.vertexError(q, p3);
  59757. error = Math.min(error1, error2, error3);
  59758. if (error === error1) {
  59759. if (pointResult) {
  59760. pointResult.copyFrom(vertex1.position);
  59761. }
  59762. }
  59763. else if (error === error2) {
  59764. if (pointResult) {
  59765. pointResult.copyFrom(vertex2.position);
  59766. }
  59767. }
  59768. else {
  59769. if (pointResult) {
  59770. pointResult.copyFrom(p3);
  59771. }
  59772. }
  59773. }
  59774. return error;
  59775. };
  59776. return QuadraticErrorSimplification;
  59777. }());
  59778. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  59779. })(BABYLON || (BABYLON = {}));
  59780. //# sourceMappingURL=babylon.meshSimplification.js.map
  59781. var BABYLON;
  59782. (function (BABYLON) {
  59783. var Internals;
  59784. (function (Internals) {
  59785. var MeshLODLevel = (function () {
  59786. function MeshLODLevel(distance, mesh) {
  59787. this.distance = distance;
  59788. this.mesh = mesh;
  59789. }
  59790. return MeshLODLevel;
  59791. }());
  59792. Internals.MeshLODLevel = MeshLODLevel;
  59793. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59794. })(BABYLON || (BABYLON = {}));
  59795. //# sourceMappingURL=babylon.meshLODLevel.js.map
  59796. var BABYLON;
  59797. (function (BABYLON) {
  59798. // Standard optimizations
  59799. var SceneOptimization = (function () {
  59800. function SceneOptimization(priority) {
  59801. if (priority === void 0) { priority = 0; }
  59802. this.priority = priority;
  59803. this.apply = function (scene) {
  59804. return true; // Return true if everything that can be done was applied
  59805. };
  59806. }
  59807. return SceneOptimization;
  59808. }());
  59809. BABYLON.SceneOptimization = SceneOptimization;
  59810. var TextureOptimization = (function (_super) {
  59811. __extends(TextureOptimization, _super);
  59812. function TextureOptimization(priority, maximumSize) {
  59813. if (priority === void 0) { priority = 0; }
  59814. if (maximumSize === void 0) { maximumSize = 1024; }
  59815. var _this = _super.call(this, priority) || this;
  59816. _this.priority = priority;
  59817. _this.maximumSize = maximumSize;
  59818. _this.apply = function (scene) {
  59819. var allDone = true;
  59820. for (var index = 0; index < scene.textures.length; index++) {
  59821. var texture = scene.textures[index];
  59822. if (!texture.canRescale) {
  59823. continue;
  59824. }
  59825. var currentSize = texture.getSize();
  59826. var maxDimension = Math.max(currentSize.width, currentSize.height);
  59827. if (maxDimension > _this.maximumSize) {
  59828. texture.scale(0.5);
  59829. allDone = false;
  59830. }
  59831. }
  59832. return allDone;
  59833. };
  59834. return _this;
  59835. }
  59836. return TextureOptimization;
  59837. }(SceneOptimization));
  59838. BABYLON.TextureOptimization = TextureOptimization;
  59839. var HardwareScalingOptimization = (function (_super) {
  59840. __extends(HardwareScalingOptimization, _super);
  59841. function HardwareScalingOptimization(priority, maximumScale) {
  59842. if (priority === void 0) { priority = 0; }
  59843. if (maximumScale === void 0) { maximumScale = 2; }
  59844. var _this = _super.call(this, priority) || this;
  59845. _this.priority = priority;
  59846. _this.maximumScale = maximumScale;
  59847. _this._currentScale = 1;
  59848. _this.apply = function (scene) {
  59849. _this._currentScale++;
  59850. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  59851. return _this._currentScale >= _this.maximumScale;
  59852. };
  59853. return _this;
  59854. }
  59855. return HardwareScalingOptimization;
  59856. }(SceneOptimization));
  59857. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  59858. var ShadowsOptimization = (function (_super) {
  59859. __extends(ShadowsOptimization, _super);
  59860. function ShadowsOptimization() {
  59861. var _this = _super !== null && _super.apply(this, arguments) || this;
  59862. _this.apply = function (scene) {
  59863. scene.shadowsEnabled = false;
  59864. return true;
  59865. };
  59866. return _this;
  59867. }
  59868. return ShadowsOptimization;
  59869. }(SceneOptimization));
  59870. BABYLON.ShadowsOptimization = ShadowsOptimization;
  59871. var PostProcessesOptimization = (function (_super) {
  59872. __extends(PostProcessesOptimization, _super);
  59873. function PostProcessesOptimization() {
  59874. var _this = _super !== null && _super.apply(this, arguments) || this;
  59875. _this.apply = function (scene) {
  59876. scene.postProcessesEnabled = false;
  59877. return true;
  59878. };
  59879. return _this;
  59880. }
  59881. return PostProcessesOptimization;
  59882. }(SceneOptimization));
  59883. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  59884. var LensFlaresOptimization = (function (_super) {
  59885. __extends(LensFlaresOptimization, _super);
  59886. function LensFlaresOptimization() {
  59887. var _this = _super !== null && _super.apply(this, arguments) || this;
  59888. _this.apply = function (scene) {
  59889. scene.lensFlaresEnabled = false;
  59890. return true;
  59891. };
  59892. return _this;
  59893. }
  59894. return LensFlaresOptimization;
  59895. }(SceneOptimization));
  59896. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  59897. var ParticlesOptimization = (function (_super) {
  59898. __extends(ParticlesOptimization, _super);
  59899. function ParticlesOptimization() {
  59900. var _this = _super !== null && _super.apply(this, arguments) || this;
  59901. _this.apply = function (scene) {
  59902. scene.particlesEnabled = false;
  59903. return true;
  59904. };
  59905. return _this;
  59906. }
  59907. return ParticlesOptimization;
  59908. }(SceneOptimization));
  59909. BABYLON.ParticlesOptimization = ParticlesOptimization;
  59910. var RenderTargetsOptimization = (function (_super) {
  59911. __extends(RenderTargetsOptimization, _super);
  59912. function RenderTargetsOptimization() {
  59913. var _this = _super !== null && _super.apply(this, arguments) || this;
  59914. _this.apply = function (scene) {
  59915. scene.renderTargetsEnabled = false;
  59916. return true;
  59917. };
  59918. return _this;
  59919. }
  59920. return RenderTargetsOptimization;
  59921. }(SceneOptimization));
  59922. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  59923. var MergeMeshesOptimization = (function (_super) {
  59924. __extends(MergeMeshesOptimization, _super);
  59925. function MergeMeshesOptimization() {
  59926. var _this = _super !== null && _super.apply(this, arguments) || this;
  59927. _this._canBeMerged = function (abstractMesh) {
  59928. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  59929. return false;
  59930. }
  59931. var mesh = abstractMesh;
  59932. if (!mesh.isVisible || !mesh.isEnabled()) {
  59933. return false;
  59934. }
  59935. if (mesh.instances.length > 0) {
  59936. return false;
  59937. }
  59938. if (mesh.skeleton || mesh.hasLODLevels) {
  59939. return false;
  59940. }
  59941. if (mesh.parent) {
  59942. return false;
  59943. }
  59944. return true;
  59945. };
  59946. _this.apply = function (scene, updateSelectionTree) {
  59947. var globalPool = scene.meshes.slice(0);
  59948. var globalLength = globalPool.length;
  59949. for (var index = 0; index < globalLength; index++) {
  59950. var currentPool = new Array();
  59951. var current = globalPool[index];
  59952. // Checks
  59953. if (!_this._canBeMerged(current)) {
  59954. continue;
  59955. }
  59956. currentPool.push(current);
  59957. // Find compatible meshes
  59958. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  59959. var otherMesh = globalPool[subIndex];
  59960. if (!_this._canBeMerged(otherMesh)) {
  59961. continue;
  59962. }
  59963. if (otherMesh.material !== current.material) {
  59964. continue;
  59965. }
  59966. if (otherMesh.checkCollisions !== current.checkCollisions) {
  59967. continue;
  59968. }
  59969. currentPool.push(otherMesh);
  59970. globalLength--;
  59971. globalPool.splice(subIndex, 1);
  59972. subIndex--;
  59973. }
  59974. if (currentPool.length < 2) {
  59975. continue;
  59976. }
  59977. // Merge meshes
  59978. BABYLON.Mesh.MergeMeshes(currentPool);
  59979. }
  59980. if (updateSelectionTree != undefined) {
  59981. if (updateSelectionTree) {
  59982. scene.createOrUpdateSelectionOctree();
  59983. }
  59984. }
  59985. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  59986. scene.createOrUpdateSelectionOctree();
  59987. }
  59988. return true;
  59989. };
  59990. return _this;
  59991. }
  59992. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  59993. get: function () {
  59994. return MergeMeshesOptimization._UpdateSelectionTree;
  59995. },
  59996. set: function (value) {
  59997. MergeMeshesOptimization._UpdateSelectionTree = value;
  59998. },
  59999. enumerable: true,
  60000. configurable: true
  60001. });
  60002. return MergeMeshesOptimization;
  60003. }(SceneOptimization));
  60004. MergeMeshesOptimization._UpdateSelectionTree = false;
  60005. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  60006. // Options
  60007. var SceneOptimizerOptions = (function () {
  60008. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  60009. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  60010. if (trackerDuration === void 0) { trackerDuration = 2000; }
  60011. this.targetFrameRate = targetFrameRate;
  60012. this.trackerDuration = trackerDuration;
  60013. this.optimizations = new Array();
  60014. }
  60015. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  60016. var result = new SceneOptimizerOptions(targetFrameRate);
  60017. var priority = 0;
  60018. result.optimizations.push(new MergeMeshesOptimization(priority));
  60019. result.optimizations.push(new ShadowsOptimization(priority));
  60020. result.optimizations.push(new LensFlaresOptimization(priority));
  60021. // Next priority
  60022. priority++;
  60023. result.optimizations.push(new PostProcessesOptimization(priority));
  60024. result.optimizations.push(new ParticlesOptimization(priority));
  60025. // Next priority
  60026. priority++;
  60027. result.optimizations.push(new TextureOptimization(priority, 1024));
  60028. return result;
  60029. };
  60030. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  60031. var result = new SceneOptimizerOptions(targetFrameRate);
  60032. var priority = 0;
  60033. result.optimizations.push(new MergeMeshesOptimization(priority));
  60034. result.optimizations.push(new ShadowsOptimization(priority));
  60035. result.optimizations.push(new LensFlaresOptimization(priority));
  60036. // Next priority
  60037. priority++;
  60038. result.optimizations.push(new PostProcessesOptimization(priority));
  60039. result.optimizations.push(new ParticlesOptimization(priority));
  60040. // Next priority
  60041. priority++;
  60042. result.optimizations.push(new TextureOptimization(priority, 512));
  60043. // Next priority
  60044. priority++;
  60045. result.optimizations.push(new RenderTargetsOptimization(priority));
  60046. // Next priority
  60047. priority++;
  60048. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  60049. return result;
  60050. };
  60051. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  60052. var result = new SceneOptimizerOptions(targetFrameRate);
  60053. var priority = 0;
  60054. result.optimizations.push(new MergeMeshesOptimization(priority));
  60055. result.optimizations.push(new ShadowsOptimization(priority));
  60056. result.optimizations.push(new LensFlaresOptimization(priority));
  60057. // Next priority
  60058. priority++;
  60059. result.optimizations.push(new PostProcessesOptimization(priority));
  60060. result.optimizations.push(new ParticlesOptimization(priority));
  60061. // Next priority
  60062. priority++;
  60063. result.optimizations.push(new TextureOptimization(priority, 256));
  60064. // Next priority
  60065. priority++;
  60066. result.optimizations.push(new RenderTargetsOptimization(priority));
  60067. // Next priority
  60068. priority++;
  60069. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  60070. return result;
  60071. };
  60072. return SceneOptimizerOptions;
  60073. }());
  60074. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  60075. // Scene optimizer tool
  60076. var SceneOptimizer = (function () {
  60077. function SceneOptimizer() {
  60078. }
  60079. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  60080. // TODO: add an epsilon
  60081. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  60082. if (onSuccess) {
  60083. onSuccess();
  60084. }
  60085. return;
  60086. }
  60087. // Apply current level of optimizations
  60088. var allDone = true;
  60089. var noOptimizationApplied = true;
  60090. for (var index = 0; index < options.optimizations.length; index++) {
  60091. var optimization = options.optimizations[index];
  60092. if (optimization.priority === currentPriorityLevel) {
  60093. noOptimizationApplied = false;
  60094. allDone = allDone && optimization.apply(scene);
  60095. }
  60096. }
  60097. // If no optimization was applied, this is a failure :(
  60098. if (noOptimizationApplied) {
  60099. if (onFailure) {
  60100. onFailure();
  60101. }
  60102. return;
  60103. }
  60104. // If all optimizations were done, move to next level
  60105. if (allDone) {
  60106. currentPriorityLevel++;
  60107. }
  60108. // Let's the system running for a specific amount of time before checking FPS
  60109. scene.executeWhenReady(function () {
  60110. setTimeout(function () {
  60111. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  60112. }, options.trackerDuration);
  60113. });
  60114. };
  60115. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  60116. if (!options) {
  60117. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  60118. }
  60119. // Let's the system running for a specific amount of time before checking FPS
  60120. scene.executeWhenReady(function () {
  60121. setTimeout(function () {
  60122. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  60123. }, options.trackerDuration);
  60124. });
  60125. };
  60126. return SceneOptimizer;
  60127. }());
  60128. BABYLON.SceneOptimizer = SceneOptimizer;
  60129. })(BABYLON || (BABYLON = {}));
  60130. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  60131. var BABYLON;
  60132. (function (BABYLON) {
  60133. var OutlineRenderer = (function () {
  60134. function OutlineRenderer(scene) {
  60135. this._scene = scene;
  60136. }
  60137. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  60138. var _this = this;
  60139. if (useOverlay === void 0) { useOverlay = false; }
  60140. var scene = this._scene;
  60141. var engine = this._scene.getEngine();
  60142. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60143. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  60144. return;
  60145. }
  60146. var mesh = subMesh.getRenderingMesh();
  60147. var material = subMesh.getMaterial();
  60148. engine.enableEffect(this._effect);
  60149. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  60150. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  60151. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  60152. // Bones
  60153. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60154. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60155. }
  60156. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  60157. // Alpha test
  60158. if (material && material.needAlphaTesting()) {
  60159. var alphaTexture = material.getAlphaTestTexture();
  60160. this._effect.setTexture("diffuseSampler", alphaTexture);
  60161. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60162. }
  60163. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  60164. };
  60165. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  60166. var defines = [];
  60167. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  60168. var mesh = subMesh.getMesh();
  60169. var material = subMesh.getMaterial();
  60170. // Alpha test
  60171. if (material && material.needAlphaTesting()) {
  60172. defines.push("#define ALPHATEST");
  60173. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60174. attribs.push(BABYLON.VertexBuffer.UVKind);
  60175. defines.push("#define UV1");
  60176. }
  60177. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  60178. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60179. defines.push("#define UV2");
  60180. }
  60181. }
  60182. // Bones
  60183. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60184. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60185. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60186. if (mesh.numBoneInfluencers > 4) {
  60187. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60188. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60189. }
  60190. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60191. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60192. }
  60193. else {
  60194. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60195. }
  60196. // Instances
  60197. if (useInstances) {
  60198. defines.push("#define INSTANCES");
  60199. attribs.push("world0");
  60200. attribs.push("world1");
  60201. attribs.push("world2");
  60202. attribs.push("world3");
  60203. }
  60204. // Get correct effect
  60205. var join = defines.join("\n");
  60206. if (this._cachedDefines !== join) {
  60207. this._cachedDefines = join;
  60208. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  60209. }
  60210. return this._effect.isReady();
  60211. };
  60212. return OutlineRenderer;
  60213. }());
  60214. BABYLON.OutlineRenderer = OutlineRenderer;
  60215. })(BABYLON || (BABYLON = {}));
  60216. //# sourceMappingURL=babylon.outlineRenderer.js.map
  60217. var BABYLON;
  60218. (function (BABYLON) {
  60219. var FaceAdjacencies = (function () {
  60220. function FaceAdjacencies() {
  60221. this.edges = new Array();
  60222. this.edgesConnectedCount = 0;
  60223. }
  60224. return FaceAdjacencies;
  60225. }());
  60226. var EdgesRenderer = (function () {
  60227. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  60228. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  60229. if (epsilon === void 0) { epsilon = 0.95; }
  60230. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  60231. this.edgesWidthScalerForOrthographic = 1000.0;
  60232. this.edgesWidthScalerForPerspective = 50.0;
  60233. this._linesPositions = new Array();
  60234. this._linesNormals = new Array();
  60235. this._linesIndices = new Array();
  60236. this._buffers = {};
  60237. this._checkVerticesInsteadOfIndices = false;
  60238. this._source = source;
  60239. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  60240. this._epsilon = epsilon;
  60241. this._prepareRessources();
  60242. this._generateEdgesLines();
  60243. }
  60244. EdgesRenderer.prototype._prepareRessources = function () {
  60245. if (this._lineShader) {
  60246. return;
  60247. }
  60248. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  60249. attributes: ["position", "normal"],
  60250. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  60251. });
  60252. this._lineShader.disableDepthWrite = true;
  60253. this._lineShader.backFaceCulling = false;
  60254. };
  60255. EdgesRenderer.prototype.dispose = function () {
  60256. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  60257. if (buffer) {
  60258. buffer.dispose();
  60259. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  60260. }
  60261. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  60262. if (buffer) {
  60263. buffer.dispose();
  60264. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  60265. }
  60266. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  60267. this._lineShader.dispose();
  60268. };
  60269. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  60270. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  60271. return 0;
  60272. }
  60273. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  60274. return 1;
  60275. }
  60276. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  60277. return 2;
  60278. }
  60279. return -1;
  60280. };
  60281. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  60282. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  60283. return 0;
  60284. }
  60285. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  60286. return 1;
  60287. }
  60288. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  60289. return 2;
  60290. }
  60291. return -1;
  60292. };
  60293. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  60294. var needToCreateLine;
  60295. if (edge === undefined) {
  60296. needToCreateLine = true;
  60297. }
  60298. else {
  60299. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  60300. needToCreateLine = dotProduct < this._epsilon;
  60301. }
  60302. if (needToCreateLine) {
  60303. var offset = this._linesPositions.length / 3;
  60304. var normal = p0.subtract(p1);
  60305. normal.normalize();
  60306. // Positions
  60307. this._linesPositions.push(p0.x);
  60308. this._linesPositions.push(p0.y);
  60309. this._linesPositions.push(p0.z);
  60310. this._linesPositions.push(p0.x);
  60311. this._linesPositions.push(p0.y);
  60312. this._linesPositions.push(p0.z);
  60313. this._linesPositions.push(p1.x);
  60314. this._linesPositions.push(p1.y);
  60315. this._linesPositions.push(p1.z);
  60316. this._linesPositions.push(p1.x);
  60317. this._linesPositions.push(p1.y);
  60318. this._linesPositions.push(p1.z);
  60319. // Normals
  60320. this._linesNormals.push(p1.x);
  60321. this._linesNormals.push(p1.y);
  60322. this._linesNormals.push(p1.z);
  60323. this._linesNormals.push(-1);
  60324. this._linesNormals.push(p1.x);
  60325. this._linesNormals.push(p1.y);
  60326. this._linesNormals.push(p1.z);
  60327. this._linesNormals.push(1);
  60328. this._linesNormals.push(p0.x);
  60329. this._linesNormals.push(p0.y);
  60330. this._linesNormals.push(p0.z);
  60331. this._linesNormals.push(-1);
  60332. this._linesNormals.push(p0.x);
  60333. this._linesNormals.push(p0.y);
  60334. this._linesNormals.push(p0.z);
  60335. this._linesNormals.push(1);
  60336. // Indices
  60337. this._linesIndices.push(offset);
  60338. this._linesIndices.push(offset + 1);
  60339. this._linesIndices.push(offset + 2);
  60340. this._linesIndices.push(offset);
  60341. this._linesIndices.push(offset + 2);
  60342. this._linesIndices.push(offset + 3);
  60343. }
  60344. };
  60345. EdgesRenderer.prototype._generateEdgesLines = function () {
  60346. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60347. var indices = this._source.getIndices();
  60348. // First let's find adjacencies
  60349. var adjacencies = new Array();
  60350. var faceNormals = new Array();
  60351. var index;
  60352. var faceAdjacencies;
  60353. // Prepare faces
  60354. for (index = 0; index < indices.length; index += 3) {
  60355. faceAdjacencies = new FaceAdjacencies();
  60356. var p0Index = indices[index];
  60357. var p1Index = indices[index + 1];
  60358. var p2Index = indices[index + 2];
  60359. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  60360. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  60361. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  60362. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  60363. faceNormal.normalize();
  60364. faceNormals.push(faceNormal);
  60365. adjacencies.push(faceAdjacencies);
  60366. }
  60367. // Scan
  60368. for (index = 0; index < adjacencies.length; index++) {
  60369. faceAdjacencies = adjacencies[index];
  60370. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  60371. var otherFaceAdjacencies = adjacencies[otherIndex];
  60372. if (faceAdjacencies.edgesConnectedCount === 3) {
  60373. break;
  60374. }
  60375. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  60376. continue;
  60377. }
  60378. var otherP0 = indices[otherIndex * 3];
  60379. var otherP1 = indices[otherIndex * 3 + 1];
  60380. var otherP2 = indices[otherIndex * 3 + 2];
  60381. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  60382. var otherEdgeIndex;
  60383. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  60384. continue;
  60385. }
  60386. switch (edgeIndex) {
  60387. case 0:
  60388. if (this._checkVerticesInsteadOfIndices) {
  60389. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  60390. }
  60391. else {
  60392. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  60393. }
  60394. break;
  60395. case 1:
  60396. if (this._checkVerticesInsteadOfIndices) {
  60397. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  60398. }
  60399. else {
  60400. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  60401. }
  60402. break;
  60403. case 2:
  60404. if (this._checkVerticesInsteadOfIndices) {
  60405. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  60406. }
  60407. else {
  60408. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  60409. }
  60410. break;
  60411. }
  60412. if (otherEdgeIndex === -1) {
  60413. continue;
  60414. }
  60415. faceAdjacencies.edges[edgeIndex] = otherIndex;
  60416. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  60417. faceAdjacencies.edgesConnectedCount++;
  60418. otherFaceAdjacencies.edgesConnectedCount++;
  60419. if (faceAdjacencies.edgesConnectedCount === 3) {
  60420. break;
  60421. }
  60422. }
  60423. }
  60424. }
  60425. // Create lines
  60426. for (index = 0; index < adjacencies.length; index++) {
  60427. // 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
  60428. var current = adjacencies[index];
  60429. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  60430. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  60431. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  60432. }
  60433. // Merge into a single mesh
  60434. var engine = this._source.getScene().getEngine();
  60435. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  60436. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  60437. this._ib = engine.createIndexBuffer(this._linesIndices);
  60438. this._indicesCount = this._linesIndices.length;
  60439. };
  60440. EdgesRenderer.prototype.render = function () {
  60441. if (!this._lineShader.isReady()) {
  60442. return;
  60443. }
  60444. var scene = this._source.getScene();
  60445. var engine = scene.getEngine();
  60446. this._lineShader._preBind();
  60447. // VBOs
  60448. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  60449. scene.resetCachedMaterial();
  60450. this._lineShader.setColor4("color", this._source.edgesColor);
  60451. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  60452. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  60453. }
  60454. else {
  60455. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  60456. }
  60457. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  60458. this._lineShader.bind(this._source.getWorldMatrix());
  60459. // Draw order
  60460. engine.draw(true, 0, this._indicesCount);
  60461. this._lineShader.unbind();
  60462. engine.setDepthWrite(true);
  60463. };
  60464. return EdgesRenderer;
  60465. }());
  60466. BABYLON.EdgesRenderer = EdgesRenderer;
  60467. })(BABYLON || (BABYLON = {}));
  60468. //# sourceMappingURL=babylon.edgesRenderer.js.map
  60469. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  60470. /// <reference path="..\Math\babylon.math.ts" />
  60471. var BABYLON;
  60472. (function (BABYLON) {
  60473. /**
  60474. * Special Glow Blur post process only blurring the alpha channel
  60475. * It enforces keeping the most luminous color in the color channel.
  60476. */
  60477. var GlowBlurPostProcess = (function (_super) {
  60478. __extends(GlowBlurPostProcess, _super);
  60479. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  60480. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  60481. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  60482. _this.direction = direction;
  60483. _this.blurWidth = blurWidth;
  60484. _this.onApplyObservable.add(function (effect) {
  60485. effect.setFloat2("screenSize", _this.width, _this.height);
  60486. effect.setVector2("direction", _this.direction);
  60487. effect.setFloat("blurWidth", _this.blurWidth);
  60488. });
  60489. return _this;
  60490. }
  60491. return GlowBlurPostProcess;
  60492. }(BABYLON.PostProcess));
  60493. /**
  60494. * The highlight layer Helps adding a glow effect around a mesh.
  60495. *
  60496. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  60497. * glowy meshes to your scene.
  60498. *
  60499. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  60500. */
  60501. var HighlightLayer = (function () {
  60502. /**
  60503. * Instantiates a new highlight Layer and references it to the scene..
  60504. * @param name The name of the layer
  60505. * @param scene The scene to use the layer in
  60506. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  60507. */
  60508. function HighlightLayer(name, scene, options) {
  60509. this.name = name;
  60510. this._vertexBuffers = {};
  60511. this._mainTextureDesiredSize = { width: 0, height: 0 };
  60512. this._meshes = {};
  60513. this._maxSize = 0;
  60514. this._shouldRender = false;
  60515. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  60516. this._excludedMeshes = {};
  60517. /**
  60518. * Specifies whether or not the inner glow is ACTIVE in the layer.
  60519. */
  60520. this.innerGlow = true;
  60521. /**
  60522. * Specifies whether or not the outer glow is ACTIVE in the layer.
  60523. */
  60524. this.outerGlow = true;
  60525. /**
  60526. * Specifies wether the highlight layer is enabled or not.
  60527. */
  60528. this.isEnabled = true;
  60529. /**
  60530. * An event triggered when the highlight layer has been disposed.
  60531. * @type {BABYLON.Observable}
  60532. */
  60533. this.onDisposeObservable = new BABYLON.Observable();
  60534. /**
  60535. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  60536. * @type {BABYLON.Observable}
  60537. */
  60538. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  60539. /**
  60540. * An event triggered when the highlight layer is being blurred.
  60541. * @type {BABYLON.Observable}
  60542. */
  60543. this.onBeforeBlurObservable = new BABYLON.Observable();
  60544. /**
  60545. * An event triggered when the highlight layer has been blurred.
  60546. * @type {BABYLON.Observable}
  60547. */
  60548. this.onAfterBlurObservable = new BABYLON.Observable();
  60549. /**
  60550. * An event triggered when the glowing blurred texture is being merged in the scene.
  60551. * @type {BABYLON.Observable}
  60552. */
  60553. this.onBeforeComposeObservable = new BABYLON.Observable();
  60554. /**
  60555. * An event triggered when the glowing blurred texture has been merged in the scene.
  60556. * @type {BABYLON.Observable}
  60557. */
  60558. this.onAfterComposeObservable = new BABYLON.Observable();
  60559. /**
  60560. * An event triggered when the highlight layer changes its size.
  60561. * @type {BABYLON.Observable}
  60562. */
  60563. this.onSizeChangedObservable = new BABYLON.Observable();
  60564. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  60565. var engine = scene.getEngine();
  60566. this._engine = engine;
  60567. this._maxSize = this._engine.getCaps().maxTextureSize;
  60568. this._scene.highlightLayers.push(this);
  60569. // Warn on stencil.
  60570. if (!this._engine.isStencilEnable) {
  60571. 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 }");
  60572. }
  60573. // Adapt options
  60574. this._options = options || {
  60575. mainTextureRatio: 0.25,
  60576. blurTextureSizeRatio: 0.5,
  60577. blurHorizontalSize: 1,
  60578. blurVerticalSize: 1,
  60579. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  60580. };
  60581. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  60582. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  60583. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  60584. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  60585. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  60586. // VBO
  60587. var vertices = [];
  60588. vertices.push(1, 1);
  60589. vertices.push(-1, 1);
  60590. vertices.push(-1, -1);
  60591. vertices.push(1, -1);
  60592. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  60593. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  60594. // Indices
  60595. var indices = [];
  60596. indices.push(0);
  60597. indices.push(1);
  60598. indices.push(2);
  60599. indices.push(0);
  60600. indices.push(2);
  60601. indices.push(3);
  60602. this._indexBuffer = engine.createIndexBuffer(indices);
  60603. // Effect
  60604. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  60605. // Render target
  60606. this.setMainTextureSize();
  60607. // Create Textures and post processes
  60608. this.createTextureAndPostProcesses();
  60609. }
  60610. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  60611. /**
  60612. * Gets the horizontal size of the blur.
  60613. */
  60614. get: function () {
  60615. return this._horizontalBlurPostprocess.blurWidth;
  60616. },
  60617. /**
  60618. * Specifies the horizontal size of the blur.
  60619. */
  60620. set: function (value) {
  60621. this._horizontalBlurPostprocess.blurWidth = value;
  60622. },
  60623. enumerable: true,
  60624. configurable: true
  60625. });
  60626. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  60627. /**
  60628. * Gets the vertical size of the blur.
  60629. */
  60630. get: function () {
  60631. return this._verticalBlurPostprocess.blurWidth;
  60632. },
  60633. /**
  60634. * Specifies the vertical size of the blur.
  60635. */
  60636. set: function (value) {
  60637. this._verticalBlurPostprocess.blurWidth = value;
  60638. },
  60639. enumerable: true,
  60640. configurable: true
  60641. });
  60642. Object.defineProperty(HighlightLayer.prototype, "camera", {
  60643. /**
  60644. * Gets the camera attached to the layer.
  60645. */
  60646. get: function () {
  60647. return this._options.camera;
  60648. },
  60649. enumerable: true,
  60650. configurable: true
  60651. });
  60652. /**
  60653. * Creates the render target textures and post processes used in the highlight layer.
  60654. */
  60655. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  60656. var _this = this;
  60657. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  60658. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  60659. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  60660. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  60661. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  60662. width: this._mainTextureDesiredSize.width,
  60663. height: this._mainTextureDesiredSize.height
  60664. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  60665. this._mainTexture.activeCamera = this._options.camera;
  60666. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60667. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60668. this._mainTexture.anisotropicFilteringLevel = 1;
  60669. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60670. this._mainTexture.renderParticles = false;
  60671. this._mainTexture.renderList = null;
  60672. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  60673. width: blurTextureWidth,
  60674. height: blurTextureHeight
  60675. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  60676. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60677. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60678. this._blurTexture.anisotropicFilteringLevel = 16;
  60679. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60680. this._blurTexture.renderParticles = false;
  60681. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  60682. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  60683. effect.setTexture("textureSampler", _this._mainTexture);
  60684. });
  60685. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  60686. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  60687. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  60688. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  60689. });
  60690. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  60691. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  60692. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  60693. });
  60694. }
  60695. else {
  60696. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  60697. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  60698. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  60699. });
  60700. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  60701. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  60702. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  60703. });
  60704. }
  60705. this._mainTexture.onAfterUnbindObservable.add(function () {
  60706. _this.onBeforeBlurObservable.notifyObservers(_this);
  60707. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  60708. _this.onAfterBlurObservable.notifyObservers(_this);
  60709. });
  60710. // Custom render function
  60711. var renderSubMesh = function (subMesh) {
  60712. var mesh = subMesh.getRenderingMesh();
  60713. var scene = _this._scene;
  60714. var engine = scene.getEngine();
  60715. // Culling
  60716. engine.setState(subMesh.getMaterial().backFaceCulling);
  60717. // Managing instances
  60718. var batch = mesh._getInstancesRenderList(subMesh._id);
  60719. if (batch.mustReturn) {
  60720. return;
  60721. }
  60722. // Excluded Mesh
  60723. if (_this._excludedMeshes[mesh.uniqueId]) {
  60724. return;
  60725. }
  60726. ;
  60727. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  60728. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  60729. var material = subMesh.getMaterial();
  60730. var emissiveTexture = null;
  60731. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  60732. emissiveTexture = material.emissiveTexture;
  60733. }
  60734. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  60735. engine.enableEffect(_this._glowMapGenerationEffect);
  60736. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  60737. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  60738. if (highlightLayerMesh) {
  60739. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  60740. }
  60741. else {
  60742. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  60743. }
  60744. // Alpha test
  60745. if (material && material.needAlphaTesting()) {
  60746. var alphaTexture = material.getAlphaTestTexture();
  60747. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  60748. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  60749. }
  60750. // Glow emissive only
  60751. if (emissiveTexture) {
  60752. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  60753. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  60754. }
  60755. // Bones
  60756. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60757. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  60758. }
  60759. // Draw
  60760. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  60761. }
  60762. else {
  60763. // Need to reset refresh rate of the shadowMap
  60764. _this._mainTexture.resetRefreshCounter();
  60765. }
  60766. };
  60767. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  60768. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  60769. var index;
  60770. for (index = 0; index < opaqueSubMeshes.length; index++) {
  60771. renderSubMesh(opaqueSubMeshes.data[index]);
  60772. }
  60773. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  60774. renderSubMesh(alphaTestSubMeshes.data[index]);
  60775. }
  60776. for (index = 0; index < transparentSubMeshes.length; index++) {
  60777. renderSubMesh(transparentSubMeshes.data[index]);
  60778. }
  60779. };
  60780. this._mainTexture.onClearObservable.add(function (engine) {
  60781. engine.clear(HighlightLayer.neutralColor, true, true, true);
  60782. });
  60783. };
  60784. /**
  60785. * Checks for the readiness of the element composing the layer.
  60786. * @param subMesh the mesh to check for
  60787. * @param useInstances specify wether or not to use instances to render the mesh
  60788. * @param emissiveTexture the associated emissive texture used to generate the glow
  60789. * @return true if ready otherwise, false
  60790. */
  60791. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  60792. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  60793. return false;
  60794. }
  60795. var defines = [];
  60796. var attribs = [BABYLON.VertexBuffer.PositionKind];
  60797. var mesh = subMesh.getMesh();
  60798. var material = subMesh.getMaterial();
  60799. var uv1 = false;
  60800. var uv2 = false;
  60801. // Alpha test
  60802. if (material && material.needAlphaTesting()) {
  60803. var alphaTexture = material.getAlphaTestTexture();
  60804. if (alphaTexture) {
  60805. defines.push("#define ALPHATEST");
  60806. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  60807. alphaTexture.coordinatesIndex === 1) {
  60808. defines.push("#define DIFFUSEUV2");
  60809. uv2 = true;
  60810. }
  60811. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60812. defines.push("#define DIFFUSEUV1");
  60813. uv1 = true;
  60814. }
  60815. }
  60816. }
  60817. // Emissive
  60818. if (emissiveTexture) {
  60819. defines.push("#define EMISSIVE");
  60820. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  60821. emissiveTexture.coordinatesIndex === 1) {
  60822. defines.push("#define EMISSIVEUV2");
  60823. uv2 = true;
  60824. }
  60825. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  60826. defines.push("#define EMISSIVEUV1");
  60827. uv1 = true;
  60828. }
  60829. }
  60830. if (uv1) {
  60831. attribs.push(BABYLON.VertexBuffer.UVKind);
  60832. defines.push("#define UV1");
  60833. }
  60834. if (uv2) {
  60835. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  60836. defines.push("#define UV2");
  60837. }
  60838. // Bones
  60839. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60840. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60841. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60842. if (mesh.numBoneInfluencers > 4) {
  60843. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60844. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60845. }
  60846. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60847. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60848. }
  60849. else {
  60850. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60851. }
  60852. // Instances
  60853. if (useInstances) {
  60854. defines.push("#define INSTANCES");
  60855. attribs.push("world0");
  60856. attribs.push("world1");
  60857. attribs.push("world2");
  60858. attribs.push("world3");
  60859. }
  60860. // Get correct effect
  60861. var join = defines.join("\n");
  60862. if (this._cachedDefines !== join) {
  60863. this._cachedDefines = join;
  60864. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  60865. }
  60866. return this._glowMapGenerationEffect.isReady();
  60867. };
  60868. /**
  60869. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  60870. */
  60871. HighlightLayer.prototype.render = function () {
  60872. var currentEffect = this._glowMapMergeEffect;
  60873. // Check
  60874. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  60875. return;
  60876. var engine = this._scene.getEngine();
  60877. this.onBeforeComposeObservable.notifyObservers(this);
  60878. // Render
  60879. engine.enableEffect(currentEffect);
  60880. engine.setState(false);
  60881. // Cache
  60882. var previousStencilBuffer = engine.getStencilBuffer();
  60883. var previousStencilFunction = engine.getStencilFunction();
  60884. var previousStencilMask = engine.getStencilMask();
  60885. var previousAlphaMode = engine.getAlphaMode();
  60886. // Texture
  60887. currentEffect.setTexture("textureSampler", this._blurTexture);
  60888. // VBOs
  60889. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  60890. // Draw order
  60891. engine.setAlphaMode(this._options.alphaBlendingMode);
  60892. engine.setStencilMask(0x00);
  60893. engine.setStencilBuffer(true);
  60894. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  60895. if (this.outerGlow) {
  60896. currentEffect.setFloat("offset", 0);
  60897. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  60898. engine.draw(true, 0, 6);
  60899. }
  60900. if (this.innerGlow) {
  60901. currentEffect.setFloat("offset", 1);
  60902. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  60903. engine.draw(true, 0, 6);
  60904. }
  60905. // Restore Cache
  60906. engine.setStencilFunction(previousStencilFunction);
  60907. engine.setStencilMask(previousStencilMask);
  60908. engine.setAlphaMode(previousAlphaMode);
  60909. engine.setStencilBuffer(previousStencilBuffer);
  60910. this.onAfterComposeObservable.notifyObservers(this);
  60911. // Handle size changes.
  60912. var size = this._mainTexture.getSize();
  60913. this.setMainTextureSize();
  60914. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  60915. // Recreate RTT and post processes on size change.
  60916. this.onSizeChangedObservable.notifyObservers(this);
  60917. this.disposeTextureAndPostProcesses();
  60918. this.createTextureAndPostProcesses();
  60919. }
  60920. };
  60921. /**
  60922. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  60923. * @param mesh The mesh to exclude from the highlight layer
  60924. */
  60925. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  60926. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  60927. if (!meshExcluded) {
  60928. this._excludedMeshes[mesh.uniqueId] = {
  60929. mesh: mesh,
  60930. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  60931. mesh.getEngine().setStencilBuffer(false);
  60932. }),
  60933. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  60934. mesh.getEngine().setStencilBuffer(true);
  60935. }),
  60936. };
  60937. }
  60938. };
  60939. /**
  60940. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  60941. * @param mesh The mesh to highlight
  60942. */
  60943. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  60944. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  60945. if (meshExcluded) {
  60946. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  60947. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  60948. }
  60949. this._excludedMeshes[mesh.uniqueId] = undefined;
  60950. };
  60951. /**
  60952. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  60953. * @param mesh The mesh to highlight
  60954. * @param color The color of the highlight
  60955. * @param glowEmissiveOnly Extract the glow from the emissive texture
  60956. */
  60957. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  60958. var _this = this;
  60959. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  60960. var meshHighlight = this._meshes[mesh.uniqueId];
  60961. if (meshHighlight) {
  60962. meshHighlight.color = color;
  60963. }
  60964. else {
  60965. this._meshes[mesh.uniqueId] = {
  60966. mesh: mesh,
  60967. color: color,
  60968. // Lambda required for capture due to Observable this context
  60969. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  60970. if (_this._excludedMeshes[mesh.uniqueId]) {
  60971. _this.defaultStencilReference(mesh);
  60972. }
  60973. else {
  60974. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  60975. }
  60976. }),
  60977. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  60978. glowEmissiveOnly: glowEmissiveOnly
  60979. };
  60980. }
  60981. this._shouldRender = true;
  60982. };
  60983. /**
  60984. * Remove a mesh from the highlight layer in order to make it stop glowing.
  60985. * @param mesh The mesh to highlight
  60986. */
  60987. HighlightLayer.prototype.removeMesh = function (mesh) {
  60988. var meshHighlight = this._meshes[mesh.uniqueId];
  60989. if (meshHighlight) {
  60990. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  60991. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  60992. }
  60993. this._meshes[mesh.uniqueId] = undefined;
  60994. this._shouldRender = false;
  60995. for (var meshHighlightToCheck in this._meshes) {
  60996. if (meshHighlightToCheck) {
  60997. this._shouldRender = true;
  60998. break;
  60999. }
  61000. }
  61001. };
  61002. /**
  61003. * Returns true if the layer contains information to display, otherwise false.
  61004. */
  61005. HighlightLayer.prototype.shouldRender = function () {
  61006. return this.isEnabled && this._shouldRender;
  61007. };
  61008. /**
  61009. * Sets the main texture desired size which is the closest power of two
  61010. * of the engine canvas size.
  61011. */
  61012. HighlightLayer.prototype.setMainTextureSize = function () {
  61013. if (this._options.mainTextureFixedSize) {
  61014. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  61015. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  61016. }
  61017. else {
  61018. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  61019. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  61020. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  61021. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  61022. }
  61023. };
  61024. /**
  61025. * Force the stencil to the normal expected value for none glowing parts
  61026. */
  61027. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  61028. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  61029. };
  61030. /**
  61031. * Dispose only the render target textures and post process.
  61032. */
  61033. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  61034. this._blurTexture.dispose();
  61035. this._mainTexture.dispose();
  61036. this._downSamplePostprocess.dispose();
  61037. this._horizontalBlurPostprocess.dispose();
  61038. this._verticalBlurPostprocess.dispose();
  61039. };
  61040. /**
  61041. * Dispose the highlight layer and free resources.
  61042. */
  61043. HighlightLayer.prototype.dispose = function () {
  61044. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  61045. if (vertexBuffer) {
  61046. vertexBuffer.dispose();
  61047. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  61048. }
  61049. if (this._indexBuffer) {
  61050. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  61051. this._indexBuffer = null;
  61052. }
  61053. // Clean textures and post processes
  61054. this.disposeTextureAndPostProcesses();
  61055. // Clean mesh references
  61056. for (var id in this._meshes) {
  61057. var meshHighlight = this._meshes[id];
  61058. if (meshHighlight && meshHighlight.mesh) {
  61059. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  61060. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  61061. }
  61062. }
  61063. this._meshes = null;
  61064. for (var id in this._excludedMeshes) {
  61065. var meshHighlight = this._excludedMeshes[id];
  61066. if (meshHighlight) {
  61067. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  61068. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  61069. }
  61070. }
  61071. this._excludedMeshes = null;
  61072. // Remove from scene
  61073. var index = this._scene.highlightLayers.indexOf(this, 0);
  61074. if (index > -1) {
  61075. this._scene.highlightLayers.splice(index, 1);
  61076. }
  61077. // Callback
  61078. this.onDisposeObservable.notifyObservers(this);
  61079. this.onDisposeObservable.clear();
  61080. this.onBeforeRenderMainTextureObservable.clear();
  61081. this.onBeforeBlurObservable.clear();
  61082. this.onBeforeComposeObservable.clear();
  61083. this.onAfterComposeObservable.clear();
  61084. this.onSizeChangedObservable.clear();
  61085. };
  61086. return HighlightLayer;
  61087. }());
  61088. /**
  61089. * The neutral color used during the preparation of the glow effect.
  61090. * This is black by default as the blend operation is a blend operation.
  61091. */
  61092. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  61093. /**
  61094. * Stencil value used for glowing meshes.
  61095. */
  61096. HighlightLayer.glowingMeshStencilReference = 0x02;
  61097. /**
  61098. * Stencil value used for the other meshes in the scene.
  61099. */
  61100. HighlightLayer.normalMeshStencilReference = 0x01;
  61101. BABYLON.HighlightLayer = HighlightLayer;
  61102. })(BABYLON || (BABYLON = {}));
  61103. //# sourceMappingURL=babylon.highlightlayer.js.map
  61104. var BABYLON;
  61105. (function (BABYLON) {
  61106. var MeshAssetTask = (function () {
  61107. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  61108. this.name = name;
  61109. this.meshesNames = meshesNames;
  61110. this.rootUrl = rootUrl;
  61111. this.sceneFilename = sceneFilename;
  61112. this.isCompleted = false;
  61113. }
  61114. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61115. var _this = this;
  61116. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  61117. _this.loadedMeshes = meshes;
  61118. _this.loadedParticleSystems = particleSystems;
  61119. _this.loadedSkeletons = skeletons;
  61120. _this.isCompleted = true;
  61121. if (_this.onSuccess) {
  61122. _this.onSuccess(_this);
  61123. }
  61124. onSuccess();
  61125. }, null, function () {
  61126. if (_this.onError) {
  61127. _this.onError(_this);
  61128. }
  61129. onError();
  61130. });
  61131. };
  61132. return MeshAssetTask;
  61133. }());
  61134. BABYLON.MeshAssetTask = MeshAssetTask;
  61135. var TextFileAssetTask = (function () {
  61136. function TextFileAssetTask(name, url) {
  61137. this.name = name;
  61138. this.url = url;
  61139. this.isCompleted = false;
  61140. }
  61141. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61142. var _this = this;
  61143. BABYLON.Tools.LoadFile(this.url, function (data) {
  61144. _this.text = data;
  61145. _this.isCompleted = true;
  61146. if (_this.onSuccess) {
  61147. _this.onSuccess(_this);
  61148. }
  61149. onSuccess();
  61150. }, null, scene.database, false, function () {
  61151. if (_this.onError) {
  61152. _this.onError(_this);
  61153. }
  61154. onError();
  61155. });
  61156. };
  61157. return TextFileAssetTask;
  61158. }());
  61159. BABYLON.TextFileAssetTask = TextFileAssetTask;
  61160. var BinaryFileAssetTask = (function () {
  61161. function BinaryFileAssetTask(name, url) {
  61162. this.name = name;
  61163. this.url = url;
  61164. this.isCompleted = false;
  61165. }
  61166. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61167. var _this = this;
  61168. BABYLON.Tools.LoadFile(this.url, function (data) {
  61169. _this.data = data;
  61170. _this.isCompleted = true;
  61171. if (_this.onSuccess) {
  61172. _this.onSuccess(_this);
  61173. }
  61174. onSuccess();
  61175. }, null, scene.database, true, function () {
  61176. if (_this.onError) {
  61177. _this.onError(_this);
  61178. }
  61179. onError();
  61180. });
  61181. };
  61182. return BinaryFileAssetTask;
  61183. }());
  61184. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  61185. var ImageAssetTask = (function () {
  61186. function ImageAssetTask(name, url) {
  61187. this.name = name;
  61188. this.url = url;
  61189. this.isCompleted = false;
  61190. }
  61191. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61192. var _this = this;
  61193. var img = new Image();
  61194. BABYLON.Tools.SetCorsBehavior(this.url, img);
  61195. img.onload = function () {
  61196. _this.image = img;
  61197. _this.isCompleted = true;
  61198. if (_this.onSuccess) {
  61199. _this.onSuccess(_this);
  61200. }
  61201. onSuccess();
  61202. };
  61203. img.onerror = function () {
  61204. if (_this.onError) {
  61205. _this.onError(_this);
  61206. }
  61207. onError();
  61208. };
  61209. img.src = this.url;
  61210. };
  61211. return ImageAssetTask;
  61212. }());
  61213. BABYLON.ImageAssetTask = ImageAssetTask;
  61214. var TextureAssetTask = (function () {
  61215. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  61216. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61217. this.name = name;
  61218. this.url = url;
  61219. this.noMipmap = noMipmap;
  61220. this.invertY = invertY;
  61221. this.samplingMode = samplingMode;
  61222. this.isCompleted = false;
  61223. }
  61224. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61225. var _this = this;
  61226. var onload = function () {
  61227. _this.isCompleted = true;
  61228. if (_this.onSuccess) {
  61229. _this.onSuccess(_this);
  61230. }
  61231. onSuccess();
  61232. };
  61233. var onerror = function () {
  61234. if (_this.onError) {
  61235. _this.onError(_this);
  61236. }
  61237. onError();
  61238. };
  61239. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  61240. };
  61241. return TextureAssetTask;
  61242. }());
  61243. BABYLON.TextureAssetTask = TextureAssetTask;
  61244. var CubeTextureAssetTask = (function () {
  61245. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  61246. this.name = name;
  61247. this.url = url;
  61248. this.extensions = extensions;
  61249. this.noMipmap = noMipmap;
  61250. this.files = files;
  61251. this.isCompleted = false;
  61252. }
  61253. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61254. var _this = this;
  61255. var onload = function () {
  61256. _this.isCompleted = true;
  61257. if (_this.onSuccess) {
  61258. _this.onSuccess(_this);
  61259. }
  61260. onSuccess();
  61261. };
  61262. var onerror = function () {
  61263. if (_this.onError) {
  61264. _this.onError(_this);
  61265. }
  61266. onError();
  61267. };
  61268. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  61269. };
  61270. return CubeTextureAssetTask;
  61271. }());
  61272. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  61273. var HDRCubeTextureAssetTask = (function () {
  61274. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  61275. if (noMipmap === void 0) { noMipmap = false; }
  61276. if (generateHarmonics === void 0) { generateHarmonics = true; }
  61277. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  61278. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  61279. this.name = name;
  61280. this.url = url;
  61281. this.size = size;
  61282. this.noMipmap = noMipmap;
  61283. this.generateHarmonics = generateHarmonics;
  61284. this.useInGammaSpace = useInGammaSpace;
  61285. this.usePMREMGenerator = usePMREMGenerator;
  61286. this.isCompleted = false;
  61287. }
  61288. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  61289. var _this = this;
  61290. var onload = function () {
  61291. _this.isCompleted = true;
  61292. if (_this.onSuccess) {
  61293. _this.onSuccess(_this);
  61294. }
  61295. onSuccess();
  61296. };
  61297. var onerror = function () {
  61298. if (_this.onError) {
  61299. _this.onError(_this);
  61300. }
  61301. onError();
  61302. };
  61303. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  61304. };
  61305. return HDRCubeTextureAssetTask;
  61306. }());
  61307. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  61308. var AssetsManager = (function () {
  61309. function AssetsManager(scene) {
  61310. this.tasks = new Array();
  61311. this.waitingTasksCount = 0;
  61312. this.useDefaultLoadingScreen = true;
  61313. this._scene = scene;
  61314. }
  61315. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  61316. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  61317. this.tasks.push(task);
  61318. return task;
  61319. };
  61320. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  61321. var task = new TextFileAssetTask(taskName, url);
  61322. this.tasks.push(task);
  61323. return task;
  61324. };
  61325. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  61326. var task = new BinaryFileAssetTask(taskName, url);
  61327. this.tasks.push(task);
  61328. return task;
  61329. };
  61330. AssetsManager.prototype.addImageTask = function (taskName, url) {
  61331. var task = new ImageAssetTask(taskName, url);
  61332. this.tasks.push(task);
  61333. return task;
  61334. };
  61335. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  61336. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61337. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  61338. this.tasks.push(task);
  61339. return task;
  61340. };
  61341. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  61342. this.waitingTasksCount--;
  61343. if (this.waitingTasksCount === 0) {
  61344. if (this.onFinish) {
  61345. this.onFinish(this.tasks);
  61346. }
  61347. this._scene.getEngine().hideLoadingUI();
  61348. }
  61349. };
  61350. AssetsManager.prototype._runTask = function (task) {
  61351. var _this = this;
  61352. task.run(this._scene, function () {
  61353. if (_this.onTaskSuccess) {
  61354. _this.onTaskSuccess(task);
  61355. }
  61356. _this._decreaseWaitingTasksCount();
  61357. }, function () {
  61358. if (_this.onTaskError) {
  61359. _this.onTaskError(task);
  61360. }
  61361. _this._decreaseWaitingTasksCount();
  61362. });
  61363. };
  61364. AssetsManager.prototype.reset = function () {
  61365. this.tasks = new Array();
  61366. return this;
  61367. };
  61368. AssetsManager.prototype.load = function () {
  61369. this.waitingTasksCount = this.tasks.length;
  61370. if (this.waitingTasksCount === 0) {
  61371. if (this.onFinish) {
  61372. this.onFinish(this.tasks);
  61373. }
  61374. return this;
  61375. }
  61376. if (this.useDefaultLoadingScreen) {
  61377. this._scene.getEngine().displayLoadingUI();
  61378. }
  61379. for (var index = 0; index < this.tasks.length; index++) {
  61380. var task = this.tasks[index];
  61381. this._runTask(task);
  61382. }
  61383. return this;
  61384. };
  61385. return AssetsManager;
  61386. }());
  61387. BABYLON.AssetsManager = AssetsManager;
  61388. })(BABYLON || (BABYLON = {}));
  61389. //# sourceMappingURL=babylon.assetsManager.js.map
  61390. var BABYLON;
  61391. (function (BABYLON) {
  61392. var MapTexture = (function (_super) {
  61393. __extends(MapTexture, _super);
  61394. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  61395. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  61396. if (useMipMap === void 0) { useMipMap = false; }
  61397. if (margin === void 0) { margin = 0; }
  61398. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  61399. _this.name = name;
  61400. _this._size = size;
  61401. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61402. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61403. // Create the rectPackMap that will allocate portion of the texture
  61404. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  61405. // Create the texture that will store the content
  61406. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  61407. return _this;
  61408. }
  61409. /**
  61410. * Allocate a rectangle of a given size in the texture map
  61411. * @param size the size of the rectangle to allocation
  61412. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  61413. */
  61414. MapTexture.prototype.allocateRect = function (size) {
  61415. return this._rectPackingMap.addRect(size);
  61416. };
  61417. /**
  61418. * Free a given rectangle from the texture map
  61419. * @param rectInfo the instance corresponding to the rect to free.
  61420. */
  61421. MapTexture.prototype.freeRect = function (rectInfo) {
  61422. if (rectInfo) {
  61423. rectInfo.freeContent();
  61424. }
  61425. };
  61426. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  61427. /**
  61428. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  61429. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  61430. * @returns {}
  61431. */
  61432. get: function () {
  61433. return this._rectPackingMap.freeSpace;
  61434. },
  61435. enumerable: true,
  61436. configurable: true
  61437. });
  61438. /**
  61439. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  61440. * 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.
  61441. * Don't forget to call unbindTexture when you're done rendering
  61442. * @param rect the zone to render to
  61443. * @param clear true to clear the portion's color/depth data
  61444. */
  61445. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  61446. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  61447. };
  61448. /**
  61449. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  61450. * 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.
  61451. * Don't forget to call unbindTexture when you're done rendering
  61452. * @param pos the position into the texture
  61453. * @param size the portion to fit the clip space to
  61454. * @param clear true to clear the portion's color/depth data
  61455. */
  61456. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  61457. var engine = this.getScene().getEngine();
  61458. engine.bindFramebuffer(this._texture);
  61459. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  61460. if (clear) {
  61461. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  61462. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  61463. }
  61464. };
  61465. /**
  61466. * Unbind the texture map from the rendering engine.
  61467. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  61468. * @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.
  61469. */
  61470. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  61471. // Dump ?
  61472. if (dumpForDebug) {
  61473. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  61474. }
  61475. var engine = this.getScene().getEngine();
  61476. if (this._replacedViewport) {
  61477. engine.setViewport(this._replacedViewport);
  61478. this._replacedViewport = null;
  61479. }
  61480. engine.unBindFramebuffer(this._texture);
  61481. };
  61482. Object.defineProperty(MapTexture.prototype, "canRescale", {
  61483. get: function () {
  61484. return false;
  61485. },
  61486. enumerable: true,
  61487. configurable: true
  61488. });
  61489. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  61490. // Anyway, there's not much point to use this method for this kind of texture I guess
  61491. MapTexture.prototype.clone = function () {
  61492. return null;
  61493. };
  61494. return MapTexture;
  61495. }(BABYLON.Texture));
  61496. BABYLON.MapTexture = MapTexture;
  61497. })(BABYLON || (BABYLON = {}));
  61498. //# sourceMappingURL=babylon.mapTexture.js.map
  61499. var BABYLON;
  61500. (function (BABYLON) {
  61501. /**
  61502. * This class describe a rectangle that were added to the map.
  61503. * You have access to its coordinates either in pixel or normalized (UV)
  61504. */
  61505. var PackedRect = (function () {
  61506. function PackedRect(root, parent, pos, size) {
  61507. this._pos = pos;
  61508. this._size = size;
  61509. this._root = root;
  61510. this._parent = parent;
  61511. this._contentSize = null;
  61512. this._bottomNode = null;
  61513. this._leftNode = null;
  61514. this._initialSize = null;
  61515. this._rightNode = null;
  61516. }
  61517. Object.defineProperty(PackedRect.prototype, "pos", {
  61518. /**
  61519. * @returns the position of this node into the map
  61520. */
  61521. get: function () {
  61522. return this._pos;
  61523. },
  61524. enumerable: true,
  61525. configurable: true
  61526. });
  61527. Object.defineProperty(PackedRect.prototype, "contentSize", {
  61528. /**
  61529. * @returns the size of the rectangle this node handles
  61530. */
  61531. get: function () {
  61532. return this._contentSize;
  61533. },
  61534. enumerable: true,
  61535. configurable: true
  61536. });
  61537. /**
  61538. * Retrieve the inner position (considering the margin) and stores it into the res object
  61539. * @param res must be a valid Vector2 that will contain the inner position after this call
  61540. */
  61541. PackedRect.prototype.getInnerPosToRef = function (res) {
  61542. var m = this._root._margin;
  61543. res.x = this._pos.x + m;
  61544. res.y = this._pos.y + m;
  61545. };
  61546. /**
  61547. * Retrieve the inner size (considering the margin) and stores it into the res object
  61548. * @param res must be a valid Size that will contain the inner size after this call
  61549. */
  61550. PackedRect.prototype.getInnerSizeToRef = function (res) {
  61551. var m = this._root._margin;
  61552. res.width = this._contentSize.width - (m * 2);
  61553. res.height = this._contentSize.height - (m * 2);
  61554. };
  61555. Object.defineProperty(PackedRect.prototype, "UVs", {
  61556. /**
  61557. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  61558. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  61559. */
  61560. get: function () {
  61561. if (!this._contentSize) {
  61562. throw new Error("Can't compute UVs for this object because it's nor allocated");
  61563. }
  61564. return this.getUVsForCustomSize(this._contentSize);
  61565. },
  61566. enumerable: true,
  61567. configurable: true
  61568. });
  61569. /**
  61570. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  61571. * and then using only a part of the PackRect.
  61572. * This method will return the UVs for this part by given the custom size of what you really use
  61573. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  61574. */
  61575. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  61576. var mainWidth = this._root._size.width;
  61577. var mainHeight = this._root._size.height;
  61578. var margin = this._root._margin;
  61579. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  61580. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  61581. var uvs = new Array();
  61582. uvs.push(topLeft);
  61583. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  61584. uvs.push(rightBottom);
  61585. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  61586. return uvs;
  61587. };
  61588. /**
  61589. * Free this rectangle from the map.
  61590. * Call this method when you no longer need the rectangle to be in the map.
  61591. */
  61592. PackedRect.prototype.freeContent = function () {
  61593. if (!this.contentSize) {
  61594. return;
  61595. }
  61596. this._contentSize = null;
  61597. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  61598. this.attemptDefrag();
  61599. };
  61600. Object.defineProperty(PackedRect.prototype, "isUsed", {
  61601. get: function () {
  61602. return this._contentSize != null || this._leftNode != null;
  61603. },
  61604. enumerable: true,
  61605. configurable: true
  61606. });
  61607. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  61608. var node = this.findNode(contentSize);
  61609. // Not enough space...
  61610. if (!node) {
  61611. return null;
  61612. }
  61613. node.splitNode(contentSize);
  61614. return node;
  61615. };
  61616. PackedRect.prototype.findNode = function (size) {
  61617. var resNode = null;
  61618. var margin = this._root._margin * 2;
  61619. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  61620. if (this.isUsed) {
  61621. if (this._leftNode) {
  61622. resNode = this._leftNode.findNode(size);
  61623. }
  61624. if (!resNode && this._rightNode) {
  61625. resNode = this._rightNode.findNode(size);
  61626. }
  61627. if (!resNode && this._bottomNode) {
  61628. resNode = this._bottomNode.findNode(size);
  61629. }
  61630. }
  61631. else if (this._initialSize) {
  61632. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  61633. resNode = this;
  61634. }
  61635. else {
  61636. return null;
  61637. }
  61638. }
  61639. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  61640. resNode = this;
  61641. }
  61642. return resNode;
  61643. };
  61644. PackedRect.prototype.splitNode = function (contentSize) {
  61645. var cs = PackedRect.TpsSize;
  61646. var margin = this._root._margin * 2;
  61647. cs.copyFrom(contentSize);
  61648. cs.width += margin;
  61649. cs.height += margin;
  61650. // 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)
  61651. if (!this._contentSize && this._initialSize) {
  61652. this._contentSize = cs.clone();
  61653. 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));
  61654. return this._leftNode.splitNode(contentSize);
  61655. }
  61656. else {
  61657. this._contentSize = cs.clone();
  61658. this._initialSize = cs.clone();
  61659. if (cs.width !== this._size.width) {
  61660. 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));
  61661. }
  61662. if (cs.height !== this._size.height) {
  61663. 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));
  61664. }
  61665. return this;
  61666. }
  61667. };
  61668. PackedRect.prototype.attemptDefrag = function () {
  61669. if (!this.isUsed && this.isRecursiveFree) {
  61670. this.clearNode();
  61671. if (this._parent) {
  61672. this._parent.attemptDefrag();
  61673. }
  61674. }
  61675. };
  61676. PackedRect.prototype.clearNode = function () {
  61677. this._initialSize = null;
  61678. this._rightNode = null;
  61679. this._bottomNode = null;
  61680. };
  61681. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  61682. get: function () {
  61683. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  61684. },
  61685. enumerable: true,
  61686. configurable: true
  61687. });
  61688. PackedRect.prototype.evalFreeSize = function (size) {
  61689. var levelSize = 0;
  61690. if (!this.isUsed) {
  61691. var margin = this._root._margin;
  61692. var is = this._initialSize;
  61693. if (is) {
  61694. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  61695. }
  61696. else {
  61697. var size_1 = this._size;
  61698. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  61699. }
  61700. }
  61701. if (this._rightNode) {
  61702. levelSize += this._rightNode.evalFreeSize(0);
  61703. }
  61704. if (this._bottomNode) {
  61705. levelSize += this._bottomNode.evalFreeSize(0);
  61706. }
  61707. return levelSize + size;
  61708. };
  61709. return PackedRect;
  61710. }());
  61711. PackedRect.TpsSize = BABYLON.Size.Zero();
  61712. BABYLON.PackedRect = PackedRect;
  61713. /**
  61714. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  61715. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  61716. * 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.
  61717. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  61718. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  61719. */
  61720. var RectPackingMap = (function (_super) {
  61721. __extends(RectPackingMap, _super);
  61722. /**
  61723. * Create an instance of the object with a dimension using the given size
  61724. * @param size The dimension of the rectangle that will contain all the sub ones.
  61725. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  61726. */
  61727. function RectPackingMap(size, margin) {
  61728. if (margin === void 0) { margin = 0; }
  61729. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  61730. _this._margin = margin;
  61731. _this._root = _this;
  61732. return _this;
  61733. }
  61734. /**
  61735. * Add a rectangle, finding the best location to store it into the map
  61736. * @param size the dimension of the rectangle to store
  61737. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  61738. */
  61739. RectPackingMap.prototype.addRect = function (size) {
  61740. var node = this.findAndSplitNode(size);
  61741. return node;
  61742. };
  61743. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  61744. /**
  61745. * Return the current space free normalized between [0;1]
  61746. * @returns {}
  61747. */
  61748. get: function () {
  61749. var freeSize = 0;
  61750. freeSize = this.evalFreeSize(freeSize);
  61751. return freeSize / (this._size.width * this._size.height);
  61752. },
  61753. enumerable: true,
  61754. configurable: true
  61755. });
  61756. return RectPackingMap;
  61757. }(PackedRect));
  61758. BABYLON.RectPackingMap = RectPackingMap;
  61759. })(BABYLON || (BABYLON = {}));
  61760. //# sourceMappingURL=babylon.rectPackingMap.js.map
  61761. var BABYLON;
  61762. (function (BABYLON) {
  61763. var DynamicFloatArrayElementInfo = (function () {
  61764. function DynamicFloatArrayElementInfo() {
  61765. }
  61766. return DynamicFloatArrayElementInfo;
  61767. }());
  61768. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  61769. /**
  61770. * 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.
  61771. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  61772. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  61773. * 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.
  61774. * 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.
  61775. * 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".
  61776. */
  61777. var DynamicFloatArray = (function () {
  61778. /**
  61779. * Construct an instance of the dynamic float array
  61780. * @param stride size of one element in float (i.e. not bytes!)
  61781. * @param initialElementCount the number of available entries at construction
  61782. */
  61783. function DynamicFloatArray(stride, initialElementCount) {
  61784. this.compareValueOffset = null;
  61785. this.sortingAscending = true;
  61786. this._stride = stride;
  61787. this.buffer = new Float32Array(stride * initialElementCount);
  61788. this._lastUsed = 0;
  61789. this._firstFree = 0;
  61790. this._allEntries = new Array(initialElementCount);
  61791. this._freeEntries = new Array(initialElementCount);
  61792. for (var i = 0; i < initialElementCount; i++) {
  61793. var element = new DynamicFloatArrayElementInfo();
  61794. element.offset = i * stride;
  61795. this._allEntries[i] = element;
  61796. this._freeEntries[initialElementCount - i - 1] = element;
  61797. }
  61798. }
  61799. /**
  61800. * Allocate an element in the array.
  61801. * @return the element info instance that contains the offset into the main buffer of the element's location.
  61802. * Beware, this offset may change when you call pack()
  61803. */
  61804. DynamicFloatArray.prototype.allocElement = function () {
  61805. if (this._freeEntries.length === 0) {
  61806. this._growBuffer();
  61807. }
  61808. var el = this._freeEntries.pop();
  61809. this._lastUsed = Math.max(el.offset, this._lastUsed);
  61810. if (el.offset === this._firstFree) {
  61811. if (this._freeEntries.length > 0) {
  61812. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  61813. }
  61814. else {
  61815. this._firstFree += this._stride;
  61816. }
  61817. }
  61818. return el;
  61819. };
  61820. /**
  61821. * Free the element corresponding to the given element info
  61822. * @param elInfo the element that describe the allocated element
  61823. */
  61824. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  61825. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  61826. this._freeEntries.push(elInfo);
  61827. };
  61828. /**
  61829. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  61830. * 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().
  61831. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  61832. */
  61833. DynamicFloatArray.prototype.pack = function () {
  61834. // no free slot? no need to pack
  61835. if (this._freeEntries.length === 0) {
  61836. return this.buffer;
  61837. }
  61838. // If the buffer is already packed the last used will always be lower than the first free
  61839. // 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.
  61840. if (this._lastUsed < this._firstFree) {
  61841. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  61842. return elementsBuffer_1;
  61843. }
  61844. var s = this._stride;
  61845. // 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
  61846. var lastFree = new DynamicFloatArrayElementInfo();
  61847. lastFree.offset = this.totalElementCount * s;
  61848. this._freeEntries.push(lastFree);
  61849. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  61850. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  61851. var firstFreeSlotOffset = sortedFree[0].offset;
  61852. var freeZoneSize = 1;
  61853. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  61854. var prevOffset = sortedFree[0].offset;
  61855. for (var i = 1; i < sortedFree.length; i++) {
  61856. // 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
  61857. if (firstFreeSlotOffset >= occupiedZoneSize) {
  61858. break;
  61859. }
  61860. var curFree = sortedFree[i];
  61861. var curOffset = curFree.offset;
  61862. // Compute the distance between this offset and the previous
  61863. var distance = curOffset - prevOffset;
  61864. // If the distance is the stride size, they are adjacent, it good, move to the next
  61865. if (distance === s) {
  61866. // Free zone is one element bigger
  61867. ++freeZoneSize;
  61868. // as we're about to iterate to the next, the cur becomes the previous...
  61869. prevOffset = curOffset;
  61870. continue;
  61871. }
  61872. // Distance is bigger, which means there's x element between the previous free and this one
  61873. var usedRange = (distance / s) - 1;
  61874. // Two cases the free zone is smaller than the data to move or bigger
  61875. // Copy what can fit in the free zone
  61876. var curMoveOffset = curOffset - s;
  61877. var copyCount = Math.min(freeZoneSize, usedRange);
  61878. for (var j = 0; j < copyCount; j++) {
  61879. var freeI = firstFreeSlotOffset / s;
  61880. var curI = curMoveOffset / s;
  61881. var moveEl = sortedAll[curI];
  61882. this._moveElement(moveEl, firstFreeSlotOffset);
  61883. var replacedEl = sortedAll[freeI];
  61884. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  61885. replacedEl.offset = curMoveOffset;
  61886. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  61887. sortedAll[freeI] = moveEl;
  61888. sortedAll[curI] = replacedEl;
  61889. curMoveOffset -= s;
  61890. firstFreeSlotOffset += s;
  61891. }
  61892. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  61893. if (freeZoneSize <= usedRange) {
  61894. firstFreeSlotOffset = curMoveOffset + s;
  61895. freeZoneSize = 1 + copyCount;
  61896. }
  61897. else {
  61898. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  61899. }
  61900. // as we're about to iterate to the next, the cur becomes the previous...
  61901. prevOffset = curOffset;
  61902. }
  61903. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  61904. this._lastUsed = firstFreeSlotOffset - s;
  61905. this._firstFree = firstFreeSlotOffset;
  61906. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  61907. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  61908. this._allEntries = sortedAll;
  61909. return elementsBuffer;
  61910. };
  61911. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  61912. for (var i = 0; i < this._stride; i++) {
  61913. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  61914. }
  61915. element.offset = destOffset;
  61916. };
  61917. DynamicFloatArray.prototype._growBuffer = function () {
  61918. // Allocate the new buffer with 50% more entries, copy the content of the current one
  61919. var newElCount = Math.floor(this.totalElementCount * 1.5);
  61920. var newBuffer = new Float32Array(newElCount * this._stride);
  61921. newBuffer.set(this.buffer);
  61922. var curCount = this.totalElementCount;
  61923. var addedCount = newElCount - this.totalElementCount;
  61924. for (var i = 0; i < addedCount; i++) {
  61925. var element = new DynamicFloatArrayElementInfo();
  61926. element.offset = (curCount + i) * this.stride;
  61927. this._allEntries.push(element);
  61928. this._freeEntries[addedCount - i - 1] = element;
  61929. }
  61930. this._firstFree = curCount * this.stride;
  61931. this.buffer = newBuffer;
  61932. };
  61933. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  61934. /**
  61935. * Get the total count of entries that can fit in the current buffer
  61936. * @returns the elements count
  61937. */
  61938. get: function () {
  61939. return this._allEntries.length;
  61940. },
  61941. enumerable: true,
  61942. configurable: true
  61943. });
  61944. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  61945. /**
  61946. * Get the count of free entries that can still be allocated without resizing the buffer
  61947. * @returns the free elements count
  61948. */
  61949. get: function () {
  61950. return this._freeEntries.length;
  61951. },
  61952. enumerable: true,
  61953. configurable: true
  61954. });
  61955. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  61956. /**
  61957. * Get the count of allocated elements
  61958. * @returns the allocated elements count
  61959. */
  61960. get: function () {
  61961. return this._allEntries.length - this._freeEntries.length;
  61962. },
  61963. enumerable: true,
  61964. configurable: true
  61965. });
  61966. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  61967. /**
  61968. * Return the size of one element in float
  61969. * @returns the size in float
  61970. */
  61971. get: function () {
  61972. return this._stride;
  61973. },
  61974. enumerable: true,
  61975. configurable: true
  61976. });
  61977. DynamicFloatArray.prototype.sort = function () {
  61978. var _this = this;
  61979. if (!this.compareValueOffset) {
  61980. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  61981. }
  61982. var count = this.usedElementCount;
  61983. // Do we have to (re)create the sort table?
  61984. if (!this._sortTable || this._sortTable.length < count) {
  61985. // 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...
  61986. var newCount = Math.min(this.totalElementCount, count * 2);
  61987. this._sortTable = new Array(newCount);
  61988. }
  61989. if (!this._sortedTable || this._sortedTable.length !== count) {
  61990. this._sortedTable = new Array(count);
  61991. }
  61992. // Because, you know...
  61993. this.pack();
  61994. //let stride = this.stride;
  61995. //for (let i = 0; i < count; i++) {
  61996. // let si = this._sortTable[i];
  61997. // if (!si) {
  61998. // si = new SortInfo();
  61999. // this._sortTable[i] = si;
  62000. // }
  62001. // si.entry = this._allEntries[i];
  62002. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  62003. // si.swapedOffset = null;
  62004. // this._sortedTable[i] = si;
  62005. //}
  62006. var curOffset = 0;
  62007. var stride = this.stride;
  62008. for (var i = 0; i < count; i++, curOffset += stride) {
  62009. var si = this._sortTable[i];
  62010. if (!si) {
  62011. si = new SortInfo();
  62012. this._sortTable[i] = si;
  62013. }
  62014. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  62015. si.offset = curOffset;
  62016. si.swapedOffset = null;
  62017. this._sortedTable[i] = si;
  62018. }
  62019. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  62020. if (this.sortingAscending) {
  62021. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  62022. }
  62023. else {
  62024. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  62025. }
  62026. var swapElements = function (src, dst) {
  62027. for (var i = 0; i < stride; i++) {
  62028. var tps = _this.buffer[dst + i];
  62029. _this.buffer[dst + i] = _this.buffer[src + i];
  62030. _this.buffer[src + i] = tps;
  62031. }
  62032. };
  62033. // 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:
  62034. // 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),
  62035. // and I still want something with a good algorithm complexity.
  62036. // 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,
  62037. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  62038. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  62039. // 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
  62040. // until we find a SortInfo object without a swapedOffset which means we got the right location
  62041. // 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
  62042. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  62043. for (var i = 0; i < count; i++) {
  62044. // Get the element to move
  62045. var sourceSI = this._sortedTable[i];
  62046. var destSI = this._sortTable[i];
  62047. var sourceOff = sourceSI.offset;
  62048. // If the source changed location, find the new one
  62049. if (sourceSI.swapedOffset) {
  62050. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  62051. var curSI = sourceSI;
  62052. while (curSI.swapedOffset) {
  62053. curSI = this._sortTable[curSI.swapedOffset / stride];
  62054. }
  62055. // Finally get the right location
  62056. sourceOff = curSI.offset;
  62057. }
  62058. // Tag the element being replaced with its new location
  62059. destSI.swapedOffset = sourceOff;
  62060. // Swap elements (only if needed)
  62061. if (sourceOff !== destSI.offset) {
  62062. swapElements(sourceOff, destSI.offset);
  62063. }
  62064. // Update the offset in the corresponding DFAE
  62065. //sourceSI.entry.offset = destSI.entry.offset;
  62066. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  62067. }
  62068. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  62069. return true;
  62070. };
  62071. return DynamicFloatArray;
  62072. }());
  62073. BABYLON.DynamicFloatArray = DynamicFloatArray;
  62074. var SortInfo = (function () {
  62075. function SortInfo() {
  62076. this.compareData = this.offset = this.swapedOffset = null;
  62077. }
  62078. return SortInfo;
  62079. }());
  62080. })(BABYLON || (BABYLON = {}));
  62081. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  62082. var BABYLON;
  62083. (function (BABYLON) {
  62084. var serializedGeometries = [];
  62085. var serializeGeometry = function (geometry, serializationGeometries) {
  62086. if (serializedGeometries[geometry.id]) {
  62087. return;
  62088. }
  62089. if (geometry.doNotSerialize) {
  62090. return;
  62091. }
  62092. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  62093. serializationGeometries.boxes.push(geometry.serialize());
  62094. }
  62095. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  62096. serializationGeometries.spheres.push(geometry.serialize());
  62097. }
  62098. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  62099. serializationGeometries.cylinders.push(geometry.serialize());
  62100. }
  62101. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  62102. serializationGeometries.toruses.push(geometry.serialize());
  62103. }
  62104. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  62105. serializationGeometries.grounds.push(geometry.serialize());
  62106. }
  62107. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  62108. serializationGeometries.planes.push(geometry.serialize());
  62109. }
  62110. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  62111. serializationGeometries.torusKnots.push(geometry.serialize());
  62112. }
  62113. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  62114. throw new Error("Unknown primitive type");
  62115. }
  62116. else {
  62117. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  62118. }
  62119. serializedGeometries[geometry.id] = true;
  62120. };
  62121. var serializeMesh = function (mesh, serializationScene) {
  62122. var serializationObject = {};
  62123. // Geometry
  62124. var geometry = mesh._geometry;
  62125. if (geometry) {
  62126. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  62127. // 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
  62128. serializeGeometry(geometry, serializationScene.geometries);
  62129. }
  62130. }
  62131. // Custom
  62132. if (mesh.serialize) {
  62133. mesh.serialize(serializationObject);
  62134. }
  62135. return serializationObject;
  62136. };
  62137. var finalizeSingleMesh = function (mesh, serializationObject) {
  62138. //only works if the mesh is already loaded
  62139. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  62140. //serialize material
  62141. if (mesh.material) {
  62142. if (mesh.material instanceof BABYLON.StandardMaterial) {
  62143. serializationObject.materials = serializationObject.materials || [];
  62144. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  62145. serializationObject.materials.push(mesh.material.serialize());
  62146. }
  62147. }
  62148. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  62149. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  62150. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  62151. serializationObject.multiMaterials.push(mesh.material.serialize());
  62152. }
  62153. }
  62154. }
  62155. //serialize geometry
  62156. var geometry = mesh._geometry;
  62157. if (geometry) {
  62158. if (!serializationObject.geometries) {
  62159. serializationObject.geometries = {};
  62160. serializationObject.geometries.boxes = [];
  62161. serializationObject.geometries.spheres = [];
  62162. serializationObject.geometries.cylinders = [];
  62163. serializationObject.geometries.toruses = [];
  62164. serializationObject.geometries.grounds = [];
  62165. serializationObject.geometries.planes = [];
  62166. serializationObject.geometries.torusKnots = [];
  62167. serializationObject.geometries.vertexData = [];
  62168. }
  62169. serializeGeometry(geometry, serializationObject.geometries);
  62170. }
  62171. // Skeletons
  62172. if (mesh.skeleton) {
  62173. serializationObject.skeletons = serializationObject.skeletons || [];
  62174. serializationObject.skeletons.push(mesh.skeleton.serialize());
  62175. }
  62176. //serialize the actual mesh
  62177. serializationObject.meshes = serializationObject.meshes || [];
  62178. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  62179. }
  62180. };
  62181. var SceneSerializer = (function () {
  62182. function SceneSerializer() {
  62183. }
  62184. SceneSerializer.ClearCache = function () {
  62185. serializedGeometries = [];
  62186. };
  62187. SceneSerializer.Serialize = function (scene) {
  62188. var serializationObject = {};
  62189. SceneSerializer.ClearCache();
  62190. // Scene
  62191. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  62192. serializationObject.autoClear = scene.autoClear;
  62193. serializationObject.clearColor = scene.clearColor.asArray();
  62194. serializationObject.ambientColor = scene.ambientColor.asArray();
  62195. serializationObject.gravity = scene.gravity.asArray();
  62196. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  62197. serializationObject.workerCollisions = scene.workerCollisions;
  62198. // Fog
  62199. if (scene.fogMode && scene.fogMode !== 0) {
  62200. serializationObject.fogMode = scene.fogMode;
  62201. serializationObject.fogColor = scene.fogColor.asArray();
  62202. serializationObject.fogStart = scene.fogStart;
  62203. serializationObject.fogEnd = scene.fogEnd;
  62204. serializationObject.fogDensity = scene.fogDensity;
  62205. }
  62206. //Physics
  62207. if (scene.isPhysicsEnabled()) {
  62208. serializationObject.physicsEnabled = true;
  62209. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  62210. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  62211. }
  62212. // Metadata
  62213. if (scene.metadata) {
  62214. serializationObject.metadata = scene.metadata;
  62215. }
  62216. // Morph targets
  62217. serializationObject.morphTargetManagers = [];
  62218. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  62219. var abstractMesh = _a[_i];
  62220. var manager = abstractMesh.morphTargetManager;
  62221. if (manager) {
  62222. serializationObject.morphTargetManagers.push(manager.serialize());
  62223. }
  62224. }
  62225. // Lights
  62226. serializationObject.lights = [];
  62227. var index;
  62228. var light;
  62229. for (index = 0; index < scene.lights.length; index++) {
  62230. light = scene.lights[index];
  62231. if (!light.doNotSerialize) {
  62232. serializationObject.lights.push(light.serialize());
  62233. }
  62234. }
  62235. // Cameras
  62236. serializationObject.cameras = [];
  62237. for (index = 0; index < scene.cameras.length; index++) {
  62238. var camera = scene.cameras[index];
  62239. if (!camera.doNotSerialize) {
  62240. serializationObject.cameras.push(camera.serialize());
  62241. }
  62242. }
  62243. if (scene.activeCamera) {
  62244. serializationObject.activeCameraID = scene.activeCamera.id;
  62245. }
  62246. // Animations
  62247. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  62248. // Materials
  62249. serializationObject.materials = [];
  62250. serializationObject.multiMaterials = [];
  62251. var material;
  62252. for (index = 0; index < scene.materials.length; index++) {
  62253. material = scene.materials[index];
  62254. if (!material.doNotSerialize) {
  62255. serializationObject.materials.push(material.serialize());
  62256. }
  62257. }
  62258. // MultiMaterials
  62259. serializationObject.multiMaterials = [];
  62260. for (index = 0; index < scene.multiMaterials.length; index++) {
  62261. var multiMaterial = scene.multiMaterials[index];
  62262. serializationObject.multiMaterials.push(multiMaterial.serialize());
  62263. }
  62264. // Skeletons
  62265. serializationObject.skeletons = [];
  62266. for (index = 0; index < scene.skeletons.length; index++) {
  62267. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  62268. }
  62269. // Geometries
  62270. serializationObject.geometries = {};
  62271. serializationObject.geometries.boxes = [];
  62272. serializationObject.geometries.spheres = [];
  62273. serializationObject.geometries.cylinders = [];
  62274. serializationObject.geometries.toruses = [];
  62275. serializationObject.geometries.grounds = [];
  62276. serializationObject.geometries.planes = [];
  62277. serializationObject.geometries.torusKnots = [];
  62278. serializationObject.geometries.vertexData = [];
  62279. serializedGeometries = [];
  62280. var geometries = scene.getGeometries();
  62281. for (index = 0; index < geometries.length; index++) {
  62282. var geometry = geometries[index];
  62283. if (geometry.isReady()) {
  62284. serializeGeometry(geometry, serializationObject.geometries);
  62285. }
  62286. }
  62287. // Meshes
  62288. serializationObject.meshes = [];
  62289. for (index = 0; index < scene.meshes.length; index++) {
  62290. var abstractMesh = scene.meshes[index];
  62291. if (abstractMesh instanceof BABYLON.Mesh) {
  62292. var mesh = abstractMesh;
  62293. if (!mesh.doNotSerialize) {
  62294. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  62295. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  62296. }
  62297. }
  62298. }
  62299. }
  62300. // Particles Systems
  62301. serializationObject.particleSystems = [];
  62302. for (index = 0; index < scene.particleSystems.length; index++) {
  62303. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  62304. }
  62305. // Lens flares
  62306. serializationObject.lensFlareSystems = [];
  62307. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  62308. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  62309. }
  62310. // Shadows
  62311. serializationObject.shadowGenerators = [];
  62312. for (index = 0; index < scene.lights.length; index++) {
  62313. light = scene.lights[index];
  62314. var shadowGenerator = light.getShadowGenerator();
  62315. // Only support serialization for official generator so far.
  62316. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  62317. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  62318. }
  62319. }
  62320. // Action Manager
  62321. if (scene.actionManager) {
  62322. serializationObject.actions = scene.actionManager.serialize("scene");
  62323. }
  62324. // Audio
  62325. serializationObject.sounds = [];
  62326. for (index = 0; index < scene.soundTracks.length; index++) {
  62327. var soundtrack = scene.soundTracks[index];
  62328. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  62329. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  62330. }
  62331. }
  62332. return serializationObject;
  62333. };
  62334. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  62335. if (withParents === void 0) { withParents = false; }
  62336. if (withChildren === void 0) { withChildren = false; }
  62337. var serializationObject = {};
  62338. SceneSerializer.ClearCache();
  62339. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  62340. if (withParents || withChildren) {
  62341. //deliberate for loop! not for each, appended should be processed as well.
  62342. for (var i = 0; i < toSerialize.length; ++i) {
  62343. if (withChildren) {
  62344. toSerialize[i].getDescendants().forEach(function (node) {
  62345. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  62346. toSerialize.push(node);
  62347. }
  62348. });
  62349. }
  62350. //make sure the array doesn't contain the object already
  62351. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  62352. toSerialize.push(toSerialize[i].parent);
  62353. }
  62354. }
  62355. }
  62356. toSerialize.forEach(function (mesh) {
  62357. finalizeSingleMesh(mesh, serializationObject);
  62358. });
  62359. return serializationObject;
  62360. };
  62361. return SceneSerializer;
  62362. }());
  62363. BABYLON.SceneSerializer = SceneSerializer;
  62364. })(BABYLON || (BABYLON = {}));
  62365. //# sourceMappingURL=babylon.sceneSerializer.js.map
  62366. var BABYLON;
  62367. (function (BABYLON) {
  62368. var ReflectionProbe = (function () {
  62369. function ReflectionProbe(name, size, scene, generateMipMaps) {
  62370. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62371. var _this = this;
  62372. this.name = name;
  62373. this._viewMatrix = BABYLON.Matrix.Identity();
  62374. this._target = BABYLON.Vector3.Zero();
  62375. this._add = BABYLON.Vector3.Zero();
  62376. this.invertYAxis = false;
  62377. this.position = BABYLON.Vector3.Zero();
  62378. this._scene = scene;
  62379. this._scene.reflectionProbes.push(this);
  62380. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  62381. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  62382. switch (faceIndex) {
  62383. case 0:
  62384. _this._add.copyFromFloats(1, 0, 0);
  62385. break;
  62386. case 1:
  62387. _this._add.copyFromFloats(-1, 0, 0);
  62388. break;
  62389. case 2:
  62390. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  62391. break;
  62392. case 3:
  62393. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  62394. break;
  62395. case 4:
  62396. _this._add.copyFromFloats(0, 0, 1);
  62397. break;
  62398. case 5:
  62399. _this._add.copyFromFloats(0, 0, -1);
  62400. break;
  62401. }
  62402. if (_this._attachedMesh) {
  62403. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  62404. }
  62405. _this.position.addToRef(_this._add, _this._target);
  62406. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  62407. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  62408. });
  62409. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  62410. scene.updateTransformMatrix(true);
  62411. });
  62412. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  62413. }
  62414. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  62415. get: function () {
  62416. return this._renderTargetTexture.samples;
  62417. },
  62418. set: function (value) {
  62419. this._renderTargetTexture.samples = value;
  62420. },
  62421. enumerable: true,
  62422. configurable: true
  62423. });
  62424. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  62425. get: function () {
  62426. return this._renderTargetTexture.refreshRate;
  62427. },
  62428. set: function (value) {
  62429. this._renderTargetTexture.refreshRate = value;
  62430. },
  62431. enumerable: true,
  62432. configurable: true
  62433. });
  62434. ReflectionProbe.prototype.getScene = function () {
  62435. return this._scene;
  62436. };
  62437. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  62438. get: function () {
  62439. return this._renderTargetTexture;
  62440. },
  62441. enumerable: true,
  62442. configurable: true
  62443. });
  62444. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  62445. get: function () {
  62446. return this._renderTargetTexture.renderList;
  62447. },
  62448. enumerable: true,
  62449. configurable: true
  62450. });
  62451. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  62452. this._attachedMesh = mesh;
  62453. };
  62454. ReflectionProbe.prototype.dispose = function () {
  62455. var index = this._scene.reflectionProbes.indexOf(this);
  62456. if (index !== -1) {
  62457. // Remove from the scene if found
  62458. this._scene.reflectionProbes.splice(index, 1);
  62459. }
  62460. if (this._renderTargetTexture) {
  62461. this._renderTargetTexture.dispose();
  62462. this._renderTargetTexture = null;
  62463. }
  62464. };
  62465. return ReflectionProbe;
  62466. }());
  62467. BABYLON.ReflectionProbe = ReflectionProbe;
  62468. })(BABYLON || (BABYLON = {}));
  62469. //# sourceMappingURL=babylon.reflectionProbe.js.map
  62470. var BABYLON;
  62471. (function (BABYLON) {
  62472. var Layer = (function () {
  62473. function Layer(name, imgUrl, scene, isBackground, color) {
  62474. this.name = name;
  62475. this.scale = new BABYLON.Vector2(1, 1);
  62476. this.offset = new BABYLON.Vector2(0, 0);
  62477. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  62478. this._vertexBuffers = {};
  62479. // Events
  62480. /**
  62481. * An event triggered when the layer is disposed.
  62482. * @type {BABYLON.Observable}
  62483. */
  62484. this.onDisposeObservable = new BABYLON.Observable();
  62485. /**
  62486. * An event triggered before rendering the scene
  62487. * @type {BABYLON.Observable}
  62488. */
  62489. this.onBeforeRenderObservable = new BABYLON.Observable();
  62490. /**
  62491. * An event triggered after rendering the scene
  62492. * @type {BABYLON.Observable}
  62493. */
  62494. this.onAfterRenderObservable = new BABYLON.Observable();
  62495. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  62496. this.isBackground = isBackground === undefined ? true : isBackground;
  62497. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  62498. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  62499. this._scene.layers.push(this);
  62500. var engine = scene.getEngine();
  62501. // VBO
  62502. var vertices = [];
  62503. vertices.push(1, 1);
  62504. vertices.push(-1, 1);
  62505. vertices.push(-1, -1);
  62506. vertices.push(1, -1);
  62507. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  62508. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  62509. // Indices
  62510. var indices = [];
  62511. indices.push(0);
  62512. indices.push(1);
  62513. indices.push(2);
  62514. indices.push(0);
  62515. indices.push(2);
  62516. indices.push(3);
  62517. this._indexBuffer = engine.createIndexBuffer(indices);
  62518. // Effects
  62519. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  62520. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  62521. }
  62522. Object.defineProperty(Layer.prototype, "onDispose", {
  62523. set: function (callback) {
  62524. if (this._onDisposeObserver) {
  62525. this.onDisposeObservable.remove(this._onDisposeObserver);
  62526. }
  62527. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  62528. },
  62529. enumerable: true,
  62530. configurable: true
  62531. });
  62532. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  62533. set: function (callback) {
  62534. if (this._onBeforeRenderObserver) {
  62535. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62536. }
  62537. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62538. },
  62539. enumerable: true,
  62540. configurable: true
  62541. });
  62542. Object.defineProperty(Layer.prototype, "onAfterRender", {
  62543. set: function (callback) {
  62544. if (this._onAfterRenderObserver) {
  62545. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62546. }
  62547. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62548. },
  62549. enumerable: true,
  62550. configurable: true
  62551. });
  62552. Layer.prototype.render = function () {
  62553. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  62554. // Check
  62555. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  62556. return;
  62557. var engine = this._scene.getEngine();
  62558. this.onBeforeRenderObservable.notifyObservers(this);
  62559. // Render
  62560. engine.enableEffect(currentEffect);
  62561. engine.setState(false);
  62562. // Texture
  62563. currentEffect.setTexture("textureSampler", this.texture);
  62564. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  62565. // Color
  62566. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  62567. // Scale / offset
  62568. currentEffect.setVector2("offset", this.offset);
  62569. currentEffect.setVector2("scale", this.scale);
  62570. // VBOs
  62571. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  62572. // Draw order
  62573. if (!this.alphaTest) {
  62574. engine.setAlphaMode(this.alphaBlendingMode);
  62575. engine.draw(true, 0, 6);
  62576. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62577. }
  62578. else {
  62579. engine.draw(true, 0, 6);
  62580. }
  62581. this.onAfterRenderObservable.notifyObservers(this);
  62582. };
  62583. Layer.prototype.dispose = function () {
  62584. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62585. if (vertexBuffer) {
  62586. vertexBuffer.dispose();
  62587. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62588. }
  62589. if (this._indexBuffer) {
  62590. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  62591. this._indexBuffer = null;
  62592. }
  62593. if (this.texture) {
  62594. this.texture.dispose();
  62595. this.texture = null;
  62596. }
  62597. // Remove from scene
  62598. var index = this._scene.layers.indexOf(this);
  62599. this._scene.layers.splice(index, 1);
  62600. // Callback
  62601. this.onDisposeObservable.notifyObservers(this);
  62602. this.onDisposeObservable.clear();
  62603. this.onAfterRenderObservable.clear();
  62604. this.onBeforeRenderObservable.clear();
  62605. };
  62606. return Layer;
  62607. }());
  62608. BABYLON.Layer = Layer;
  62609. })(BABYLON || (BABYLON = {}));
  62610. //# sourceMappingURL=babylon.layer.js.map
  62611. 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":"#ifdef BUMP\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=vec3(1.0,1.0,1.0);\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(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}"};
  62612. 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 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"};
  62613. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  62614. module.exports = BABYLON;
  62615. };